|
root / base / usr / src / cmd / auditreduce
auditreduce Plain Text 6635 lines 156.8 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
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
#
# 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 2010 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# Copyright 2019 Joyent, Inc.

TABLEDIR = ../praudit

PROG = auditreduce
SRCS = main.c option.c proc.c time.c token.c regex2.c $(TABLEDIR)/toktable.c
OBJS = main.o option.o proc.o time.o token.o regex2.o toktable.o

include $(SRC)/cmd/Makefile.cmd

TEXT_DOMAIN = SUNW_OST_OSCMD
POFILE = $(PROG).po
MSGFILES = $(SRCS)

CPPFLAGS += -I$(TABLEDIR) -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
LDLIBS += -lnsl -lbsm -lscf -ltsol

CERRWARN += $(CNOWARN_UNINIT)
CERRWARN += -Wno-parentheses

# false positive
SMOFF += strcpy_overflow

.KEEP_STATE:

all: $(PROG)

install: all $(ROOTUSRSBINPROG)

$(PROG): $(OBJS)
	$(LINK.c) -o $(PROG) $(OBJS) $(LDLIBS)
	$(POST_PROCESS)

toktable.o:	$(TABLEDIR)/toktable.c
	$(COMPILE.c) $(TABLEDIR)/toktable.c

$(POFILE): $(MSGFILES)
	$(BUILDPO.msgfiles)

_msg: $(MSGDOMAINPOFILE)

lint: lint_SRCS

clean:
	$(RM) $(OBJS)

include $(SRC)/cmd/Makefile.targ
include $(SRC)/Makefile.msg.targ
/*
 * 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.
 */

#ifndef _AUDITR_H
#define	_AUDITR_H

#ifdef __cplusplus
extern "C" {
#endif

#include <sys/types.h>
#include <stdio.h>
#include <sys/types.h>

#include <grp.h>
#include <pwd.h>
#include <signal.h>
#include <string.h>
#include <values.h>

#include <dirent.h>
#include <sys/errno.h>
#include <sys/file.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <tzfile.h>
#include <sys/resource.h>
#include <netdb.h>
#include <unistd.h>
#include <libgen.h>
#include <stdlib.h>
#include <libscf_priv.h>

#include <bsm/audit.h>
#include <bsm/audit_record.h>
#include <bsm/libbsm.h>

#include <tsol/label.h>

#include "auditrt.h"

/*
 * Flags for on/off code.
 * The release setting would be 0 0 0 1.
 */
#define	AUDIT_PROC_TRACE	0	/* process trace code */
#define	AUDIT_FILE		0	/* file trace code (use -V also) */
#define	AUDIT_REC		0	/* record trace code (very verbose) */
#define	AUDIT_RENAME		1	/* rename output file w/time stamps */

#define	TRUE	1
#define	FALSE	0

#define	FM_ALLDIR	1	/* f_mode in o.c - all dirs in this dir */
#define	FM_ALLFILE	0	/* f_mode in o.c - all audit files in dir */

#define	MAXFILELEN	(MAXPATHLEN+MAXNAMLEN+1)

/*
 * Initial size of a record buffer.
 * Never smaller than (2 * sizeof (short)).
 * If a buffer is too small for the record being read then the
 * current buffer is freed and a large-enough one is allocated.
 */
#define	AUDITBUFSIZE	512	/* size of default record buffer */

/*
 * Controls size of audit_pcbs[] array.
 * INITSIZE is the initial allocation for the array.
 * INC is the growth jump when the array becomes too small.
 */
#define	PCB_INITSIZE	100
#define	PCB_INC		50


/*
 * Memory allocation functions.
 * audit calloc that checks for NULL return
 */
extern void	*a_calloc(int, size_t);

/*
 * Statistical reporting for error conditions.
 */
extern void	audit_stats(void);
extern int	errno;

#ifdef	__cplusplus
}
#endif

#endif /* _AUDITR_H */
/*
 * 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 2010 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_AUDITRD_H
#define	_AUDITRD_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * Global data for auditreduce
 */

/*
 * Message selection options
 */
unsigned short	m_type;		/* 'm' message type */
gid_t	m_groupr;		/* 'g' group-id */
gid_t	m_groupe;		/* 'f' effective group-id */
uid_t	m_usera;		/* 'u' user id */
uid_t	m_usere;		/* 'e' effective user-id */
uid_t	m_userr;		/* 'r' real user-id */
au_asid_t m_sid;		/* 's' session-id */
time_t	m_after;		/* 'a' after a time */
time_t	m_before;		/* 'b' before a time */
audit_state_t mask;		/* used with m_class */
char	*zonename;		/* 'z' zonename */
m_range_t *m_label;		/* 'l' mandatory label range */
int	flags;
int	checkflags;
int	socket_flag;
int	ip_type;
uchar_t	ip_ipv6[16];		/* ipv6 type object */
int	obj_flag;		/* 'o' object type */
int	obj_id;			/* object identifier */
gid_t	obj_group;		/* object group */
uid_t	obj_owner;		/* object owner */
int	subj_id;		/* subject identifier  */
char	ipc_type;		/* 'o' object type - tell what type of IPC */
scf_pattern_t fmri;		/* 'o' fmri value */
uid_t	obj_user;		/* 'o' user value */

/*
 * File selection options
 */
char	*f_machine;		/* 'M' machine (suffix) type */
char	*f_root;		/* 'R' audit root */
char	*f_server;		/* 'S' server */
char	*f_outfile;		/* 'W' output file */
static char	*f_outtemp;	/* 'W' temporary file name */
int	f_all;			/* 'A' all records from a file */
int	f_complete;		/* 'C' only completed files */
int	f_delete;		/* 'D' delete when done */
int	f_quiet;		/* 'Q' sshhhh! */
int	f_verbose;		/* 'V' verbose */
int	f_stdin;		/* '-' read from stdin */
int	f_cmdline;		/* files specified on the command line */
int	new_mode;		/* 'N' new object selection mode */

/*
 * Global error reporting
 */
char	*error_str;		/* current error message */
char	errbuf[256];		/* for creating error messages with sprintf */
char	*ar = "auditreduce:";
static int	root_pid;	/* remember original process's pid */

/*
 * Global control blocks
 */
audit_pcb_t *audit_pcbs; /* ptr to array of pcbs that hold files (fcbs) */

int	pcbsize;		/* size of audit_pcb[] */
int	pcbnum;		/* number of pcbs in audit_pcb[] that are active */

/*
 * Time values
 */
time_t f_start;		/* time of first record written */
time_t f_end;		/* time of last record written */
time_t time_now;	/* time the program began */

/*
 * Global counting vars
 */
int	filenum;		/* number of files to process */

/*
 * Global variable, class of current record being processed.
 */
int global_class;

#ifdef __cplusplus
}
#endif

#endif	/* _AUDITRD_H */
/*
 * 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 2010 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * Copyright 2018 Nexenta Systems, Inc.  All rights reserved.
 */

#ifndef _AUDITRT_H
#define	_AUDITRT_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * Auditreduce data structures.
 */

/*
 * File Control Block
 * Controls a single file.
 * These are held by the pcb's in audit_pcbs[] in a linked list.
 * There is one fcb for each file controlled by the pcb,
 * and all of the files in a list have the same suffix in their names.
 */
struct audit_fcb {
	struct audit_fcb *fcb_next;	/* ptr to next fcb in list */
	int	fcb_flags;	/* flags - see below */
	time_t	fcb_start;	/* start time from filename */
	time_t	fcb_end;	/* end time from filename */
	char	*fcb_suffix;	/* ptr to suffix in fcb_file */
	char	*fcb_name;	/* ptr to name in fcb_file */
	char	fcb_file[1];	/* full path and name string */
};

typedef struct audit_fcb audit_fcb_t;

/*
 * Flags for fcb_flags.
 */
#define	FF_NOTTERM	0x01	/* file is "not_terminated" */
#define	FF_DELETE	0x02	/* we may delete this file if requested */

/*
 * Process Control Block
 * A pcb comes in two types:
 * It controls either:
 *
 * 1.	A single group of pcbs (processes that are lower on the process tree).
 *	These are the pcb's that the process tree is built from.
 *	These are allocated as needed while the process tree is	being built.
 *
 * 2.	A single group of files (fcbs).
 *	All of the files in one pcb have the same suffix in their filename.
 *	They are controlled by the leaf nodes of the process tree.
 *	They are found in audit_pcbs[].
 *	They are initially setup by process_fileopt() when the files to be
 *	processes are gathered together. Then they are parsed out to
 *	the leaf nodes by mfork().
 *	A particular leaf node's range of audit_pcbs[] is determined
 *	in the call to mfork() by the lo and hi paramters.
 */
struct audit_pcb {
	struct audit_pcb *pcb_below;	/* ptr to group of pcb's */
	struct audit_pcb *pcb_next;	/* ptr to next - for list in mproc() */
	int	pcb_procno;	/* subprocess # */
	int	pcb_nrecs;	/* how many records read (current pcb/file) */
	int	pcb_nprecs;	/* how many records put (current pcb/file) */
	int	pcb_flags;	/* flags - see below */
	int	pcb_count;	/* count of active pcb's */
	int	pcb_lo;		/* low index for pcb's */
	int	pcb_hi;		/* hi index for pcb's */
	int	pcb_size;	/* size of current record buffer */
	time_t	pcb_time;	/* time of current record */
	time_t	pcb_otime;	/* time of previous record */
	char	*pcb_rec;	/* ptr to current record buffer */
	char	*pcb_suffix;	/* ptr to suffix name (string) */
	audit_fcb_t *pcb_first;	/* ptr to first fcb_ */
	audit_fcb_t *pcb_last;	/* ptr to last fcb_ */
	audit_fcb_t *pcb_cur;	/* ptr to current fcb_ */
	audit_fcb_t *pcb_dfirst; /* ptr to first fcb_ for deleting */
	audit_fcb_t *pcb_dlast;	/* ptr to last fcb_ for deleting */
	FILE	 *pcb_fpr;	/* read stream */
	FILE	 *pcb_fpw;	/* write stream */
};

typedef struct audit_pcb audit_pcb_t;

/*
 * Flags for pcb_flags
 */
#define	PF_ROOT		0x01	/* current pcb is the root of process tree */
#define	PF_LEAF		0x02	/* current pcb is a leaf of process tree */
#define	PF_USEFILE	0x04	/* current pcb uses files as input, not pipes */

/*
 * Message selection options
 */
#define	M_AFTER		0x0001	/* 'a' after a time */
#define	M_BEFORE	0x0002	/* 'b' before a time */
#define	M_CLASS		0x0004	/* 'c' event class */
#define	M_GROUPE 	0x0008	/* 'f' effective group-id */
#define	M_GROUPR 	0x0010	/* 'g' real group-id */
#define	M_OBJECT	0x0020	/* 'o' object */
#define	M_SUBJECT	0x0040	/* 'j' subject */
#define	M_TYPE		0x0080	/* 'm' event type */
#define	M_USERA		0x0100	/* 'u' audit user */
#define	M_USERE		0x0200	/* 'e' effective user */
#define	M_USERR		0x0400	/* 'r' real user */
#define	M_LABEL		0x0800	/* 'l' mandatory label range */
#define	M_ZONENAME	0x1000	/* 'z' zone name */
#define	M_SID		0x2000	/* 's' session ID */
#define	M_SORF		0x4000	/* success or failure of event */
#define	M_TID		0x8000	/* 't' terminal ID */
/*
 * object types
 */

/* XXX Why is this a bit map?  There can be only one M_OBJECT. */

#define	OBJ_LP		0x00001  /* 'o' lp object */
#define	OBJ_MSG		0x00002  /* 'o' msgq object */
#define	OBJ_PATH	0x00004  /* 'o' file system object */
#define	OBJ_PROC	0x00008  /* 'o' process object */
#define	OBJ_SEM		0x00010  /* 'o' semaphore object */
#define	OBJ_SHM		0x00020  /* 'o' shared memory object */
#define	OBJ_SOCK	0x00040  /* 'o' socket object */
#define	OBJ_FGROUP	0x00080  /* 'o' file group */
#define	OBJ_FOWNER	0x00100  /* 'o' file owner */
#define	OBJ_MSGGROUP	0x00200	 /* 'o' msgq [c]group */
#define	OBJ_MSGOWNER	0x00400  /* 'o' msgq [c]owner */
#define	OBJ_PGROUP	0x00800  /* 'o' process [e]group */
#define	OBJ_POWNER	0x01000  /* 'o' process [e]owner */
#define	OBJ_SEMGROUP	0x02000  /* 'o' semaphore [c]group */
#define	OBJ_SEMOWNER	0x04000  /* 'o' semaphore [c]owner */
#define	OBJ_SHMGROUP	0x08000  /* 'o' shared memory [c]group */
#define	OBJ_SHMOWNER	0x10000  /* 'o' shared memory [c]owner */
#define	OBJ_FMRI	0x20000  /* 'o' fmri object */
#define	OBJ_USER	0x40000  /* 'o' user object */
#define	OBJ_WSID	0x80000  /* 'o' windows sid object */

#define	SOCKFLG_MACHINE 0	/* search socket token by machine name */
#define	SOCKFLG_PORT    1	/* search socket token by port number */

/*
 * Global variables
 */
extern unsigned short m_type;	/* 'm' message type */
extern gid_t	m_groupr;	/* 'g' real group-id */
extern gid_t	m_groupe;	/* 'f' effective group-id */
extern uid_t	m_usera;	/* 'u' audit user */
extern uid_t	m_userr;	/* 'r' real user */
extern uid_t	m_usere;	/* 'f' effective user */
extern au_asid_t m_sid;		/* 's' session-id */
extern time_t	m_after;	/* 'a' after a time */
extern time_t	m_before;	/* 'b' before a time */
extern audit_state_t mask;	/* used with m_class */
extern char	*zonename;	/* 'z' zonename */

extern m_range_t *m_label;	/* 'l' mandatory label range */
extern int	flags;
extern int	checkflags;
extern int	socket_flag;
extern int	ip_type;
extern uchar_t	ip_ipv6[16];	/* ip ipv6 object identifier */
extern int	obj_flag;	/* 'o' object type */
extern int	obj_id;		/* object identifier */
extern gid_t	obj_group;	/* object group */
extern uid_t	obj_owner;	/* object owner */
extern int	subj_id; 	/* subject identifier */
extern char	ipc_type;	/* 'o' object type - tell what type of IPC */
extern scf_pattern_t fmri;	/* 'o' fmri value */
extern uid_t	obj_user;	/* 'o' user value */

/*
 * File selection options
 */
extern char	*f_machine;	/* 'M' machine (suffix) type */
extern char	*f_root;	/* 'R' audit root */
extern char	*f_server;	/* 'S' server */
extern char	*f_outfile;	/* 'W' output file */
extern int	f_all;		/* 'A' all records from a file */
extern int	f_complete;	/* 'C' only completed files */
extern int	f_delete;	/* 'D' delete when done */
extern int	f_quiet;	/* 'Q' sshhhh! */
extern int	f_verbose;	/* 'V' verbose */
extern int	f_stdin;	/* '-' read from stdin */
extern int	f_cmdline;	/*	files specified on the command line */
extern int	new_mode;	/* 'N' new object selection mode */

/*
 * Error reporting
 * Error_str is set whenever an error occurs to point to a string describing
 * the error. When the error message is printed error_str is also
 * printed to describe exactly what went wrong.
 * Errbuf is used to build messages with variables in them.
 */
extern char	*error_str;	/* current error message */
extern char	errbuf[];	/* buffer for building error message */
extern char	*ar;		/* => "auditreduce:" */

/*
 * Control blocks
 * Audit_pcbs[] is an array of pcbs that control files directly.
 * In the program's initialization phase it will gather all of the input
 * files it needs to process. Each file will have one fcb allocated for it,
 * and each fcb will belong to one pcb from audit_pcbs[]. All of the files
 * in a single pcb will have the same suffix in their filenames. If the
 * number of active pcbs in audit_pcbs[] is greater that the number of open
 * files a single process can have then the program will need to fork
 * subprocesses to handle all of the files.
 */
extern audit_pcb_t *audit_pcbs;	/* file-holding pcb's */
extern int	pcbsize;	/* current size of audit_pcbs[] */
extern int	pcbnum;		/* total # of active pcbs in audit_pcbs[] */

/*
 * Time values
 */
extern time_t f_start;		/* time of start rec for outfile */
extern time_t f_end;		/* time of end rec for outfile */
extern time_t time_now;		/* time program began */

/*
 * Counting vars
 */
extern int	filenum;	/* number of files total */

/*
 * Global variable, class of current record being processed.
 */
extern int	global_class;

#ifdef	__cplusplus
}
#endif

#endif /* _AUDITRT_H */
/*
 * 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 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright 2019 Joyent, Inc.
 * Copyright 2024 Oxide Computer Company
 */

/*
 * The Secure SunOS audit reduction tool - auditreduce.
 * Document SM0071 is the primary source of information on auditreduce.
 *
 * Composed of 4 source modules:
 * main.c - main driver.
 * option.c - command line option processing.
 * process.c - record/file/process functions.
 * time.c - date/time handling.
 *
 * Main(), write_header(), audit_stats(), and a_calloc()
 * are the only functions visible outside this module.
 */

#include <siginfo.h>
#include <locale.h>
#include <libintl.h>
#include "auditr.h"
#include "auditrd.h"

#if !defined(TEXT_DOMAIN)
#define	TEXT_DOMAIN "SUNW_OST_OSCMD"
#endif

extern void	derive_str(time_t, char *);
extern int	process_options(int, char **);
extern int	mproc(audit_pcb_t *);
extern void	init_tokens(void);	/* shared with praudit */

static int	a_pow(int, int);
static void	calc_procs(void);
static void	chld_handler(int);
static int	close_outfile(void);
static void	c_close(audit_pcb_t *, int);
static void	delete_infiles(void);
static void	gather_pcb(audit_pcb_t *, int, int);
static void	init_options(void);
static int	init_sig(void);
static void	int_handler(int);
static int	mfork(audit_pcb_t *, int, int, int);
static void	mcount(int, int);
static int	open_outfile(void);
static void	p_close(audit_pcb_t *);
static int	rename_outfile(void);
static void	rm_mem(audit_pcb_t *);
static void	rm_outfile(void);
static void	trim_mem(audit_pcb_t *);
static int	write_file_token(time_t);
static int	write_trailer(void);

/*
 * File globals.
 */
static int	max_sproc;	/* maximum number of subprocesses per process */
static int	total_procs;	/* number of processes in the process tree */
static int	total_layers;	/* number of layers in the process tree */

/*
 * .func main - main.
 * .desc The beginning. Main() calls each of the initialization routines
 *	and then allocates the root pcb. Then it calls mfork() to get
 *	the work done.
 * .call	main(argc, argv).
 * .arg	argc	- number of arguments.
 * .arg	argv	- array of pointers to arguments.
 * .ret	0	- via exit() - no errors detected.
 * .ret	1	- via exit() - errors detected (messages printed).
 */
int
main(int argc, char **argv)
{
	int	ret;
	audit_pcb_t *pcb;

	/* Internationalization */
	(void) setlocale(LC_ALL, "");
	(void) textdomain(TEXT_DOMAIN);

	root_pid = getpid();	/* know who is root process for error */
	init_options();		/* initialize options */
	init_tokens();		/* initialize token processing table */
	if (init_sig())		/* initialize signals */
		exit(1);
	if (process_options(argc, argv))
		exit(1);	/* process command line options */
	if (open_outfile())	/* setup root process output stream */
		exit(1);
	calc_procs();		/* see how many subprocesses we need */
	/*
	 * Allocate the root pcb and set it up.
	 */
	pcb = (audit_pcb_t *)a_calloc(1, sizeof (audit_pcb_t));
	pcb->pcb_procno = root_pid;
	pcb->pcb_flags |= PF_ROOT;
	pcb->pcb_fpw = stdout;
	pcb->pcb_time = -1;
	/*
	 * Now start the whole thing rolling.
	 */
	if (mfork(pcb, pcbnum, 0, pcbnum - 1)) {
		/*
		 * Error in processing somewhere. A message is already printed.
		 * Display usage statistics and remove the outfile.
		 */
		if (getpid() == root_pid) {
			audit_stats();
			(void) close_outfile();
			rm_outfile();
		}
		exit(1);
	}
	/*
	 * Clean up afterwards.
	 * Only do outfile cleanup if we are root process.
	 */
	if (getpid() == root_pid) {
		if ((ret = write_trailer()) == 0) { /* write trailer to file */

			ret = close_outfile();	/* close the outfile */
		}
		/*
		 * If there was an error in cleanup then remove outfile.
		 */
		if (ret) {
			rm_outfile();
			exit(1);
		}
		/*
		 * And lastly delete the infiles if the user so wishes.
		 */
		if (f_delete)
			delete_infiles();
	}
	return (0);
/*NOTREACHED*/
}


/*
 * .func mfork - main fork routine.
 * .desc Create a (sub-)tree of processses if needed, or just do the work
 *	if we have few enough groups to process. This is a recursive routine
 *	which stops recursing when the number of files to process is small
 *	enough. Each call to mfork() is responsible for a range of pcbs
 *	from audit_pcbs[]. This range is designated by the lo and hi
 *	arguments (inclusive). If the number of pcbs is small enough
 *	then we have hit a leaf of the tree and mproc() is called to
 *	do the processing. Otherwise we fork some processes and break
 *	the range of pcbs up amongst them.
 * .call	ret = mfork(pcb, nsp, lo, hi).
 * .arg	pcb	- ptr to pcb that is root node of the to-be-created tree.
 * .arg	nsp	- number of sub-processes this tree must process.
 * .arg	lo	- lower-limit of process number range. Index into audit_pcbs.
 * .arg	hi	- higher limit of pcb range. Index into audit_pcbs.
 * .ret	0	- succesful completion.
 * .ret	-1	- error encountered in processing - message already printed.
 */
static int
mfork(audit_pcb_t *pcb, int nsp, int lo, int hi)
{
	int	range, procno, i, tofork, nnsp, nrem;
	int	fildes[2];
	audit_pcb_t *pcbn;

#if AUDIT_PROC_TRACE
	(void) fprintf(stderr, "mfork: nsp %d %d->%d\n", nsp, lo, hi);
#endif

	/*
	 * The range of pcb's to process is small enough now. Do the work.
	 */
	if (nsp <= max_sproc) {
		pcb->pcb_flags |= PF_LEAF;	/* leaf in process tree */
		pcb->pcb_below = audit_pcbs;	/* proc pcbs from audit_pcbs */
		gather_pcb(pcb, lo, hi);
		trim_mem(pcb);			/* trim allocated memory */
		return (mproc(pcb));		/* do the work */
	}
	/*
	 * Too many pcb's for one process - must fork.
	 * Try to balance the tree as it grows and make it short and fat.
	 * The thing to minimize is the number of times a record passes
	 * through a pipe.
	 */
	else {
		/*
		 * Fork less than the maximum number of processes.
		 */
		if (nsp <= max_sproc * (max_sproc - 1)) {
			tofork = nsp / max_sproc;
			if (nsp % max_sproc)
				tofork++;	/* how many to fork */
		}
		/*
		 * Fork the maximum number of processes.
		 */
		else {
			tofork = max_sproc;	/* how many to fork */
		}
		/*
		 * Allocate the nodes below us in the process tree.
		 */
		pcb->pcb_below = (audit_pcb_t *)a_calloc(tofork, sizeof (*pcb));
		nnsp = nsp / tofork;	/* # of pcbs per forked process */
		nrem = nsp % tofork;	/* remainder to spread around */
		/*
		 * Loop to fork all of the subs. Open a pipe for each.
		 * If there are any errors in pipes, forks, or getting streams
		 * for the pipes then quit altogether.
		 */
		for (i = 0; i < tofork; i++) {
			pcbn = &pcb->pcb_below[i];
			pcbn->pcb_time = -1;
			if (pipe(fildes)) {
				perror(gettext(
				    "auditreduce: couldn't get a pipe"));
				return (-1);
			}
			/*
			 * Convert descriptors to streams.
			 */
			if ((pcbn->pcb_fpr = fdopen(fildes[0], "r")) == NULL) {
				perror(gettext("auditreduce: couldn't get read "
				    "stream for pipe"));
				return (-1);
			}
			if ((pcbn->pcb_fpw = fdopen(fildes[1], "w")) == NULL) {
				perror(gettext("auditreduce: couldn't get "
				    "write stream for pipe"));
				return (-1);
			}
			if ((procno = fork()) == -1) {
				perror(gettext("auditreduce: fork failed"));
				return (-1);
			}
			/*
			 * Calculate the range of pcbs from audit_pcbs [] this
			 * branch of the tree will be responsible for.
			 */
			range = (nrem > 0) ? nnsp + 1 : nnsp;
			/*
			 * Child route.
			 */
			if (procno == 0) {
				pcbn->pcb_procno = getpid();
				c_close(pcb, i); /* close unused streams */
				/*
				 * Continue resolving this branch.
				 */
				return (mfork(pcbn, range, lo, lo + range - 1));
			}
			/* Parent route. */
			else {
				pcbn->pcb_procno = i;
				/* allocate buffer to hold record */
				pcbn->pcb_rec = (char *)a_calloc(1,
				    AUDITBUFSIZE);
				pcbn->pcb_size = AUDITBUFSIZE;
				p_close(pcbn);	/* close unused streams */

				nrem--;
				lo += range;
			}
		}
		/*
		 * Done forking all of the subs.
		 */
		gather_pcb(pcb, 0, tofork - 1);
		trim_mem(pcb);			/* free unused memory */
		return (mproc(pcb));
	}
}


/*
 * .func	trim_mem - trim memory usage.
 * .desc	Free un-needed allocated memory.
 * .call	trim_mem(pcb).
 * .arg	pcb	- ptr to pcb for current process.
 * .ret	void.
 */
static void
trim_mem(audit_pcb_t *pcb)
{
	int	count;
	size_t	size;

	/*
	 * For the root don't free anything. We need to save audit_pcbs[]
	 * in case we are deleting the infiles at the end.
	 */
	if (pcb->pcb_flags & PF_ROOT)
		return;
	/*
	 * For a leaf save its part of audit_pcbs[] and then remove it all.
	 */
	if (pcb->pcb_flags & PF_LEAF) {
		count = pcb->pcb_count;
		size = sizeof (audit_pcb_t);
		/* allocate a new buffer to hold the pcbs */
		pcb->pcb_below = (audit_pcb_t *)a_calloc(count, size);
		/* save this pcb's portion */
		(void) memcpy((void *) pcb->pcb_below,
		    (void *) &audit_pcbs[pcb->pcb_lo], count * size);
		rm_mem(pcb);
		gather_pcb(pcb, 0, count - 1);
	}
		/*
		 * If this is an intermediate node then just remove it all.
		 */
	else {
		rm_mem(pcb);
	}
}


/*
 * .func	rm_mem - remove memory.
 * .desc	Remove unused memory associated with audit_pcbs[]. For each
 *	pcb in audit_pcbs[] free the record buffer and all of
 *	the fcbs. Then free audit_pcbs[].
 * .call	rm_mem(pcbr).
 * .arg	pcbr	- ptr to pcb of current process.
 * .ret	void.
 */
static void
rm_mem(audit_pcb_t *pcbr)
{
	int	i;
	audit_pcb_t *pcb;
	audit_fcb_t *fcb, *fcbn;

	for (i = 0; i < pcbsize; i++) {
		/*
		 * Don't free the record buffer and fcbs for the pcbs this
		 * process is using.
		 */
		if (pcbr->pcb_flags & PF_LEAF) {
			if (pcbr->pcb_lo <= i || i <= pcbr->pcb_hi)
				continue;
		}
		pcb = &audit_pcbs[i];
		free(pcb->pcb_rec);
		for (fcb = pcb->pcb_first; fcb != NULL; /* */) {
			fcbn = fcb->fcb_next;
			free((char *)fcb);
			fcb = fcbn;
		}
	}
	free((char *)audit_pcbs);
}


/*
 * .func	c_close - close unused streams.
 * .desc	This is called for each child process just after being born.
 *	The child closes the read stream for the pipe to its parent.
 *	It also closes the read streams for the other children that
 *	have been born before it. If any closes fail a warning message
 *	is printed, but processing continues.
 * .call	ret = c_close(pcb, i).
 * .arg	pcb	- ptr to the child's parent pcb.
 * .arg	i	- iteration # of child in forking loop.
 * .ret	void.
 */
static void
c_close(audit_pcb_t *pcb, int	i)
{
	int	j;
	audit_pcb_t *pcbt;

	/*
	 * Do all pcbs in parent's group up to and including us
	 */
	for (j = 0; j <= i; j++) {
		pcbt = &pcb->pcb_below[j];
		if (fclose(pcbt->pcb_fpr) == EOF) {
			if (!f_quiet) {
				perror(gettext("auditreduce: initial close "
				    "on pipe failed"));
			}
		}
		/*
		 * Free the buffer allocated to hold incoming records.
		 */
		if (i != j) {
			free(pcbt->pcb_rec);
		}
	}
}


/*
 * .func	p_close - close unused streams for parent.
 * .desc	Called by the parent right after forking a child.
 *	Closes the write stream on the pipe to the child since
 *	we will never use it.
 * .call	p_close(pcbn),
 * .arg	pcbn	- ptr to pcb.
 * .ret	void.
 */
static void
p_close(audit_pcb_t *pcbn)
{
	if (fclose(pcbn->pcb_fpw) == EOF) {
		if (!f_quiet) {
			perror(gettext("auditreduce: close for write "
			    "pipe failed"));
		}
	}
}


/*
 * .func	audit_stats - print statistics.
 * .desc	Print usage statistics for the user if the run fails.
 *	Tells them how many files they had and how many groups this
 *	totalled. Also tell them how many layers and processes the
 *	process tree had.
 * .call	audit_stats().
 * .arg	none.
 * .ret	void.
 */
void
audit_stats(void)
{
	struct rlimit rl;

	if (getrlimit(RLIMIT_NOFILE, &rl) != -1) {
		(void) fprintf(stderr,
		    gettext("%s The system allows %d files per process.\n"),
		    ar, rl.rlim_cur);
	}
	(void) fprintf(stderr, gettext(
	    "%s There were %d file(s) %d file group(s) %d process(es) "
	    "%d layer(s).\n"),
	    ar, filenum, pcbnum, total_procs, total_layers);
}


/*
 * .func gather_pcb - gather pcbs.
 * .desc Gather together the range of the sub-processes that we are
 *	responsible for. For a pcb that controls processes this is all
 *	of the sub-processes that it forks. For a pcb that controls
 *	files this is the the range of pcbs from audit_pcbs[].
 * .call gather_pcb(pcb, lo, hi).
 * .arg	pcb	- ptr to pcb.
 * .arg	lo	- lo index into pcb_below.
 * .arg	hi	- hi index into pcb_below.
 * .ret	void.
 */
static void
gather_pcb(audit_pcb_t *pcb, int lo, int hi)
{
	pcb->pcb_lo = lo;
	pcb->pcb_hi = hi;
	pcb->pcb_count = hi - lo + 1;
}


/*
 * .func calc_procs - calculate process parameters.
 * .desc Calculate the current run's paramters regarding how many
 *	processes will have to be forked (maybe none).
 *	5 is subtracted from maxfiles_proc to allow for stdin, stdout,
 *	stderr, and the pipe to a parent process. The outfile
 *	in the root process is assigned to stdout. The unused half of each
 *	pipe is closed, to allow for more connections, but we still
 *	have to have the 5th spot because in order to get the pipe
 *	we need 2 descriptors up front.
 * .call calc_procs().
 * .arg	none.
 * .ret	void.
 */
static void
calc_procs(void)
{
	int	val;
	int	maxfiles_proc;
	struct rlimit rl;

	if (getrlimit(RLIMIT_NOFILE, &rl) == -1) {
		perror("auditreduce: getrlimit");
		exit(1);
	}

	maxfiles_proc = rl.rlim_cur;

	max_sproc = maxfiles_proc - 5;	/* max subprocesses per process */

	/*
	 * Calculate how many layers the process tree has.
	 */
	total_layers = 1;
	for (/* */; /* */; /* */) {
		val = a_pow(max_sproc, total_layers);
		if (val > pcbnum)
			break;
		total_layers++;
	}
	/*
	 * Count how many processes are in the process tree.
	 */
	mcount(pcbnum, 0);

#if AUDIT_PROC_TRACE
	(void) fprintf(stderr,
	    "pcbnum %d filenum %d mfp %d msp %d ly %d tot %d\n\n",
	    pcbnum, filenum, maxfiles_proc, max_sproc,
	    total_layers, total_procs);
#endif
}


static int
a_pow(int base, int exp)
{
	int	i;
	int	answer;

	if (exp == 0) {
		answer = 1;
	} else {
		answer = base;
		for (i = 0; i < (exp - 1); i++)
			answer *= base;
	}
	return (answer);
}


/*
 * .func mcount - main count.
 * .desc Go through the motions of building the process tree just
 *	to count how many processes there are. Don't really
 *	build anything. Answer is in global var total_procs.
 * .call mcount(nsp, lo).
 * .arg	nsp	- number of subs for this tree branch.
 * .arg	lo	- lo side of range of subs.
 * .ret	void.
 */
static void
mcount(int nsp, int lo)
{
	int	range, i, tofork, nnsp, nrem;

	total_procs++;		/* count another process created */

	if (nsp > max_sproc) {
		if (nsp <= max_sproc * (max_sproc - 1)) {
			tofork = nsp / max_sproc;
			if (nsp % max_sproc)
				tofork++;
		} else {
			tofork = max_sproc;
		}
		nnsp = nsp / tofork;
		nrem = nsp % tofork;
		for (i = 0; i < tofork; i++) {
			range = (nrem > 0) ? nnsp + 1 : nnsp;
			mcount(range, lo);
			nrem--;
			lo += range;
		}
	}
}


/*
 * .func delete_infiles - delete the input files.
 * .desc If the user asked us to (via 'D' flag) then unlink the input files.
 * .call ret = delete_infiles().
 * .arg none.
 * .ret void.
 */
static void
delete_infiles(void)
{
	int	i;
	audit_pcb_t *pcb;
	audit_fcb_t *fcb;

	for (i = 0; i < pcbsize; i++) {
		pcb = &audit_pcbs[i];
		fcb = pcb->pcb_dfirst;
		while (fcb != NULL) {
			/*
			 * Only delete a file if it was succesfully processed.
			 * If there were any read errors or bad records
			 * then don't delete it.
			 * There may still be unprocessed records in it.
			 */
			if (fcb->fcb_flags & FF_DELETE) {
				if (unlink(fcb->fcb_file)) {
					if (f_verbose) {
						(void) sprintf(errbuf, gettext(
						    "%s delete on %s failed"),
						    ar, fcb->fcb_file);
					}
					perror(errbuf);
				}
			}
			fcb = fcb->fcb_next;
		}
	}
}


/*
 * .func rm_outfile - remove the outfile.
 * .desc Remove the file we are writing the records to. We do this if
 *	processing failed and we are quitting before finishing.
 *	Update - don't actually remove the outfile, but generate
 *	a warning about its possible heathen nature.
 * .call ret = rm_outfile().
 * .arg	none.
 * .ret	void.
 */
static void
rm_outfile(void)
{
#if 0
	if (f_outfile) {
		if (unlink(f_outtemp) == -1) {
			(void) sprintf(errbuf,
			    gettext("%s delete on %s failed"),
			    ar, f_outtemp);
			perror(errbuf);
		}
	}
#else
	(void) fprintf(stderr,
	    gettext(
	    "%s Warning: Incomplete audit file may have been generated - %s\n"),
	    ar,
	    (f_outfile == NULL) ? gettext("standard output") : f_outfile);
#endif
}


/*
 * .func	close_outfile - close the outfile.
 * .desc	Close the file we are writing records to.
 * .call	ret = close_outfile().
 * .arg	none.
 * .ret	0	- close was succesful.
 * .ret	-1	- close failed.
 */
static int
close_outfile(void)
{
	if (fclose(stdout) == EOF) {
		(void) sprintf(errbuf, gettext("%s close on %s failed"),
		    ar, f_outfile ? f_outfile : "standard output");
		perror(errbuf);
		return (-1);
	}
	(void) fsync(fileno(stdout));
	return (rename_outfile());
}


/*
 * .func write_header - write audit file header.
 * .desc Write an audit file header to the output stream. The time in the
 *	header is the time of the first record written to the stream. This
 *	routine is called by the process handling the root node of the
 *	process tree just before it writes the first record to the output
 *	stream.
 * .ret	0 - succesful write.
 * .ret -1 - failed write - message printed.
 */
int
write_header(void)
{
	return (write_file_token(f_start));
}


static int
write_file_token(time_t when)
{
	adr_t adr;			/* adr ptr */
	struct timeval tv;		/* time now */
	char	for_adr[16];		/* plenty of room */
#ifdef _LP64
	char	token_id = AUT_OTHER_FILE64;
#else
	char	token_id = AUT_OTHER_FILE32;
#endif
	short	i = 1;
	char	c = '\0';

	tv.tv_sec = when;
	tv.tv_usec = 0;
	adr_start(&adr, for_adr);
	adr_char(&adr, &token_id, 1);
#ifdef _LP64
	adr_int64(&adr, (int64_t *)&tv, 2);
#else
	adr_int32(&adr, (int32_t *)&tv, 2);
#endif
	adr_short(&adr, &i, 1);
	adr_char(&adr, &c, 1);

	if (fwrite(for_adr, sizeof (char), adr_count(&adr), stdout) !=
	    adr_count(&adr)) {
		if (when == f_start) {
			(void) sprintf(errbuf,
			    gettext("%s error writing header to %s. "),
			    ar,
			    f_outfile ? f_outfile :
			    gettext("standard output"));
		} else {
			(void) sprintf(errbuf,
			    gettext("%s error writing trailer to %s. "),
			    ar,
			    f_outfile ? f_outfile :
			    gettext("standard output"));
		}
		perror(errbuf);
		return (-1);
	}
	return (0);
}


/*
 * .func  write_trailer - write audit file trailer.
 * .desc  Write an audit file trailer to the output stream. The finish
 *	time for the trailer is the time of the last record written
 *	to the stream.
 * .ret	0 - succesful write.
 * .ret	-1 - failed write - message printed.
 */
static int
write_trailer(void)
{
	return (write_file_token(f_end));
}


/*
 * .func rename_outfile - rename the outfile.
 * .desc If the user used the -O flag they only gave us the suffix name
 *	for the outfile. We have to add the time stamps to put the filename
 *	in the proper audit file name format. The start time will be the time
 *	of the first record in the file and the end time will be the time of
 *	the last record in the file.
 * .ret	0 - rename succesful.
 * .ret	-1 - rename failed - message printed.
 */
static int
rename_outfile(void)
{
	static char f_newfile[MAXFILELEN];
	char	buf1[15], buf2[15];
	char	*f_file, *f_nfile, *f_time, *f_name;

	if (f_outfile != NULL) {
		/*
		 * Get string representations of start and end times.
		 */
		derive_str(f_start, buf1);
		derive_str(f_end, buf2);

		f_nfile = f_time = f_newfile;	/* working copy */
		f_file = f_name = f_outfile;	/* their version */
		while (*f_file) {
			if (*f_file == '/') {	/* look for filename */
				f_time = f_nfile + 1;
				f_name = f_file + 1;
			}
			*f_nfile++ = *f_file++;	/* make copy of their version */
		}
		*f_time = '\0';
		/* start time goes first */
		(void) strcat(f_newfile, buf1);
		(void) strcat(f_newfile, ".");
		/* then the finish time */
		(void) strcat(f_newfile, buf2);
		(void) strcat(f_newfile, ".");
		/* and the name they gave us */
		(void) strcat(f_newfile, f_name);

#if AUDIT_FILE
		(void) fprintf(stderr, "rename_outfile: <%s> --> <%s>\n",
		    f_outfile, f_newfile);
#endif

#if AUDIT_RENAME
		if (rename(f_outtemp, f_newfile) == -1) {
			(void) fprintf(stderr,
			    "%s rename of %s to %s failed.\n",
			    ar, f_outtemp, f_newfile);
			return (-1);
		}
		f_outfile = f_newfile;
#else
		if (rename(f_outtemp, f_outfile) == -1) {
			(void) fprintf(stderr,
			    gettext("%s rename of %s to %s failed.\n"),
			    ar, f_outtemp, f_outfile);
			return (-1);
		}
#endif
	}
	return (0);
}


/*
 * .func open_outfile - open the outfile.
 * .desc Open the outfile specified by the -O option. Assign it to the
 *	the standard output. Get a unique temporary name to use so we
 *	don't clobber an existing file.
 * .ret	0 - no errors detected.
 * .ret	-1 - errors in processing (message already printed).
 */
static int
open_outfile(void)
{
	int	tmpfd = -1;

	if (f_outfile != NULL) {
		f_outtemp = (char *)a_calloc(1, strlen(f_outfile) + 8);
		(void) strcpy(f_outtemp, f_outfile);
		(void) strcat(f_outtemp, "XXXXXX");
		if ((tmpfd = mkstemp(f_outtemp)) == -1) {
			(void) sprintf(errbuf,
			    gettext("%s couldn't create temporary file"), ar);
			perror(errbuf);
			return (-1);
		}
		(void) fflush(stdout);
		if (tmpfd != fileno(stdout)) {
			if ((dup2(tmpfd, fileno(stdout))) == -1) {
				(void) sprintf(errbuf,
				    gettext("%s can't assign %s to the "
				    "standard output"), ar, f_outfile);
				perror(errbuf);
				return (-1);
			}
			(void) close(tmpfd);
		}
	}
	return (0);
}


/*
 * .func init_options - initialize the options.
 * .desc Give initial and/or default values to some options.
 * .call init_options();
 * .arg	none.
 * .ret	void.
 */
static void
init_options(void)
{
	struct timeval tp;
	struct timezone tpz;

	/*
	 * Get current time for general use.
	 */
	if (gettimeofday(&tp, &tpz) == -1)
		perror(gettext("auditreduce: initial getttimeofday failed"));

	time_now = tp.tv_sec;		/* save for general use */
	f_start = 0;			/* first record time default */
	f_end = time_now;		/* last record time default */
	m_after = 0;			/* Jan 1, 1970 00:00:00 */

	/*
	 * Setup initial size of audit_pcbs[].
	 */
	pcbsize = PCB_INITSIZE;		/* initial size of file-holding pcb's */

	audit_pcbs = (audit_pcb_t *)a_calloc(pcbsize, sizeof (audit_pcb_t));

	/* description of 'current' error */
	error_str = gettext("initial error");

}


/*
 * .func a_calloc - audit calloc.
 * .desc Calloc with check for failure. This is called by all of the
 *	places that want memory.
 * .call ptr = a_calloc(nelem, size).
 * .arg	nelem - number of elements to allocate.
 * .arg	size - size of each element.
 * .ret	ptr - ptr to allocated and zeroed memory.
 * .ret	never - if calloc fails then we never return.
 */
void	*
a_calloc(int nelem, size_t size)
{
	void	*ptr;

	if ((ptr = calloc((unsigned)nelem, size)) == NULL) {
		perror(gettext("auditreduce: memory allocation failed"));
		exit(1);
	}
	return (ptr);
}


/*
 * .func init_sig - initial signal catching.
 *
 * .desc
 *	Setup the signal catcher to catch the SIGCHLD signal plus
 *	"environmental" signals -- keyboard plus other externally
 *	generated signals such as out of file space or cpu time.  If a
 *	child exits with either a non-zero exit code or was killed by
 *	a signal to it then we will also exit with a non-zero exit
 *	code. In this way abnormal conditions can be passed up to the
 *	root process and the entire run be halted. Also catch the int
 *	and quit signals. Remove the output file since it is in an
 *	inconsistent state.
 * .call ret = init_sig().
 * .arg none.
 * .ret 0 - no errors detected.
 * .ret -1 - signal failed (message printed).
 */
static int
init_sig(void)
{
	if (signal(SIGCHLD, chld_handler) == SIG_ERR) {
		perror(gettext("auditreduce: SIGCHLD signal failed"));
		return (-1);
	}

	if (signal(SIGHUP, int_handler) == SIG_ERR) {
		perror(gettext("auditreduce: SIGHUP signal failed"));
		return (-1);
	}
	if (signal(SIGINT, int_handler) == SIG_ERR) {
		perror(gettext("auditreduce: SIGINT signal failed"));
		return (-1);
	}
	if (signal(SIGQUIT, int_handler) == SIG_ERR) {
		perror(gettext("auditreduce: SIGQUIT signal failed"));
		return (-1);
	}
	if (signal(SIGABRT, int_handler) == SIG_ERR) {
		perror(gettext("auditreduce: SIGABRT signal failed"));
		return (-1);
	}
	if (signal(SIGTERM, int_handler) == SIG_ERR) {
		perror(gettext("auditreduce: SIGTERM signal failed"));
		return (-1);
	}
	if (signal(SIGPWR, int_handler) == SIG_ERR) {
		perror(gettext("auditreduce: SIGPWR signal failed"));
		return (-1);
	}
	if (signal(SIGXCPU, int_handler) == SIG_ERR) {
		perror(gettext("auditreduce: SIGXCPU signal failed"));
		return (-1);
	}
	if (signal(SIGXFSZ, int_handler) == SIG_ERR) {
		perror(gettext("auditreduce: SIGXFSZ signal failed"));
		return (-1);
	}
	if (signal(SIGSEGV, int_handler) == SIG_ERR) {
		perror(gettext("auditreduce: SIGSEGV signal failed"));
		return (-1);
	}

	return (0);
}


/*
 * .func chld_handler - handle child signals.
 * .desc Catch the SIGCHLD signals. Remove the root process
 *	output file because it is in an inconsistent state.
 *	Print a message giving the signal number and/or return code
 *	of the child who caused the signal.
 * .ret	void.
 */
/* ARGSUSED */
void
chld_handler(int sig)
{
	int	pid;
	int	status;

	/*
	 * Get pid and reasons for cause of event.
	 */
	pid = wait(&status);

	if (pid > 0) {
		/*
		 * If child received a signal or exited with a non-zero
		 * exit status then print message and exit
		 */
		if ((WHIBYTE(status) == 0 && WLOBYTE(status) != 0) ||
		    (WHIBYTE(status) != 0 && WLOBYTE(status) == 0)) {
			(void) fprintf(stderr,
			    gettext("%s abnormal child termination - "), ar);

			if (WHIBYTE(status) == 0 && WLOBYTE(status) != 0) {
				psignal(WLOBYTE(status), "signal");
				if (WCOREDUMP(status))
					(void) fprintf(stderr,
					    gettext("core dumped\n"));
			}

			if (WHIBYTE(status) != 0 && WLOBYTE(status) == 0) {
				(void) fprintf(stderr,
				    gettext("return code %d\n"),
				    WHIBYTE(status));
			}

			/*
			 * Get rid of outfile - it is suspect.
			 */
			if (f_outfile != NULL) {
				(void) close_outfile();
				rm_outfile();
			}
			/*
			 * Give statistical info that may be useful.
			 */
			audit_stats();

			exit(1);
		}
	}
}


/*
 * .func	int_handler - handle quit/int signals.
 * .desc	Catch the keyboard and other environmental signals.
 *		Remove the root process output file because it is in
 *		an inconsistent state.
 * .ret	void.
 */
/* ARGSUSED */
void
int_handler(int sig)
{
	if (getpid() == root_pid) {
		(void) close_outfile();
		rm_outfile();
		exit(1);
	}
	/*
	 * For a child process don't give an error exit or the
	 * parent process will catch it with the chld_handler and
	 * try to erase the outfile again.
	 */
	exit(0);
}
/*
 * 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 2010 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Command line option processing for auditreduce.
 * The entry point is process_options(), which is called by main().
 * Process_options() is the only function visible outside this module.
 */

#include <locale.h>
#include <sys/zone.h>	/* for max zonename length */
#include "auditr.h"

/*
 * Object entry.
 * Maps object strings specified on the command line to a flag
 * used when searching by object type.
 */

struct obj_ent {
	char	*obj_str; /* string specified on the command line */
	int	obj_flag; /* flag used when searching */
};

typedef struct obj_ent obj_ent_t;

/*
 * Supports searches by object type.
 */
static obj_ent_t obj_tbl[] = {
			{ "file", OBJ_PATH },
			{ "filegroup", OBJ_FGROUP },
			{ "fileowner", OBJ_FOWNER },
			{ "fmri", OBJ_FMRI },
			{ "lp", OBJ_LP   },
			{ "msgqid", OBJ_MSG  },
			{ "msgqgroup", OBJ_MSGGROUP },
			{ "msgqowner", OBJ_MSGOWNER },
			{ "path", OBJ_PATH },
			{ "pid", OBJ_PROC },
			{ "procgroup", OBJ_PGROUP },
			{ "procowner", OBJ_POWNER },
			{ "semid", OBJ_SEM  },
			{ "semgroup", OBJ_SEMGROUP  },
			{ "semowner", OBJ_SEMOWNER  },
			{ "shmid", OBJ_SHM  },
			{ "shmgroup", OBJ_SHMGROUP  },
			{ "shmowner", OBJ_SHMOWNER  },
			{ "sock", OBJ_SOCK },
			{ "user", OBJ_USER } };

extern int	derive_date(char *, struct tm *);
extern int	parse_time(char *, int);
extern char	*re_comp2(char *);
extern time_t	tm_to_secs(struct tm *);

static int	a_isnum(char *, int);
static int	check_file(audit_fcb_t *, int);
static int	gather_dir(char *);
static audit_pcb_t *get_next_pcb(char *);
static obj_ent_t *obj_lkup(char *);
static int	proc_class(char *);
static int	proc_date(char *, int);
static int	proc_file(char *, int);
static int	process_fileopt(int, char *argv[], int);
static int	proc_group(char *, gid_t *);
static int	proc_id(char *, int);
static int	proc_object(char *);
static void	proc_pcb(audit_pcb_t *, char *, int);
static int	proc_label(char *);
static int	proc_subject(char *);
static int	proc_sid(char *);
static int	proc_type(char *);
static int	proc_user(char *, uid_t *);
static int	proc_zonename(char *);
static int	proc_fmri(char *);

/*
 * .func	process_options - process command line options.
 * .desc	Process the user's command line options. These are of two types:
 *	single letter flags that are denoted by '-', and filenames. Some
 *	of the flags have arguments. Getopt() is used to get the flags.
 *	When this is done it calls process_fileopt() to handle any filenames
 *	that were there.
 * .call	ret = process_options(argc, argv).
 * .arg	argc	- the original value.
 * .arg	argv	- the original value.
 * .ret	0	- no errors detected.
 * .ret	-1	- command line error detected (message already printed).
 */
int
process_options(int argc, char **argv)
{
	int	opt;
	int	error = FALSE;
	int	error_combo = FALSE;
	extern int	optind;		/* in getopt() */
	extern char	*optarg;	/* in getopt() - holds arg to flag */

	static char	*options = "ACD:M:NQR:S:VO:"
	    "a:b:c:d:e:g:j:l:m:o:r:s:t:u:z:";

	error_str = gettext("general error");

	zonename = NULL;
	/*
	 * Big switch to process the flags.
	 * Start_over: is for handling the '-' for standard input. Getopt()
	 * doesn't recognize it.
	 */
start_over:
	while ((opt = getopt(argc, argv, options)) != EOF) {
		switch (opt) {
		case 'A':		/* all records from the files */
			f_all = TRUE;
			break;
		case 'C':		/* process only completed files */
			f_complete = TRUE;
			break;
		case 'D':		/* delete the files when done */
			/* force 'A' 'C' 'O' to be active */
			f_all = f_complete = TRUE;
			f_outfile = optarg;
			f_delete = TRUE;
			break;
		case 'M':		/* only files from a certain machine */
			f_machine = optarg;
			break;
		case 'N':		/* new object selection mode */
			new_mode = TRUE;
			break;
		case 'Q':		/* no file error reporting */
			f_quiet = TRUE;
			break;
		case 'R':		/* from specified root */
			f_root = optarg;
			break;
		case 'S':		/* from specified server */
			f_server = optarg;
			break;
		case 'V':		/* list all files as they are opened */
			f_verbose = TRUE;
			break;
		case 'O':		/* write to outfile */
			f_outfile = optarg;
			break;
		case 'a':		/* after 'date' */
		case 'b':		/* before 'date' */
		case 'd':		/* from 'day' */
			if (proc_date(optarg, opt))
				error = TRUE;
			break;
		case 'j':		/* subject */
			if (proc_subject(optarg))
				error = TRUE;
			break;
		case 'm':		/* message 'type' */
			if (proc_type(optarg))
				error = TRUE;
			break;
		case 'o':		/* object type */
			if (proc_object(optarg))
				error = TRUE;
			break;
		case 'c':		/* message class */
			if (proc_class(optarg))
				error = TRUE;
			break;
		case 'u':		/* form audit user */
		case 'e':		/* form effective user */
		case 'r':		/* form real user */
		case 'f':		/* form effective group */
		case 'g':		/* form real group */
			if (proc_id(optarg, opt))
				error = TRUE;
			break;
		case 'l':		/* TX label range */
			if (!is_system_labeled()) {
				(void) fprintf(stderr,
				    gettext("%s option 'l' requires "
				    "Trusted Extensions.\n"), ar);
				return (-1);
			}
			if (proc_label(optarg))
				error = TRUE;
			break;
		case 's':		/* session ID */
			if (proc_sid(optarg))
				error = TRUE;
			break;
		case 'z':		/* zone name */
			if (proc_zonename(optarg))
				error = TRUE;
			break;
		case 't':		/* termial ID reserved for later */
		default:
			return (-1);
		}
		if (error) {
			(void) fprintf(stderr,
			    gettext("%s command line error - %s.\n"),
			    ar, error_str);
			return (-1);
		}
	}
	/* catch '-' option for stdin processing - getopt() won't see it */
	if (optind < argc) {
		if (argv[optind][0] == '-' && argv[optind][1] == '\0') {
			optind++;
			f_stdin = TRUE;
			goto start_over;
		}
	}
	/*
	 * Give a default value for 'b' option if not specified.
	 */
	if (m_before == 0)
		m_before = MAXLONG;	/* forever */
	/*
	 * Validate combinations of options.
	 * The following are done:
	 *	1. Can't have 'M' or 'S' or 'R' with filenames.
	 *	2. Can't have an after ('a') time after a before ('b') time.
	 *	3. Delete ('D') must have 'C' and 'A' and 'O' with it.
	 *	4. Input from stdin ('-') can't have filenames too.
	 */
	if ((f_machine || f_server || f_root) && (argc != optind)) {
		error_str = gettext(
		    "no filenames allowed with 'M' or 'S' or 'R' options");
		error_combo = TRUE;
	}
	if (m_after >= m_before) {
		error_str =
		    gettext("'a' parameter must be before 'b' parameter");
		error_combo = TRUE;
	}
	if (f_delete &&
	    (!f_complete || !f_all || !f_outfile)) {
		error_str = gettext(
		    "'C', 'A', and 'O' must be specified with 'D'");
		error_combo = TRUE;
	}
	if (f_stdin && (argc != optind)) {
		error_str = gettext("no filenames allowed with '-' option");
		error_combo = TRUE;
	}
	/*
	 * If error with option combos then print message and exit.
	 * If there was an error with just an option then exit.
	 */
	if (error_combo) {
		(void) fprintf(stderr,
		    gettext("%s command line error - %s.\n"), ar, error_str);
		return (-1);
	}
	if (f_root == NULL)
		f_root = "/etc/security/audit";
	/*
	 * Now handle any filenames included in the command line.
	 */
	return (process_fileopt(argc, argv, optind));
}

int
proc_subject(char *optarg)
{
	if (flags & M_SUBJECT) {
		error_str = gettext("'j' option specified multiple times");
		return (-1);
	}
	flags |= M_SUBJECT;
	subj_id = atol(optarg);
	return (0);
}

int
proc_sid(char *optarg)
{
	if (flags & M_SID) {
		error_str = gettext("'s' option specified multiple times");
		return (-1);
	}
	flags |= M_SID;
	m_sid = (au_asid_t)atol(optarg);
	return (0);
}

int
proc_object(char *optarg)
{
	char	*obj_str;
	char	*obj_val;
	char	*obj_arg;
	int	err;

	obj_ent_t *oep;
	struct hostent *he;

	if (flags & M_OBJECT) {
		error_str = gettext("'o' option specified multiple times");
		return (-1);
	}
	flags |= M_OBJECT;
	if ((obj_arg = strdup(optarg)) == (char *)0)
		return (-1);
	if ((obj_str = strtok(optarg, "=")) == (char *)0 ||
	    (oep = obj_lkup(obj_str)) == (obj_ent_t *)0 ||
	    (obj_val = strtok((char *)0, "=")) == (char *)0) {
		(void) sprintf(errbuf, gettext("invalid object arg (%s)"),
		    obj_arg);
		error_str = errbuf;
		return (-1);
	}

	obj_flag = oep->obj_flag;

	switch (obj_flag) {
	case OBJ_PATH:
		if ((error_str = re_comp2(obj_val)) != (char *)NULL) {
			return (-1);
		}
		return (0);
	case OBJ_SOCK:
		if (!a_isnum(obj_val, TRUE)) {
			obj_id = atol(obj_val);
			socket_flag = SOCKFLG_PORT;
			return (0);
		}
		if (*obj_val == '0') {
			(void) sscanf(obj_val, "%x", (uint_t *)&obj_id);
			socket_flag = SOCKFLG_PORT;
			return (0);
		}

		he = getipnodebyname((const void *)obj_val, AF_INET6, 0, &err);
		if (he == 0) {
			he = getipnodebyname((const void *)obj_val, AF_INET,
			    0, &err);
			if (he == 0) {
				(void) sprintf(errbuf,
				    gettext("invalid machine name (%s)"),
				    obj_val);
				error_str = errbuf;
				return (-1);
			}
		}

		if (he->h_addrtype == AF_INET6) {
			/* LINTED */
			if (IN6_IS_ADDR_V4MAPPED(
			    (in6_addr_t *)he->h_addr_list[0])) {
				/* address is IPv4 (32 bits) */
				(void) memcpy(&obj_id,
				    he->h_addr_list[0] + 12, 4);
				ip_type = AU_IPv4;
			} else {
				(void) memcpy(ip_ipv6, he->h_addr_list[0], 16);
				ip_type = AU_IPv6;
			}
		} else {
			/* address is IPv4 (32 bits) */
			(void) memcpy(&obj_id, he->h_addr_list[0], 4);
			ip_type = AU_IPv4;
		}

		freehostent(he);
		socket_flag = SOCKFLG_MACHINE;
		return (0);
	case OBJ_MSG:
	case OBJ_SEM:
	case OBJ_SHM:
	case OBJ_PROC:
		obj_id = atol(obj_val);
		return (0);
	case OBJ_FGROUP:
	case OBJ_MSGGROUP:
	case OBJ_SEMGROUP:
	case OBJ_SHMGROUP:
	case OBJ_PGROUP:
		return (proc_group(obj_val, &obj_group));
	case OBJ_FOWNER:
	case OBJ_MSGOWNER:
	case OBJ_SEMOWNER:
	case OBJ_SHMOWNER:
	case OBJ_POWNER:
		return (proc_user(obj_val, &obj_owner));
	case OBJ_FMRI:
		return (proc_fmri(obj_val));
	case OBJ_USER:
		return (proc_user(obj_val, &obj_user));
	case OBJ_LP: /* lp objects have not yet been defined */
	default: /* impossible */
		(void) sprintf(errbuf, gettext("invalid object type (%s)"),
		    obj_str);
		error_str = errbuf;
		return (-1);
	} /* switch */
	/*NOTREACHED*/
}


obj_ent_t *
obj_lkup(char *obj_str)
{
	int	i;

	for (i = 0; i < sizeof (obj_tbl) / sizeof (obj_ent_t); i++)
		if (strcmp(obj_str, obj_tbl[i].obj_str) == 0)
			return (&obj_tbl[i]);

	/* not in table */
	return (NULL);
}


/*
 * .func	proc_type - process record type.
 * .desc	Process a record type. It is either as a number or a mnemonic.
 * .call	ret = proc_type(optstr).
 * .arg	optstr	- ptr to name or number.
 * .ret	0	- no errors detected.
 * .ret	-1	- error detected (error_str contains description).
 */
int
proc_type(char *optstr)
{
	struct au_event_ent *aep;

	/*
	 * Either a number or a name.
	 */

	if (flags & M_TYPE) {
		error_str = gettext("'m' option specified multiple times");
		return (-1);
	}
	flags |= M_TYPE;
	m_type = 0;
	if (a_isnum(optstr, TRUE)) {
		if ((aep = getauevnam(optstr)) != NULL)
			m_type = aep->ae_number;
	} else {
		if ((aep = getauevnum((au_event_t)atoi(optstr))) !=
		    (struct au_event_ent *)NULL)
			m_type = aep->ae_number;
	}
	if ((m_type == 0)) {
		(void) sprintf(errbuf, gettext("invalid event (%s)"), optstr);
		error_str = errbuf;
		return (-1);
	}
	return (0);
}


/*
 * .func	a_isnum - is it a number?
 * .desc	Determine if a string is a number or a name.
 *	A number may have a leading '+' or '-', but then must be
 *	all digits.
 * .call	ret = a_isnum(str).
 * .arg	str - ptr to the string.
 * .arg	leading	- TRUE if leading '+-' allowed.
 * .ret	0	- is a number.
 * .ret	1	- is not a number.
 */
int
a_isnum(char *str, int leading)
{
	char	*strs;

	if ((leading == TRUE) && (*str == '-' || *str == '+'))
		strs = str + 1;
	else
		strs = str;

	if (strlen(strs) == strspn(strs, "0123456789"))
		return (0);
	else
		return (1);
}


/*
 * .func	proc_id	- process user/group id's/
 * .desc	Process either a user number/name or group number/name.
 *	For names check to see if the name is active in the system
 *	to derive the number. If it is not active then fail. For a number
 *	also check to see if it is active, but only print a warning if it
 *	is not. An administrator may be looking at activity of a 'phantom'
 *	user.
 * .call	ret = proc_id(optstr, opt).
 * .arg	optstr	- ptr to name or number.
 * .arg	opt	- 'u' - audit user, 'e' - effective user, 'r' - real user,
 *		  'g' - group, 'f' - effective group.
 * .ret	0	- no errors detected.
 * .ret	-1	- error detected (error_str contains description).
 */
int
proc_id(char *optstr, int opt)
{
	switch (opt) {
	case 'e': 		/* effective user id */
		if (flags & M_USERE) {
			error_str = gettext(
			    "'e' option specified multiple times");
			return (-1);
		}
		flags |= M_USERE;
		return (proc_user(optstr, &m_usere));
	case 'f': 		/* effective group id */
		if (flags & M_GROUPE) {
			error_str = gettext(
			    "'f' option specified multiple times");
			return (-1);
		}
		flags |= M_GROUPE;
		return (proc_group(optstr, &m_groupe));
	case 'r': 		/* real user id */
		if (flags & M_USERR) {
			error_str = gettext(
			    "'r' option specified multiple times");
			return (-1);
		}
		flags |= M_USERR;
		return (proc_user(optstr, &m_userr));
	case 'u': 		/* audit user id */
		if (flags & M_USERA) {
			error_str = gettext(
			    "'u' option specified multiple times");
			return (-1);
		}
		flags |= M_USERA;
		return (proc_user(optstr, &m_usera));
	case 'g': 		/* real group id */
		if (flags & M_GROUPR) {
			error_str = gettext(
			    "'g' option specified multiple times");
			return (-1);
		}
		flags |= M_GROUPR;
		return (proc_group(optstr, &m_groupr));
	default: 		/* impossible */
		(void) sprintf(errbuf, gettext("'%c' unknown option"), opt);
		error_str = errbuf;
		return (-1);
	}
	/*NOTREACHED*/
}


int
proc_group(char *optstr, gid_t *gid)
{
	struct group *grp;

	if ((grp = getgrnam(optstr)) == NULL) {
		if (!a_isnum(optstr, TRUE)) {
			*gid = (gid_t)atoi(optstr);
			return (0);
		}
		(void) sprintf(errbuf, gettext("group name invalid (%s)"),
		    optstr);
		error_str = errbuf;
		return (-1);
	}
	*gid = grp->gr_gid;
	return (0);
}


int
proc_user(char *optstr, uid_t *uid)
{
	struct passwd *usr;

	if ((usr = getpwnam(optstr)) == NULL) {
		if (!a_isnum(optstr, TRUE)) {
			*uid = (uid_t)atoi(optstr);
			return (0);
		}
		(void) sprintf(errbuf, gettext("user name invalid (%s)"),
		    optstr);
		error_str = errbuf;
		return (-1);
	}
	*uid = usr->pw_uid;
	return (0);
}


/*
 * .func proc_date - process date argument.
 * .desc Handle a date/time argument. See if the user has erred in combining
 *	the types of date arguments. Then parse the string and check for
 *	validity of each part.
 * .call	ret = proc_date(optstr, opt).
 * .arg	optstr	- ptr to date/time string.
 * .arg	opt	- 'd' for day, 'a' for after, or 'b' for before.
 * .ret	0	- no errors detected.
 * .ret	-1	- errors detected (error_str knows what it is).
 */
int
proc_date(char *optstr, int opt)
{
	static int	m_day = FALSE;

	if (opt == 'd') {
		if (m_day == TRUE) {
			error_str = gettext(
			    "'d' option may not be used with 'a' or 'b'");
			return (-1);
		}
		m_day = TRUE;
	}
	if ((opt == 'd') && (m_before || m_after)) {
		error_str = gettext(
		    "'d' option may not be used with 'a' or 'b'");
		return (-1);
	}
	if ((opt == 'a' || opt == 'b') && m_day) {
		error_str = gettext(
		    "'a' or 'b' option may not be used with 'd'");
		return (-1);
	}
	if ((opt == 'a') && (m_after != 0)) {
		error_str = gettext("'a' option specified multiple times");
		return (-1);
	}
	if ((opt == 'b') && (m_before != 0)) {
		error_str = gettext("'b' option specified multiple times");
		return (-1);
	}
	if (parse_time(optstr, opt))
		return (-1);
	return (0);
}


/*
 * .func	proc_class - process message class argument.
 * .desc	Process class type and see if it is for real.
 * .call	ret = proc_class(optstr).
 * .arg	optstr	- ptr to class.
 * .ret	0	- class has class.
 * .ret	-1	- class in no good.
 */
int
proc_class(char *optstr)
{
	if (flags & M_CLASS) {
		error_str = gettext("'c' option specified multiple times");
		return (-1);
	}
	flags |= M_CLASS;

	if (getauditflagsbin(optstr, &mask) != 0) {
		(void) sprintf(errbuf, gettext("unknown class (%s)"), optstr);
		error_str = errbuf;
		return (-1);
	}

	if (mask.am_success != mask.am_failure) {
		flags |= M_SORF;
	}

	return (0);
}


/*
 * .func process_fileopt - process command line file options.
 * .desc Process the command line file options and gather the specified files
 *	together in file groups based upon file name suffix. The user can
 *	specify files explicitly on the command line or via a directory.
 *	This is called after the command line flags are processed (as
 *	denoted by '-').
 * .call	ret = process_fileopt(argc, argv, optindex).
 * .arg	argc	- current value of argc.
 * .arg	argv	- current value of argv.
 * .arg	optindex- current index into argv (as setup by getopt()).
 * .ret	0	- no errors detected.
 * .ret	-1	- error detected (message already printed).
 */
int
process_fileopt(int argc, char **argv, int optindex)
{
	int	f_mode = FM_ALLDIR;
	char	f_dr[MAXNAMLEN+1];
	char	*f_dir = f_dr;
	char	*fname;
	static char	*std = "standard input";
	audit_fcb_t *fcb;
	DIR * dirp;
	struct dirent *dp;
	audit_pcb_t *pcb;

	/*
	 * Take input from stdin, not any files.
	 * Use a single fcb to do this.
	 */
	if (f_stdin) {
		fcb = (audit_fcb_t *)a_calloc(1, sizeof (*fcb) + strlen(std));
		(void) strcpy(fcb->fcb_file, std);
		fcb->fcb_suffix = fcb->fcb_name = fcb->fcb_file;
		fcb->fcb_next = NULL;
		fcb->fcb_start = 0;
		fcb->fcb_end = MAXLONG;		/* forever */
		if ((pcb = get_next_pcb((char *)NULL)) == (audit_pcb_t *)NULL)
			return (-1);
		pcb->pcb_suffix = fcb->fcb_file;
		pcb->pcb_dfirst = pcb->pcb_first = fcb;	/* one-item list */
		pcb->pcb_dlast = pcb->pcb_last = fcb;
		pcb->pcb_cur = fcb;
	}
	/*
	 * No files specified on the command line.
	 * Process a directory of files or subdirectories.
	 */
	else if (argc == optindex) {
		/*
		 * A specific server directory was requested.
		 */
		if (f_server) {
			if (strchr(f_server, '/')) {	/* given full path */
				f_dir = f_server;
				f_mode = FM_ALLFILE;	/* all files here */
			} else {		/* directory off audit root */
				f_dir[0] = '\0';
				(void) strcat(f_dir, f_root);
				(void) strcat(f_dir, "/");
				(void) strcat(f_dir, f_server);
				f_mode = FM_ALLFILE;
			}
		}
		/*
		 * Gather all of the files in the directory 'f_dir'.
		 */
		if (f_mode == FM_ALLFILE) {
			if (gather_dir(f_dir)) { /* get those files together */
				return (-1);
			}
		} else {
			/*
			 * Gather all of the files in all of the
			 * directories in 'f_root'.
			 */
			if ((dirp = opendir(f_root)) == NULL) {
				(void) sprintf(errbuf, gettext(
				    "%s can't open directory %s"), ar, f_root);
				perror(errbuf);
				return (-1);
			}
			/* read the directory and process all of the subs */
			for (dp = readdir(dirp);
			    dp != NULL; dp = readdir(dirp)) {
				if (dp->d_name[0] == '.')
					continue;
				f_dir[0] = '\0';
				(void) strcat(f_dir, f_root);
				(void) strcat(f_dir, "/");
				(void) strcat(f_dir, dp->d_name);
				if (gather_dir(f_dir))	/* process a sub */
					return (-1);
			}
			(void) closedir(dirp);
		}
	} else {
		/*
		 * User specified filenames on the comm and line.
		 */
		f_cmdline = TRUE;
		for (; optindex < argc; optindex++) {
			fname = argv[optindex];		/* get a filename */
			if (proc_file(fname, FALSE))
				return (-1);
		}
	}
	return (0);
}


/*
 * .func	gather_dir - gather a directory's files together.
 * .desc	Process all of the files in a specific directory. The files may
 *	be checked for adherence to the file name form at.
 *	If the directory can't be opened that is ok - just print
 *	a message and continue.
 * .call	ret = gather_dir(dir).
 * .arg	dir	- ptr to full pathname of directory.
 * .ret	0	- no errors detected.
 * .ret	-1	- error detected (message already printed).
 */
int
gather_dir(char *dir)
{
	char	dname[MAXNAMLEN+1];
	char	fname[MAXNAMLEN+1];
	DIR * dirp;
	struct dirent *dp;

	(void) snprintf(dname, sizeof (dname), "%s/files", dir);

	if ((dirp = opendir(dname)) == NULL) {
		if (errno != ENOTDIR) {
			(void) sprintf(errbuf,
			    gettext("%s can't open directory - %s"), ar, dname);
			perror(errbuf);
		}
		return (0);
	}
	for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
		if (dp->d_name[0] == '.')	/* can't see hidden files */
			continue;
		fname[0] = '\0';
		(void) strcat(fname, dname);	/* create pathname of file */
		(void) strcat(fname, "/");
		(void) strcat(fname, dp->d_name);
		if (proc_file(fname, TRUE))
			return (-1);
	}
	(void) closedir(dirp);
	return (0);
}


/*
 * .func	proc_file - process a single candidate file.
 * .desc	Check out a file to see if it should be used in the merge.
 *	This includes checking the name (mode is TRUE) against the
 *	file format, checking access rights to the file, and thence
 *	getting and fcb and installing the fcb into the correct pcb.
 *	If the file fails then the fcb is not installed into a pcb
 *	and the file dissapears from view.
 * .call	proc_file(fname, mode).
 * .arg	fname	- ptr to full pathna me of file.
 * .arg	mode	- TRUE if checking adherence to file name format.
 * .ret	0	- no fatal errors detected.
 * .ret	-1	- fatal error detected - quit altogether
 *		  (message already printed).
 */
int
proc_file(char *fname, int mode)
{
	int reject = FALSE;
	size_t len;
	struct stat stat_buf;
	audit_fcb_t *fcb, *fcbp, *fcbprev;
	audit_pcb_t *pcb;

	/*
	 * See if it is a weird file like a directory or
	 * character special (around here?).
	 */
	if (stat(fname, &stat_buf)) {
		return (0);
	}
	if (!S_ISREG(stat_buf.st_mode))
		return (0);
	/*
	 * Allocate a new fcb to hold fcb and full filename.
	 */
	len = sizeof (audit_fcb_t) + strlen(fname);
	fcb = (audit_fcb_t *)a_calloc(1, len);
	(void) strcpy(fcb->fcb_file, fname);
	if (check_file(fcb, mode)) { /* check file name */
		if (!f_quiet) {
			(void) fprintf(stderr, "%s %s:\n  %s.\n", ar,
			    error_str, fname);
		}
		reject = TRUE;
	} else {
		/*
		 * Check against file criteria.
		 * Check finish-time here, and start-time later on
		 * while processing.
		 * This is because the start time on a file can be after
		 * the first record(s).
		 */
		if (f_complete && (fcb->fcb_flags & FF_NOTTERM) && !f_cmdline)
			reject = TRUE;
		if (!f_all && (fcb->fcb_end < m_after))
			reject = TRUE;
		if (f_machine) {
			if (strlen(fcb->fcb_suffix) != strlen(f_machine) ||
			    (strcmp(fcb->fcb_suffix, f_machine) != 0)) {
				reject = TRUE;
			}
		}
	}
	if (reject == FALSE) {
		filenum++;	/* count of total files to be processed */
		fcb->fcb_next = NULL;
		if ((pcb = get_next_pcb(fcb->fcb_suffix)) == NULL) {
			return (-1);
		}
		/* Place FCB into the PCB in order - oldest first.  */
		fcbp = pcb->pcb_first;
		fcbprev = NULL;
		while (fcbp != NULL) {
			if (fcb->fcb_start < fcbp->fcb_start) {
				if (fcbprev)
					fcbprev->fcb_next = fcb;
				else
					pcb->pcb_dfirst = pcb->pcb_first = fcb;
				fcb->fcb_next = fcbp;
				break;
			}
			fcbprev = fcbp;
			fcbp = fcbp->fcb_next;
		}
		/* younger than all || empty list */
		if (!fcb->fcb_next) {
			if (pcb->pcb_first == NULL)
				pcb->pcb_dfirst = pcb->pcb_first = fcb;
			pcb->pcb_dlast = pcb->pcb_last = fcb;
			if (fcbprev)
				fcbprev->fcb_next = fcb;
		}
	} else {
		free((char *)fcb);	/* rejected */
	}
	return (0);
}


/*
 * .func	check_file - check filename and setup fcb.
 * .desc	Check adherence to the file format (do_check is TRUE) and setup
 *	the fcb with useful information.
 *	filename format: yyyymmddhhmmss.yyyymmddhhmmss.suffix
 *			 yyyymmddhhmmss.not_terminated.suffix
 *	If do_check is FALSE then still see if the filename does confirm
 *	to the format. If it does then extract useful information from
 *	it (start time and end time).  But if it doesn't then don't print
 *	any error messages.
 * .call	ret = check_file(fcb, do_check).
 * .arg	fcb	- ptr to fcb that holds the file.
 * .arg	do_check - if TRUE do check adherence to file format.
 * .ret	0	- no errors detected.
 * .ret	-1	- file failed somehow (error_str tells why).
 */
int
check_file(audit_fcb_t *fcb, int do_check)
{
	int	ret;
	char	*namep, *slp;
	char	errb[256];		/* build error message */
	struct tm tme;

	errb[0] = '\0';
	/* get just the filename */
	for (slp = namep = fcb->fcb_file; *namep; namep++) {
		if (*namep == '/')
			slp = namep + 1; /* slp -> the filename itself */
	}
	if (do_check == FALSE) {
		fcb->fcb_end = MAXLONG;		/* forever */
		fcb->fcb_suffix = NULL;
		fcb->fcb_name = slp;
		ret = 0;
	} else {
		ret = -1;
	}
	if ((int)strlen(slp) < 31) {
		(void) sprintf(errbuf, gettext("filename too short (%d)"),
		    strlen(slp));
		error_str = errbuf;
		return (ret);
	}
	/*
	 * Get working copy of filename.
	 */
	namep = (char *)a_calloc(1, strlen(slp) + 1);
	(void) strcpy(namep, slp);
	if (namep[14] != '.' || namep[29] != '.') {
		(void) sprintf(errbuf,
		    gettext("invalid filename format (%c or %c)"), namep[14],
		    namep[29]);
		error_str = errbuf;
		free(namep);
		return (ret);
	}
	namep[14] = '\0';			/* mark off start time */
	namep[29] = '\0';			/* mark off finish time */
	if (derive_date(namep, &tme)) {
		(void) strcat(errb, gettext("starting time-stamp invalid - "));
		(void) strcat(errb, error_str);
		(void) strcpy(errbuf, errb);
		error_str = errbuf;
		free(namep);
		return (ret);
	}
	/*
	 * Keep start time from filename. Use it to order files in
	 * the file list. Later we will update this when we read
	 * the first record from the file.
	 */
	fcb->fcb_start = tm_to_secs(&tme);

	if (strcmp(&namep[15], "not_terminated") == 0) {
		fcb->fcb_end = MAXLONG;		/* forever */
		/*
		 * Only treat a 'not_terminated' file as such if
		 * it is not on the command line.
		 */
		if (do_check == TRUE)
			fcb->fcb_flags |= FF_NOTTERM;
	} else if (derive_date(&namep[15], &tme)) {
		(void) strcat(errb, gettext("ending time-stamp invalid - "));
		(void) strcat(errb, error_str);
		(void) strcpy(errbuf, errb);
		error_str = errbuf;
		free(namep);
		return (ret);
	} else {
		fcb->fcb_end = tm_to_secs(&tme);
	}
	fcb->fcb_name = slp;
	fcb->fcb_suffix = &slp[30];
	free(namep);
	return (0);
}


/*
 * .func get_next_pcb - get a pcb to use.
 * .desc	The pcb's in the array audit_pcbs are used to hold single file
 *	groups in the form of a linked list. Each pcb holds files that
 *	are tied together by a common suffix in the file name. Here we
 *	get either 1. the existing pcb holding a specified sufix or
 *	2. a new pcb if we can't find an existing one.
 * .call	pcb = get_next_pcb(suffix).
 * .arg	suffix	- ptr to suffix we are seeking.
 * .ret	pcb	- ptr to pcb that hold s the sought suffix.
 * .ret	NULL- serious failure in memory allocation. Quit processing.
 */
audit_pcb_t *
get_next_pcb(char *suffix)
{
	int	i = 0;
	int	zerosize;
	unsigned int	size;
	audit_pcb_t *pcb;

	/* Search through (maybe) entire array. */
	while (i < pcbsize) {
		pcb = &audit_pcbs[i++];
		if (pcb->pcb_first == NULL) {
			proc_pcb(pcb, suffix, i);
			return (pcb);	/* came to an unused one */
		}
		if (suffix) {
			if (strcmp(pcb->pcb_suffix, suffix) == 0)
				return (pcb);	/* matched one with suffix */
		}
	}
	/*
	 * Uh-oh, the entire array is used and we haven't gotten one yet.
	 * Allocate a bigger array.
	 */
	pcbsize += PCB_INC;
	size = pcbsize * sizeof (audit_pcb_t);
	zerosize = size - ((pcbsize - PCB_INC) * sizeof (audit_pcb_t));
	if ((audit_pcbs = (audit_pcb_t *)realloc((char *)audit_pcbs, size)) ==
	    NULL) {
		(void) sprintf(errbuf,
		    gettext("%s memory reallocation failed (%d bytes)"), ar,
		    size);
		perror(errbuf);
		audit_stats();		/* give user statistics on usage */
		return (NULL);		/* really bad thing to have happen */
	}
	/*
	 * Don't know if realloc clears the new memory like calloc would.
	 */
	(void) memset((void *) & audit_pcbs[pcbsize-PCB_INC], 0,
	    (size_t)zerosize);
	pcb = &audit_pcbs[pcbsize-PCB_INC];	/* allocate the first new one */
	proc_pcb(pcb, suffix, pcbsize - PCB_INC);
	return (pcb);
}


/*
 * .func proc_pcb - process pcb.
 * .desc	Common pcb processing for above routine.
 * .call	proc_pcb(pcb, suffix, i).
 * .arg	pcb	- ptr to pcb.
 * .arg	suffix	- prt to suffix tha t ties this group together.
 * .arg	i	- index into audit_pcbs[ ].
 * .ret	void.
 */
void
proc_pcb(audit_pcb_t *pcb, char *suffix, int i)
{
	if (suffix)
		pcb->pcb_suffix = suffix;
	pcbnum++;	/* one more pcb in use */
	pcb->pcb_size = AUDITBUFSIZE;
	pcb->pcb_rec = (char *)a_calloc(1, AUDITBUFSIZE);
	pcb->pcb_time = -1;
	pcb->pcb_flags |= PF_USEFILE;	/* note this one controls files */
	pcb->pcb_procno = i;	/* save index into audit_pcbs [] for id */
}


/*
 * .func	proc_label - process label range argument.
 * .desc	Parse label range lower-bound[;upper-bound]
 * .call	ret = proc_label(optstr).
 * .arg	opstr	- ptr to label range string
 * .ret 0	- no errors detected.
 * .ret -1	- errors detected (error_str set).
 */

int
proc_label(char *optstr)
{
	char	*p;
	int	error;

	if (flags & M_LABEL) {
		error_str = gettext("'l' option specified multiple times");
		return (-1);
	}
	flags |= M_LABEL;

	if ((m_label = malloc(sizeof (m_range_t))) == NULL) {
		return (-1);
	}
	m_label->lower_bound = NULL;
	m_label->upper_bound = NULL;

	p = strchr(optstr, ';');
	if (p == NULL) {
		/* exact label match, lower and upper range bounds the same */
		if (str_to_label(optstr, &m_label->lower_bound, MAC_LABEL,
		    L_NO_CORRECTION, &error) == -1) {
			(void) sprintf(errbuf,
			    gettext("invalid sensitivity label (%s) err %d"),
			    optstr, error);
			error_str = errbuf;
			goto errout;
		}
		m_label->upper_bound = m_label->lower_bound;
		return (0);
	}
	if (p == optstr) {
		/* lower bound is not specified .. default is admin_low */
		if (str_to_label(ADMIN_LOW, &m_label->lower_bound, MAC_LABEL,
		    L_NO_CORRECTION, &error) == -1) {
			goto errout;
		}

		p++;
		if (*p == '\0') {
			/* upper bound not specified .. default is admin_high */
			if (str_to_label(ADMIN_HIGH, &m_label->upper_bound,
			    MAC_LABEL, L_NO_CORRECTION, &error) == -1) {
				goto errout;
			}
		} else {
			if (str_to_label(p, &m_label->upper_bound, MAC_LABEL,
			    L_NO_CORRECTION, &error) == -1) {
				(void) sprintf(errbuf, gettext(
				    "invalid sensitivity label (%s) err %d"),
				    p, error);
				error_str = errbuf;
				goto errout;
			}
		}
		return (0);
	}
	*p++ = '\0';
	if (str_to_label(optstr, &m_label->lower_bound, MAC_LABEL,
	    L_NO_CORRECTION, &error) == -1) {
		(void) sprintf(errbuf,
		    gettext("invalid sensitivity label (%s) err %d"), optstr,
		    error);
		error_str = errbuf;
		goto errout;
	}
	if (*p == '\0') {
		/* upper bound is not specified .. default is admin_high */
		if (str_to_label(ADMIN_HIGH, &m_label->upper_bound,
		    MAC_LABEL, L_NO_CORRECTION, &error) == -1) {
			goto errout;
		}
	} else {
		if (str_to_label(p, &m_label->upper_bound, MAC_LABEL,
		    L_NO_CORRECTION, &error) == -1) {
			(void) sprintf(errbuf,
			    gettext("invalid sensitivity label (%s) err %d"),
			    p, error);
			error_str = errbuf;
			goto errout;
		}
	}
	/* make sure that upper bound dominates the lower bound */
	if (!bldominates(m_label->upper_bound, m_label->lower_bound)) {
		*--p = ';';
		(void) sprintf(errbuf,
		    gettext("invalid sensitivity label range (%s)"), optstr);
		error_str = errbuf;
		goto errout;
	}
	return (0);

errout:
	m_label_free(m_label->upper_bound);
	m_label_free(m_label->lower_bound);
	free(m_label);

	return (-1);
}

/*
 * proc_zonename - pick up zone name.
 *
 * all non-empty and not-too-long strings are valid since any name
 * may be valid.
 *
 * ret 0:	non-empty string
 * ret -1:	empty string or string is too long.
 */
static int
proc_zonename(char *optstr)
{
	size_t	length = strlen(optstr);
	if ((length < 1) || (length > ZONENAME_MAX)) {
		(void) sprintf(errbuf,
		    gettext("invalid zone name: %s"), optstr);
		error_str = errbuf;
		return (-1);
	}
	zonename = strdup(optstr);
	flags |= M_ZONENAME;
	return (0);
}

/*
 * proc_frmi - set up frmi for pattern matching.
 *	Logic ripped off of scf_walk_fmri()
 *		Thanks to the smf team.
 *
 * ret 0:	OK
 * ret -1:	error
 */
static int
proc_fmri(char *optstr)
{
	if (strpbrk(optstr, "*?[") != NULL) {
		/* have a pattern to glob for */

		fmri.sp_type = PATTERN_GLOB;
		if (optstr[0] == '*' ||
		    (strlen(optstr) >= 4 && optstr[3] == ':')) {
			fmri.sp_arg = strdup(optstr);
		} else if ((fmri.sp_arg = malloc(strlen(optstr) + 6)) != NULL) {
			(void) snprintf(fmri.sp_arg, strlen(optstr) + 6,
			    "svc:/%s", optstr);
		}
	} else {
		fmri.sp_type = PATTERN_PARTIAL;
		fmri.sp_arg = strdup(optstr);
	}
	if (fmri.sp_arg == NULL)
		return (-1);

	return (0);
}
/*
 * 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 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Main processor for auditreduce.
 * Mproc() is the entry point for this module. It is the only visible
 * function in this module.
 */

#include <sys/types.h>
#include <locale.h>
#include <bsm/libbsm.h>
#include <bsm/audit.h>
#include "auditr.h"

extern int	write_header();
extern int	token_processing();

static void	asort();
static audit_pcb_t *aget();
static int	get_file();
static int	write_recs();
static int	get_recs();
static int	check_rec();
static void	check_order();
static int	check_header();
static int	get_record();

static char	empty_file_token[] = {
#ifdef _LP64
		AUT_OTHER_FILE64, /* token id */
		0, 0, 0, 0, 0, 0, 0, 0, /* seconds of time */
		0, 0, 0, 0, 0, 0, 0, 0, /* microseconds of time */
#else
		AUT_OTHER_FILE32, /* token id */
		0, 0, 0, 0, /* seconds of time */
		0, 0, 0, 0, /* microseconds of time */
#endif
		0, 0, /* length of path name */
};


/*
 * .func	mproc - main processor.
 * .desc	Mproc controls a single process's actions.
 *	First one record is retreived from each pcb. As they are retreived
 *	they are placed into a linked list sorted with oldest first. Then
 *	the first one from the list is written out and another record
 *	read in to replace it. The new record is placed into the list.
 *	This continues until the list is empty.
 * .call	ret = mproc(pcbr).
 * .arg	pcbr	- ptr to pcb for this process.
 * .ret	0	- no errors in processing.
 * .ret	-1	- errors in processing (message already printed).
 */
int
mproc(pcbr)
register audit_pcb_t *pcbr;
{
	int	i, ret, junk;
	int	nrecs = 0;		/* number of records read from stream */
	int	nprecs = 0;		/* number of records put to stream */
	register audit_pcb_t *pcb;
	audit_pcb_t *aget();
	void	asort();

#if AUDIT_PROC_TRACE
	(void) fprintf(stderr, "mproc: count %d lo %d hi %d\n",
	    pcbr->pcb_count, pcbr->pcb_lo, pcbr->pcb_hi);
#endif

	/*
	 * First load up a record from each input group.
	 */
	for (i = pcbr->pcb_lo; i <= pcbr->pcb_hi; i++) {
		pcb = &(pcbr->pcb_below[i]); /* get next PCB */
		while (pcb->pcb_time < 0) { /* while no active record ... */
			if ((ret = get_file(pcb)) == -1)
				break;		/*  no files - finished PCB */
			if (ret == -2)
				return (-1);	/* quit processing - failed */
			if (get_recs(pcb, &nrecs) == 0)
				asort(pcb);	/* got a rec - put in list */
		}
	}
	/*
	 * Now process all of the records.
	 */
	while ((pcb = aget()) != NULL) {	/* get oldest record */
		if (write_recs(pcbr, pcb, &nprecs))
			return (-1);
		while (pcb->pcb_time < 0) {	/* while we don't have a rec */
			if (pcb->pcb_fpr == NULL) {	/* no active file ... */
				if ((ret = get_file(pcb)) == -1)
					break;	/* no files - finished pcb */
				else if (ret == -2)
					return (-1);	/* quit - failed */
			}
			if (get_recs(pcb, &nrecs) == 0)
				asort(pcb);		/* put record in list */
		}
	}
	/*
	 * For root: write outfile header if no records were encountered.
	 * For non-root: write trailer to pipe and close pipe.
	 */
	if (pcbr->pcb_flags & PF_ROOT) {
		if (nprecs == 0) {
			if (write_header())	/* write header if no records */
				return (-1);
		}
	} else {
		pcb = &(pcbr->pcb_below[0]);	/* any old PCB will do */
		pcb->pcb_rec = empty_file_token;
		if (write_recs(pcbr, pcb, &junk))
			return (-1);
		if (fclose(pcbr->pcb_fpw) == EOF) {
			if (!f_quiet)
				(void) fprintf(stderr,
				    gettext("%s couldn't close pipe.\n"), ar);
		}
	}
	/*
	 * For root process tell how many records were written.
	 */
	if (f_verbose && (pcbr->pcb_flags & PF_ROOT)) {
		(void) fprintf(stderr,
		    gettext("%s %d record(s) total were written out.\n"),
			ar, nprecs);
	}
	return (0);
}


/*
 * Head of linked-list of pcbs - sorted by time - oldest first.
 */
static audit_pcb_t		*pcbls = NULL;

/*
 * .func	asort - audit sort.
 * .desc	Place a pcb in the list sorted by time - oldest first.
 * .call	asort(pcb);
 * .arg	pcb	- ptr to pcb to install in list.
 * .ret	void.
 */
static void
asort(pcb)
register audit_pcb_t *pcb;
{
	register audit_pcb_t *pcbc, *pcbp;
	extern audit_pcb_t *pcbls;	/* ptr to start of list */

	pcb->pcb_next = NULL;
	if (pcbls == NULL) {
		pcbls = pcb;		/* empty list */
		return;
	}
	pcbc = pcbls;			/* current pcb */
	pcbp = pcbls;			/* previous pcb */
	while (pcbc != NULL) {
		if (pcb->pcb_time < pcbc->pcb_time) {
			if (pcbp == pcbc) {
				pcb->pcb_next = pcbls;	/* new -> 1st in list */
				pcbls = pcb;
				return;
			}
			pcbp->pcb_next = pcb;
			pcb->pcb_next = pcbc;		/* new in the inside */
			return;
		}
		pcbp = pcbc;
		pcbc = pcbc->pcb_next;
	}
	pcbp->pcb_next = pcb;				/* new -> last */
}


/*
 * .func	aget - audit get.
 * .desc	Get the first pcb from the list. Pcb is removed from list, too.
 * .call	pcb = aget().
 * .arg	none.
 * .ret	pcb	- ptr to pcb that was the first.
 */
static audit_pcb_t *
aget()
{
	audit_pcb_t *pcbret;
	extern audit_pcb_t *pcbls;	/* ptr to start of list */

	if (pcbls == NULL)
		return (pcbls);		/* empty list */
	pcbret = pcbls;
	pcbls = pcbls->pcb_next;	/* 2nd becomes 1st */
	return (pcbret);
}


/*
 * .func	get_file - get a new file.
 * .desc	Get the next file from the pcb's list. Check the header to see
 *	if the file really is an audit file. If there are no more then
 *	quit. If a file open (fopen) fails because the system file table
 *	is full or the process file table is full then quit processing
 *	altogether.
 * .call	ret = get_file(pcb).
 * .arg	pcb	- pcb holding the fcb's (files).
 * .ret	0	- new file opened for processing.
 * .ret	-1	- no more files - pcb finished.
 * .ret	-2	- fatal error - quit processing.
 */
static int
get_file(pcb)
register audit_pcb_t *pcb;
{
	FILE *fp;
	audit_fcb_t *fcb;

	/*
	 * Process file list until a good one if found or empty.
	 */
	while (pcb->pcb_fpr == NULL) {
		if ((fcb = pcb->pcb_first) == NULL) {
			pcb->pcb_time = -1;
			return (-1);	/* pcb is all done */
		} else {
		/*
		 * If we are reading from files then open the next one.
		 */
			if (!f_stdin) {
				if ((fp = fopen(fcb->fcb_file, "r")) == NULL) {
					if (!f_quiet) {
						(void) sprintf(errbuf, gettext(
						"%s couldn't open:\n  %s"),
						ar, fcb->fcb_file);
						perror(errbuf);
					}
					/*
					 * See if file space is depleted.
					 * If it is then we quit.
					 */
					if (errno == ENFILE || errno == EMFILE)
					{
						return (-2);
					}
					pcb->pcb_first = fcb->fcb_next;
					continue;	/* try another file */
				}
			} else {
				/*
				 * Read from standard input.
				 */
				fp = stdin;
			}
			/*
			 * Check header of audit file.
			 */
			if (check_header(fp, fcb->fcb_name)) {
				if (!f_quiet) {
					(void) fprintf(stderr,
					    "%s %s:\n  %s.\n",
					    ar, error_str, fcb->fcb_file);
				}
				if (fclose(fp) == EOF) {
					if (!f_quiet) {
						(void) fprintf(stderr, gettext(
						"%s couldn't close %s.\n"),
						ar, fcb->fcb_file);
					}
				}
				pcb->pcb_first = fcb->fcb_next;
				continue;		/* try another file */
			}
			/*
			 * Found a good audit file.
			 * Initalize pcb for processing.
			 */
			pcb->pcb_first = fcb->fcb_next;
			pcb->pcb_cur = fcb;
			pcb->pcb_fpr = fp;
			pcb->pcb_nrecs = 0;
			pcb->pcb_nprecs = 0;
			pcb->pcb_otime = -1;
		}
	}
	return (0);
}


/*
 * .func	write_recs - write records.
 * .desc	Write record from a buffer to output stream. Keep an eye out
 *	for the first and last records of the root's output stream.
 * .call	ret = write_recs(pcbr, pcb, nprecs).
 * .arg	pcbr	- ptr to node pcb.
 * .arg	pcb		- ptr to pcb holding the stream.
 * .arg	nprecs	- ptr to the number of put records. Updated here.
 * .ret	0	- no errors detected.
 * .ret	-1	- error in writing. Quit processing.
 */
static int
write_recs(pcbr, pcb, nprecs)
register audit_pcb_t *pcbr, *pcb;
int	*nprecs;
{
	adr_t adr;
	char	id;
	int32_t	size;

	adrm_start(&adr, pcb->pcb_rec);
	(void) adrm_char(&adr, &id, 1);
	(void) adrm_int32(&adr, &size, 1);

	/*
	 * Scan for first record to be written to outfile.
	 * When we find it then write the header and
	 * save the time for the outfile name.
	 */
	if ((*nprecs)++ == 0) {
		if (pcbr->pcb_flags & PF_ROOT) {
			f_start = pcb->pcb_time;	/* save start time */
			if (write_header())
				return (-1);
		}
	}
	f_end = pcb->pcb_time;			/* find last record's time */
	pcb->pcb_time = -1;			/* disable just written rec */

	if ((fwrite(pcb->pcb_rec, sizeof (char), size, pcbr->pcb_fpw)) !=
			size) {
		if (pcbr->pcb_flags & PF_ROOT) {
			(void) sprintf(errbuf, gettext(
				"%s write failed to %s"),
				ar, f_outfile ? f_outfile : gettext("stdout"));
			perror(errbuf);
		} else {
			perror(gettext("auditreduce: write failed to pipe"));
		}
		return (-1);
	}
	free(pcb->pcb_rec);
	return (0);
}

/*
 * .func get_recs - get records.
 * .desc Get records from a stream until one passing the current selection
 *	criteria is found or the stream is emptied.
 * .call	ret = get_recs(pcb, nr).
 * .arg	pcb	- ptr to pcb that holds this stream.
 * .arg	nr	- ptr to number of records read. Updated by this routine.
 * .ret	0	- got a record.
 * .ret	-1	- stream is finished.
 */
static int
get_recs(pcb, nr)
register audit_pcb_t *pcb;
int	*nr;
{
	adr_t adr;
	time_t secs;
	int	tmp;
	int	ret, ret2;
	int	nrecs = 0;	/* count how many records read this call */
	int	getrec = TRUE;
	int	alldone = FALSE;
	char	header_type;
	short	e;
	char	*str;
#if AUDIT_FILE
	static void	get_trace();
#endif

	while (getrec) {
		ret = get_record(pcb->pcb_fpr, &pcb->pcb_rec,
			pcb->pcb_cur->fcb_name);
		if (ret > 0) {
			adrm_start(&adr, pcb->pcb_rec);

			/* get token id */
			(void) adrm_char(&adr, (char *)&header_type, 1);
			/* skip over byte count */
			(void) adrm_int32(&adr, (int32_t *)&tmp, 1);
			/* skip over version # */
			(void) adrm_char(&adr, (char *)&tmp, 1);
			/* skip over event id */
			(void) adrm_short(&adr, (short *)&e, 1);
			/* skip over event id modifier */
			(void) adrm_short(&adr, (short *)&tmp, 1);

			if (header_type == AUT_HEADER32) {
			    int32_t s, m;

			    /* get seconds */
			    (void) adrm_int32(&adr, (int32_t *)&s, 1);
			    /* get microseconds */
			    (void) adrm_int32(&adr, (int32_t *)&m, 1);
			    secs = (time_t)s;
			} else if (header_type == AUT_HEADER32_EX) {
			    int32_t s, m;
			    int32_t t, junk[4];	/* at_type + at_addr[4] */

			    /* skip type and ip address field */
			    (void) adrm_int32(&adr, (int32_t *)&t, 1);
			    (void) adrm_int32(&adr, (int32_t *)&junk[0], t/4);

			    /* get seconds */
			    (void) adrm_int32(&adr, (int32_t *)&s, 1);
			    /* get microseconds */
			    (void) adrm_int32(&adr, (int32_t *)&m, 1);
			    secs = (time_t)s;
			} else if (header_type == AUT_HEADER64) {
			    int64_t s, m;

			    /* get seconds */
			    (void) adrm_int64(&adr, (int64_t *)&s, 1);
			    /* get microseconds */
			    (void) adrm_int64(&adr, (int64_t *)&m, 1);
#if ((!defined(_LP64)) || defined(_SYSCALL32))
			    if (s < (time_t)INT32_MIN ||
				s > (time_t)INT32_MAX)
					secs = 0;
			    else
					secs = (time_t)s;
#else
			    secs = (time_t)s;
#endif
			} else if (header_type == AUT_HEADER64_EX) {
			    int64_t s, m;
			    int32_t t, junk[4];

			    /* skip type and ip address field */
			    (void) adrm_int32(&adr, (int32_t *)&t, 1);
			    (void) adrm_int32(&adr, (int32_t *)&junk[0], t/4);

			    /* get seconds */
			    (void) adrm_int64(&adr, (int64_t *)&s, 1);
			    /* get microseconds */
			    (void) adrm_int64(&adr, (int64_t *)&m, 1);
#if ((!defined(_LP64)) || defined(_SYSCALL32))
			    if (s < (time_t)INT32_MIN ||
				s > (time_t)INT32_MAX)
					secs = 0;
			    else
					secs = (time_t)s;
#else
			    secs = (time_t)s;
#endif
			}
		}

#if AUDIT_REC
		(void) fprintf(stderr, "get_recs: %d ret %d recno %d\n",
			pcb->pcb_procno, ret, pcb->pcb_nrecs + 1);
#endif
		/*
		 * See if entire file is after the time window specified.
		 * Must be check here because the start time of the file name
		 * may be after the first record(s).
		 */
		if (pcb->pcb_nrecs == 0 && (pcb->pcb_flags & PF_USEFILE)) {
			/*
			 * If the first record read failed then use the time
			 * that was in the filename to judge.
			 */
			if (ret > 0)
				(pcb->pcb_cur)->fcb_start = secs;
			if (!f_all && (m_before <= (pcb->pcb_cur)->fcb_start)) {
				(void) fclose(pcb->pcb_fpr); /* ignore file */
				pcb->pcb_fpr = NULL;
				pcb->pcb_time = -1;
				return (-1);
			} else {
				/* Give belated announcement of file opening. */
				if (f_verbose) {
					(void) fprintf(stderr,
						gettext("%s opened:\n  %s.\n"),
						ar, (pcb->pcb_cur)->fcb_file);
				}
			}
		}
		/* Succesful acquisition of a record.  */
		if (ret > 0) {
			pcb->pcb_time = secs;	/* time of record */
			pcb->pcb_nrecs++;	/* # of read recs from stream */
			nrecs++;		/* # of recs read this call */
			/* Only check record if at bottom of process tree. */
			if (pcb->pcb_flags & PF_USEFILE) {
				check_order(pcb); /* check time sequence */
				if ((ret2 = check_rec(pcb)) == 0) {
					pcb->pcb_nprecs++;
					getrec = FALSE;
				} else if (ret2 == -2) {
					/* error */
					getrec = FALSE;	/* get no more recs */
					alldone = TRUE;	/* quit this file */
					free(pcb->pcb_rec);
				} else {
					/* -1: record not interesting */
					free(pcb->pcb_rec);
				}
			} else {
				pcb->pcb_nprecs++;
				getrec = FALSE;
			}
		} else {
			/* Error with record read or all done with stream. */
			getrec = FALSE;
			alldone = TRUE;
		}
	}
	if (alldone == TRUE) {
#if AUDIT_FILE
		get_trace(pcb);
#endif
		/* Error in record read. Display messages. */
		if (ret < 0 || ret2 == -2) {
			pcb->pcb_nrecs++;	/* # of read records */
			if (!f_quiet) {
				if (pcb->pcb_flags & PF_USEFILE) {
					/* Ignore if this is not_terminated. */
					if (!strstr((pcb->pcb_cur)->fcb_file,
							"not_terminated")) {
(void) fprintf(stderr, gettext("%s read error in %s at record %d.\n"), ar,
	(pcb->pcb_cur)->fcb_file, pcb->pcb_nrecs);
					}
				} else {
(void) fprintf(stderr, gettext("%s read error in pipe at record %d.\n"), ar,
	pcb->pcb_nrecs);
				}
			}
		} else {
			/*
			 * Only mark infile for deleting if we have succesfully
			 * processed all of it.
			 */
			if (pcb->pcb_flags & PF_USEFILE)
				(pcb->pcb_cur)->fcb_flags |= FF_DELETE;
		}
		if (fclose(pcb->pcb_fpr) == EOF) {
			if (!f_quiet) {
				if (pcb->pcb_flags & PF_USEFILE) {
					str = (pcb->pcb_cur)->fcb_file;
				} else {
					str = "pipe";
				}
				(void) fprintf(stderr,
					gettext("%s couldn't close %s.\n"),
					ar, str);
			}
		}
		pcb->pcb_fpr = NULL;
		pcb->pcb_time = -1;
		*nr += nrecs;
		return (-1);
	}
	*nr += nrecs;
	return (0);
}


#if AUDIT_FILE
/*
 * .func get_trace - get trace.
 * .desc If we are tracing file action (AUDIT_FILE is on) then print out
 *	a message when the file is closed regarding how many records
 *	were handled.
 * .call	get_trace(pcb).
 * .arg	pcb	- ptr to pcb holding file/pipe.
 * .ret	void.
 */
static void
get_trace(pcb)
audit_pcb_t *pcb;
{
	/*
	 * For file give filename, too.
	 */
	if (pcb->pcb_flags & PF_USEFILE) {
	(void) fprintf(stderr, "%s closed %s: %d records read recs: \
		%d record written.\n", ar, (pcb->pcb_cur)->fcb_file,
		pcb->pcb_nrecs, pcb->pcb_nprecs);
	} else {
		(void) fprintf(stderr, "%s closed pipe: %d records read: \
			%d records written .\n", ar, pcb->pcb_nrecs,
			pcb->pcb_nprecs);
	}
}

#endif

/*
 * .func	check_rec - check a record.
 * .desc	Check a record against the user's selection criteria.
 * .call	ret = check_rec(pcb).
 * .arg	pcb	- ptr to pcb holding the record.
 * .ret	0	- record accepted.
 * .ret	-1	- record rejected - continue processing file.
 * .ret	-2	- record rejected - quit processing file.
 */
static int
check_rec(pcb)
register audit_pcb_t *pcb;
{
	adr_t adr;
	struct timeval tv;
	uint_t	bytes;
	au_emod_t id_modifier;
	char	version;
	au_event_t event_type;
	char	tokenid;
	int	rc;	 /* return code */

	adrm_start(&adr, pcb->pcb_rec);
	(void) adrm_char(&adr, &tokenid, 1);

	/*
	 * checkflags will be my data structure for determining if
	 * a record has met ALL the selection criteria.  Once
	 * checkflags == flags, we have seen all we need to of the
	 * record, and can go to the next one.  If when we finish
	 * processing the record we still have stuff to see,
	 * checkflags != flags, and thus we should return a -1
	 * from this function meaning reject this record.
	 */

	checkflags = 0;

	/* must be header token -- sanity check */
	if (tokenid != AUT_HEADER32 && tokenid != AUT_HEADER64 &&
	    tokenid != AUT_HEADER32_EX && tokenid != AUT_HEADER64_EX) {
#if AUDIT_REC
		(void) fprintf(stderr,
		    "check_rec: %d recno %d no header %d found\n",
		    pcb->pcb_procno, pcb->pcb_nrecs, tokenid);
#endif
		return (-2);
	}

	/*
	 * The header token is:
	 *	attribute id:		char
	 *	byte count:		int
	 *	version #:		char
	 *	event ID:		short
	 *	ID modifier:		short
	 *	seconds (date):		int
	 *	time (microsecs):	int
	 */
	(void) adrm_u_int32(&adr, (uint32_t *)&bytes, 1);
	(void) adrm_char(&adr, &version, 1);
	(void) adrm_u_short(&adr, &event_type, 1);

	/*
	 * Used by s5_IPC_token to set the ipc_type so
	 * s5_IPC_perm_token can test.
	 */
	ipc_type = (char)0;

	if (flags & M_TYPE) {
		checkflags |= M_TYPE;
		if (m_type != event_type)
			return (-1);
	}
	if (flags & M_CLASS) {
		au_event_ent_t *ev = NULL;

		checkflags |= M_CLASS;
		if (cacheauevent(&ev, event_type) <= 0) {
		    (void) fprintf(stderr, gettext(
			"Warning: invalid event no %d in audit trail."),
			event_type);
		    return (-1);
		}
		global_class = ev->ae_class;
		if (!(flags & M_SORF) && !(mask.am_success & global_class))
			return (-1);
	}

	(void) adrm_u_short(&adr, &id_modifier, 1);

	/*
	 * Check record against time criteria.
	 * If the 'A' option was used then no time checking is done.
	 * The 'a' parameter is inclusive and the 'b' exclusive.
	 */
	if (tokenid == AUT_HEADER32) {
	    int32_t secs, msecs;
	    (void) adrm_int32(&adr, (int32_t *)&secs, 1);
	    (void) adrm_int32(&adr, (int32_t *)&msecs, 1);
	    tv.tv_sec = (time_t)secs;
	    tv.tv_usec = (suseconds_t)msecs;
	} else if (tokenid == AUT_HEADER32_EX) {
	    int32_t secs, msecs;
	    int32_t t, junk[5];	/* at_type + at_addr[4] */
	    /* skip type and ip address field */
	    (void) adrm_int32(&adr, (int32_t *)&t, 1);
	    (void) adrm_int32(&adr, (int32_t *)&junk[0], t/4);
	    /* get time */
	    (void) adrm_int32(&adr, (int32_t *)&secs, 1);
	    (void) adrm_int32(&adr, (int32_t *)&msecs, 1);
	    tv.tv_sec = (time_t)secs;
	    tv.tv_usec = (suseconds_t)msecs;
	} else if (tokenid == AUT_HEADER64) {
	    int64_t secs, msecs;
	    (void) adrm_int64(&adr, (int64_t *)&secs, 1);
	    (void) adrm_int64(&adr, (int64_t *)&msecs, 1);
#if ((!defined(_LP64)) || defined(_SYSCALL32))
	    if (secs < (time_t)INT32_MIN ||
		secs > (time_t)INT32_MAX)
			tv.tv_sec = 0;
	    else
			tv.tv_sec = (time_t)secs;
	    if (msecs < (suseconds_t)INT32_MIN ||
		msecs > (suseconds_t)INT32_MAX)
			tv.tv_usec = 0;
	    else
			tv.tv_usec = (suseconds_t)msecs;
#else
	    tv.tv_sec = (time_t)secs;
	    tv.tv_usec = (suseconds_t)msecs;
#endif
	} else if (tokenid == AUT_HEADER64_EX) {
	    int64_t secs, msecs;
	    int32_t t, junk[4];	/* at_type + at_addr[4] */
	    /* skip type and ip address field */
	    (void) adrm_int32(&adr, (int32_t *)&t, 1);
	    (void) adrm_int32(&adr, (int32_t *)&junk[0], t/4);
	    /* get time */
	    (void) adrm_int64(&adr, (int64_t *)&secs, 1);
	    (void) adrm_int64(&adr, (int64_t *)&msecs, 1);
#if ((!defined(_LP64)) || defined(_SYSCALL32))
	    if (secs < (time_t)INT32_MIN ||
		secs > (time_t)INT32_MAX)
			tv.tv_sec = 0;
	    else
			tv.tv_sec = (time_t)secs;
	    if (msecs < (suseconds_t)INT32_MIN ||
		msecs > (suseconds_t)INT32_MAX)
			tv.tv_usec = 0;
	    else
			tv.tv_usec = (suseconds_t)msecs;
#else
	    tv.tv_sec = (time_t)secs;
	    tv.tv_usec = (suseconds_t)msecs;
#endif
	}
	pcb->pcb_otime = pcb->pcb_time;
	if (!f_all) {
		if (m_after > tv.tv_sec)
			return (-1);
		if (m_before <= tv.tv_sec)
			return (-1);
	}

	/* if no selection flags were passed, select everything */
	if (!flags)
		return (0);

	/*
	 * If all information can be found in header,
	 * there is no need to continue processing the tokens.
	 */
	if (flags == checkflags)
		return (0);

	/*
	 * Process tokens until we hit the end of the record
	 */
	while ((uint_t)(adr.adr_now - adr.adr_stream) < bytes) {
		adrm_char(&adr, &tokenid, 1);
		rc = token_processing(&adr, tokenid);

		/* Any Problems? */
		if (rc == -2) {
			(void) fprintf(stderr,
			    gettext("auditreduce: bad token %u, terminating "
			    "file %s\n"), tokenid, (pcb->pcb_cur)->fcb_file);
			return (-2);
		}

		/* Are we finished? */
		if (flags == checkflags)
			return (0);
	}

	/*
	 * So, we haven't seen all that we need to see.  Reject record.
	 */

	return (-1);
}


/*
 * .func check_order - Check temporal sequence.
 * .call check_order(pcb).
 * .arg	 pcb - ptr to audit_pcb_t.
 * .desc	Check to see if the records are out of temporal sequence, ie,
 *	a record has a time stamp older than its predecessor.
 *	Also check to see if the current record is within the bounds of
 *	the file itself.
 *	This routine prints a diagnostic message, unless the QUIET
 *	option was selected.
 * .call	check_order(pcb).
 * .arg	pcb	- ptr to pcb holding the records.
 * .ret	void.
 */
static void
check_order(pcb)
register audit_pcb_t *pcb;
{
	char	cptr1[28], cptr2[28];	/* for error reporting */

	/*
	 * If the record-past is not the oldest then say so.
	 */
	if (pcb->pcb_otime > pcb->pcb_time) {
		if (!f_quiet) {
			(void) memcpy((void *)cptr1,
				(void *)ctime(&pcb->pcb_otime), 26);
			cptr1[24] = ' ';
			(void) memcpy((void *)cptr2,
				(void *)ctime(&pcb->pcb_time), 26);
			cptr2[24] = ' ';
			(void) fprintf(stderr,
	gettext("%s %s had records out of order: %s was followed by %s.\n"),
				ar, (pcb->pcb_cur)->fcb_file, cptr1, cptr2);
		}
	}
}


/*
 * .func	check_header.
 * .desc	Read in and check the header for an audit file.
 *	The header must read-in properly and have the magic #.
 * .call	err = check_header(fp).
 * .arg	fp	- file stream.
 * .ret	0	no problems.
 * .ret	-1	problems.
 */
static int
check_header(fp, fn)
FILE *fp;
char	*fn;
{
	char	id;
	char	*fname;
	short	pathlength;
	adr_t	adr;
	adrf_t	adrf;

	adrf_start(&adrf, &adr, fp);

	if (adrf_char(&adrf, &id, 1)) {
		(void) sprintf(errbuf, gettext("%s is empty"), fn);
		error_str = errbuf;
		return (-1);
	}
	if (!(id == AUT_OTHER_FILE32 || id == AUT_OTHER_FILE64)) {
		(void) sprintf(errbuf, gettext("%s not an audit file "), fn);
		error_str = errbuf;
		return (-1);
	}

	if (id == AUT_OTHER_FILE32) {
	    int32_t secs, msecs;
	    (void) adrf_int32(&adrf, (int32_t *)&secs, 1);
	    (void) adrf_int32(&adrf, (int32_t *)&msecs, 1);
	} else {
	    int64_t secs, msecs;
	    (void) adrf_int64(&adrf, (int64_t *)&secs, 1);
	    (void) adrf_int64(&adrf, (int64_t *)&msecs, 1);
#if ((!defined(_LP64)) || defined(_SYSCALL32))
	    if (secs < (time_t)INT32_MIN ||
		secs > (time_t)INT32_MAX) {
		    error_str = gettext("bad time stamp in file header");
		    return (-1);
	    }
	    if (msecs < (suseconds_t)INT32_MIN ||
		msecs > (suseconds_t)INT32_MAX) {
		    error_str = gettext("bad time stamp in file header");
		    return (-1);
	    }
#endif
	}

	if (adrf_short(&adrf, &pathlength, 1)) {
		error_str = gettext("incomplete file header");
		return (-1);
	}

	if (pathlength != 0) {
		fname = (char *)a_calloc(1, (size_t)pathlength);
		if ((fread(fname, sizeof (char), pathlength, fp)) !=
				pathlength) {
			(void) sprintf(errbuf,
				gettext("error in header/filename read in %s"),
				fn);
			error_str = errbuf;
			return (-1);
		}
		free(fname);
	}
	return (0);
}


/*
 * .func	get_record - get a single record.
 * .desc	Read a single record from stream fp. If the record to be read
 *	is larger than the buffer given to hold it (as determined by
 *	cur_size) then free that buffer and allocate a new and bigger
 *	one, making sure to store its size.
 * .call	ret = get_record(fp, buf, cur_size, flags).
 * .arg	fp	- stream to read from.
 * .arg	buf	- ptr to ptr to buffer to place record in.
 * .arg	cur_size- ptr to the size of the buffer that *buf points to.
 * .arg	flags	- flags from fcb (to get FF_NOTTERM).
 * .ret	+number	- number of chars in the record.
 * .ret	0	- trailer seen - file done.
 * .ret	-1	- read error (error_str know what type).
 */
static int
get_record(fp, buf, fn)
FILE *fp;
char	**buf;
char	*fn;
{
	adr_t	adr;
	adrf_t	adrf;
	int	leadin;
	char	id;
	int	lsize;
	short	ssize;

	/*
	 * Get the token type. It will be either a header or a file
	 * token.
	 */
	(void) adrf_start(&adrf, &adr, fp);
	if (adrf_char(&adrf, &id, 1)) {
		(void) sprintf(errbuf, gettext(
			"record expected but not found in %s"),
			fn);
		error_str = errbuf;
		return (-1);
	}
	switch (id) {
	case AUT_HEADER32:
	case AUT_HEADER32_EX:
	case AUT_HEADER64:
	case AUT_HEADER64_EX:
		/*
		 * The header token is:
		 *	attribute id:		char
		 *	byte count:		int
		 *	version #:		char
		 *	event ID:		short
		 *	ID modifier:		short
		 *	IP address type		int	(_EX only)
		 *	IP address		1/4*int (_EX only)
		 *	seconds (date):		long
		 *	time (microsecs):	long
		 */
		leadin = sizeof (int32_t) + sizeof (char);
		(void) adrf_int32(&adrf, &lsize, 1);
		*buf = (char *)a_calloc(1, (size_t)(lsize + leadin));
		adr_start(&adr, *buf);
		adr_char(&adr, &id, 1);
		adr_int32(&adr, (int32_t *)&lsize, 1);
		if (fread(*buf + leadin, sizeof (char), lsize - leadin, fp) !=
			lsize - leadin) {
			(void) sprintf(errbuf,
				gettext("header token read failure in %s"), fn);
			error_str = errbuf;
			return (-1);
		}
		return (lsize + leadin);
	case AUT_OTHER_FILE32: {
		int32_t secs, msecs;
		leadin =  2 * sizeof (int32_t) +
				sizeof (short) + sizeof (char);
		(void) adrf_int32(&adrf, (int32_t *)&secs, 1);
		(void) adrf_int32(&adrf, (int32_t *)&msecs, 1);
		(void) adrf_short(&adrf, &ssize, 1);
		*buf = (char *)a_calloc(1, (size_t)(ssize + leadin));
		adr_start(&adr, *buf);
		adr_char(&adr, &id, 1);
		adr_int32(&adr, (int32_t *)&secs, 1);
		adr_int32(&adr, (int32_t *)&msecs, 1);
		adr_short(&adr, &ssize, 1);
		if (fread(*buf + leadin, sizeof (char), ssize, fp) != ssize) {
			error_str = gettext("file token read failure");
			return (-1);
		}
		return (0);		/* done! */
	}
	case AUT_OTHER_FILE64: {
		int64_t secs, msecs;
		leadin =  2 * sizeof (int64_t) +
				sizeof (short) + sizeof (char);
		(void) adrf_int64(&adrf, (int64_t *)&secs, 1);
		(void) adrf_int64(&adrf, (int64_t *)&msecs, 1);
		(void) adrf_short(&adrf, &ssize, 1);
		*buf = (char *)a_calloc(1, (size_t)(ssize + leadin));
		adr_start(&adr, *buf);
		adr_char(&adr, &id, 1);
		adr_int64(&adr, (int64_t *)&secs, 1);
		adr_int64(&adr, (int64_t *)&msecs, 1);
		adr_short(&adr, &ssize, 1);
		if (fread(*buf + leadin, sizeof (char), ssize, fp) != ssize) {
			error_str = gettext("file token read failure");
			return (-1);
		}
		return (0);		/* done! */
	}
	default:
		break;
	}
	error_str = gettext("record begins without proper token");
	return (-1);
}
/*
 * 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 2010 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Extend regular expression matching for the file objects to allow
 * multiple regular expressions (instead of just 1), and to not select
 * regular expressions starting with a "~".  This will allow adminstrator
 * to exclude uninteresting files from the audit trail.
 */

#include <stdlib.h>
#include <string.h>
#include <libgen.h>

struct exp {
	char *s;	/* The regular is expression */
	int not;	/* Exclude if matched? */
	char *comp;	/* The compiled regular expression */
};

static char SEP = ',';		/* separator used between reg exprs */
static char NOT = '~';		/* Character used to exclude rex exprs */
static int compile = 1;		/* Must we compile the expressions */

static char *fexp = NULL;	/* full list of regular expressions */
static int nexp = 1;		/* number of regular expressions in fexp */
static struct exp *p_exp = NULL; /* list of individual expressions */

char *
re_comp2(s)
	char *s;
{
	char *p;
	int i;
	static char *er = "regcmp: error";

	compile = 1;
	if (p_exp != NULL) {
		for (i = 0; i < nexp; i++)
			if (p_exp[i].comp != NULL)
				free(p_exp[i].comp);
		free(p_exp);
	}
	if (fexp != NULL) {
		free(fexp);
	}
	fexp = strdup(s);
	for (p = fexp, nexp = 1; *p != '\0'; p++) {
		if (*p == SEP) {
			nexp++;
		}
	}
	p_exp = (struct exp *)malloc(nexp * sizeof (struct exp));
	for (i = 0, p = fexp; *p != '\0'; i++) {
		p_exp[i].comp = NULL;
		if (*p == NOT) {
			p++;
			p_exp[i].not = 1;
		} else {
			p_exp[i].not = 0;
		}
		p_exp[i].s = p;
		while (*p != SEP && *p != '\0')
			p++;
		if (*p == SEP) {
			*p = '\0';
			p++;
		}
		if (regcmp(p_exp[i].s, NULL) == NULL)
			return (er);
	}
	return (NULL);
}

int
re_exec2(s)
	char *s;
{
	int i;
	char *ret;

	if (compile) {
		for (i = 0; i < nexp; i++) {
			if ((p_exp[i].comp = regcmp(p_exp[i].s, NULL)) == NULL)
				return (-1);
		}
		compile = 0;
	}
	for (i = 0; i < nexp; i++) {
		ret = regex(p_exp[i].comp, s);
		if (ret != NULL) {
			return (!p_exp[i].not);
		}
	}

	/* no match and no more to check */
	return (0);

}
/*
 * 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) 1987-2000 by Sun Microsystems, Inc.
 * All rights reserved.
 */

/*
 * Time management functions for auditreduce.
 */

#include "auditr.h"
#include <locale.h>
#include <libintl.h>

int	derive_date(char *, struct tm *);
void	derive_str(time_t, char *);
int	parse_time(char *, int);
time_t	tm_to_secs(struct tm *);

static int	check_time(struct tm *);
static int	days_in_year(int);
static char *do_invalid(void);
static time_t	local_to_gm(struct tm *);

static char *invalid_inter = NULL;

/*
 * Array of days per month.
 */
static int	days_month[] = {
		31, 28, 31, 30, 31, 30,
		31, 31, 30, 31, 30, 31 };

char *
do_invalid(void)
{
	if (invalid_inter == NULL)
		invalid_inter = gettext("invalid date/time format -");
	return (invalid_inter);
}

/*
 * .func	local_to_gm - local time to gm time.
 * .desc	Convert a local time to Greenwhich Mean Time.
 *	The local time is in the struct tm (time.h) format, which
 *	is easily got from an ASCII input format (10:30:33 Jan 3, 1983).
 *	It works by assuming that the given local time is a GMT time and
 *	then asking the system for the corresponding local time. It then
 *	takes the difference between those two as the correction for
 * 	time zones and daylight savings time. This is accurate unless
 *	the time the user asked for is near a DST switch. Then a
 *	correction is applied - it is assumed that if we can produce
 *	a GMT that, when run through localtime(), is equivalent to the
 *	user's original input, we have an accurate GMT. The applied
 *	correction simply adjusts the GMT by the amount that the derived
 *	localtime was off. See?
 *	It should be noted that when there is DST there is one local hour
 *	a year when time occurs twice (in the fall) and one local hour a
 *	year when time never occurs (in the spring).
 *	memcpy() is used because the calls to gmtime() and localtime()
 *	return pointers to static structures that are overwritten at each
 *	call.
 * .call	ret = local_to_gm(tme).
 * .arg	tme	- ptr to struct tm (see time.h) containing local time.
 * .ret	time_t	- seconds since epoch of equivalent GMT.
 */
time_t
local_to_gm(struct tm *tme)
{
	time_t secs, gsecs, lsecs, save_gsecs;
	time_t r1secs, r2secs;
	struct tm ltime, gtime;

	/*
	 * Get the input time in local and gmtime assuming the input
	 * was GMT (which it probably wasn't).
	 */
	r1secs = secs = tm_to_secs(tme);
	(void) memcpy((void *)&gtime, (void *)gmtime(&secs), sizeof (gtime));
	(void) memcpy((void *)&ltime, (void *)localtime(&secs), sizeof (ltime));

	/*
	 * Get the local and gmtime in seconds, from the above tm structures.
	 * Calculate difference between local and GMT.
	 */
	gsecs = tm_to_secs(&gtime);
	lsecs = tm_to_secs(&ltime);
	secs = lsecs - gsecs;
	gsecs -= secs;
	(void) memcpy((void *)&ltime, (void *)localtime(&gsecs),
	    sizeof (ltime));

	/*
	 * Now get a computed local time from the computed gmtime.
	 */
	save_gsecs = gsecs;
	r2secs = tm_to_secs(&ltime);

	/*
	 * If the user given local time is != computed local time then
	 * we need to try a correction.
	 */
	if (r1secs != r2secs) {
		/*
		 * Use the difference between give localtime and computed
		 * localtime as our correction.
		 */
		if (r2secs > r1secs) {
			gsecs -= r2secs - r1secs;
		} else {
			gsecs += r1secs - r2secs;
		}
		/*
		 * And try the comparison again...
		 */
		(void) memcpy((void *)&ltime, (void *)localtime(&gsecs),
		    sizeof (ltime));
		r2secs = tm_to_secs(&ltime);
		/*
		 * If the correction fails then we are on a DST line
		 * and the user-given local time never happened.
		 * Do the best we can.
		 */
		if (r1secs != r2secs) {
			gsecs = save_gsecs;
		}
	}
	return (gsecs);
}


/*
 * .func	tm_to_secs - convert to seconds.
 * .desc	Convert a tm time structure (time.h) into seconds since
 *	Jan 1, 1970 00:00:00. The time is assumed to be GMT and
 *	so no daylight savings time correction is applied. That
 *	is left up to the system calls (localtime(), gmtime()).
 * .call	ret = tm_to_secs(tme).
 * .arg	tme	- ptr to tm structure.
 * .ret	time_t	- number of seconds.
 */
time_t
tm_to_secs(struct tm *tme)
{
	int	leap_year = FALSE;
	int	days = 0;
	time_t num_sec = 0;

	int	sec = tme->tm_sec;
	int	min = tme->tm_min;
	int	hour = tme->tm_hour;
	int	day = tme->tm_mday;
	int	month = tme->tm_mon;
	int	year = tme->tm_year + 1900;

	if (days_in_year(year) == 366)
		leap_year = TRUE;

	while (year > 1970) {
		num_sec += days_in_year(--year) * 24 * 60 * 60;
	}
	while (month > 0) {
		days = days_month[--month];
		if (leap_year && month == 1) {	/* 1 is February */
			days++;
		}
		num_sec += days * 24 * 60 * 60;
	}
	num_sec += --day * 24 * 60 * 60;
	num_sec += hour * 60 * 60;
	num_sec += min * 60;
	num_sec += sec;

	return (num_sec);
}


/*
 * .func	check_time - check tm structure.
 * .desc	Check the time in a tm structure to see if all of the fields
 *	are within range.
 * .call	err = check_time(tme).
 * .arg	tme	- ptr to struct tm (see time.h).
 * .ret	0	- time is ok.
 * .ret	-1	- time had a problem (description in error_str).
 */
int
check_time(struct tm *tme)
{
	error_str = NULL;

	if (tme->tm_sec < 0 || tme->tm_sec > 59) {
		(void) sprintf(errbuf,
		    gettext("seconds out of range (%d)"), tme->tm_sec + 1);
		error_str = errbuf;
	} else if (tme->tm_min < 0 || tme->tm_min > 59) {
		(void) sprintf(errbuf,
		    gettext("minutes out of range (%d)"), tme->tm_min + 1);
		error_str = errbuf;
	} else if (tme->tm_hour < 0 || tme->tm_hour > 23) {
		(void) sprintf(errbuf,
		    gettext("hours out of range (%d)"), tme->tm_hour + 1);
		error_str = errbuf;
	} else if (tme->tm_mon < 0 || tme->tm_mon > 11) {
		(void) sprintf(errbuf,
		    gettext("months out of range (%d)"), tme->tm_mon + 1);
		error_str = errbuf;
	} else if (tme->tm_year < 0) {
		(void) sprintf(errbuf,
		    gettext("years out of range (%d)"), tme->tm_year);
		error_str = errbuf;
	} else if (tme->tm_mday < 1 || tme->tm_mday > days_month[tme->tm_mon]) {
		if (!(days_in_year(tme->tm_year + 1900) == 366 &&
			tme->tm_mon == 1 &&
			tme->tm_mday == 29)) { /* leap year and February */
			(void) sprintf(errbuf,
			    gettext("days out of range (%d)"), tme->tm_mday);
			error_str = errbuf;
		}
	} else if (tme->tm_wday < 0 || tme->tm_wday > 6) {
		(void) sprintf(errbuf,
		    gettext("weekday out of range (%d)"), tme->tm_wday);
		error_str = errbuf;
	} else if (tme->tm_yday < 0 || tme->tm_yday > 365) {
		(void) sprintf(errbuf,
		    gettext("day of year out of range (%d)"), tme->tm_yday);
		error_str = errbuf;
	}

	if (error_str == NULL)
		return (0);
	else
		return (-1);
}


/*
 * .func parse_time.
 * .desc Parse a user time from the command line. The user time is assumed
 *	to be local time.
 *	Supported formats currently are:
 *	1. 	+xt	- where x is a number and t is a type.
 *		types are - 's' second, 'm' minute, 'h' hour, and 'd' day.
 *	2. 	yymmdd - yyyymmdd.
 *		yymmddhh - yyyymmddhh.
 *		yymmddhhmm - yyyymmddhhmm.
 *		yymmddhhmmss - yyyymmddhhmmss.
 * .call	err = parse_time(str, opt).
 * .arg	str	- ptr to user input string.
 * .arg	opt	- time option being processed.
 * .ret	0	- succesful.
 * .ret	-1	- failure (error message in error_str).
 */
int
parse_time(char *str, int opt)
{
	int	ret, len, factor;
	char	*strxx;
	long	lnum;
	struct tm thentime;

	len = strlen(str);
	/*
	 * If the strlen < 6 then in the "-b +2d" type of format.
	 */
	if (len < 6) {
		if (*str++ != '+') {
			(void) sprintf(errbuf, gettext("%s needs '+' (%s)"),
			    do_invalid(), str);
			error_str = errbuf;
			return (-1);
		}
		if (opt != 'b') {
			(void) sprintf(errbuf,
			    gettext("%s only allowed with 'b' option (%s)"),
			    do_invalid(), str);
			error_str = errbuf;
			return (-1);
		}
		if (m_after == 0) {
			(void) sprintf(errbuf,
			    gettext("must have -a to use -b +nx form (%s)"),
			    str);
			error_str = errbuf;
			return (-1);
		}
		/*
		 * Find out what type of offset it is - 's' 'm' 'h' or 'd'.
		 * Make sure that the offset is all numbers.
		 */
		if ((strxx = strpbrk(str, "dhms")) == NULL) {
			(void) sprintf(errbuf,
			    gettext("%s needs 'd', 'h', 'm', or 's' (%s)"),
			    do_invalid(), str);
			error_str = errbuf;
			return (-1);
		} else {
			ret = *strxx;
			*strxx = '\0';
		}
		if (strlen(str) != strspn(str, "0123456789")) {
			(void) sprintf(errbuf,
			    gettext("%s non-numeric offset (%s)"),
			    do_invalid(), str);
			error_str = errbuf;
			return (-1);
		}
		factor = 1;			/* seconds is default */
		if (ret == 'd')			/* days */
			factor = 24 * 60 * 60;
		else if (ret == 'h')		/* hours */
			factor = 60 * 60;
		else if (ret == 'm')		/* minutes */
			factor = 60;
		lnum = atol(str);
		m_before = m_after + (lnum * factor);
		return (0);
	}
	/*
	 * Must be a specific date/time format.
	 */
	if (derive_date(str, &thentime))
		return (-1);
	/*
	 * For 'd' option clear out the hh:mm:ss to get to the start of the day.
	 * Then add one day's worth of seconds to get the 'b' time.
	 */
	if (opt == 'd') {
		thentime.tm_sec = 0;
		thentime.tm_min = 0;
		thentime.tm_hour = 0;
		m_after = local_to_gm(&thentime);
		m_before = m_after + (24 * 60 * 60);
	} else if (opt == 'a') {
		m_after = local_to_gm(&thentime);
	} else if (opt == 'b') {
		m_before = local_to_gm(&thentime);
	}
	return (0);
}


/*
 * .func	derive_date.
 * .desc	Derive a date/time structure (tm) from a string.
 *	String is in one of these formats:
 *	[yy]yymmddhhmmss
 *	[yy]yymmddhhmm
 *	[yy]yymmddhh
 *	[yy]yymmdd
 * .call	ret = derive_date(str, tme).
 * .arg	str	- ptr to input string.
 * .arg	tme	- ptr to tm structure (time.h).
 * .ret	0	- no errors in string.
 * .ret	-1	- errors in string (description in error_str).
 */
int
derive_date(char *str, struct tm *tme)
{
	char	*strs;
	char	*digits = "0123456789";
	size_t	len;
	struct tm nowtime;

	len = strlen(str);

	if (len != strspn(str, digits)) {
		(void) sprintf(errbuf, gettext("%s not all digits (%s)"),
		    do_invalid(), str);
		error_str = errbuf;
		return (-1);
	}
	if (len % 2) {
		(void) sprintf(errbuf, gettext("%s odd number of digits (%s)"),
		    do_invalid(), str);
		error_str = errbuf;
		return (-1);
	}
	/*
	 * May need larger string storage to add '19' or '20'.
	 */
	strs = (char *)a_calloc(1, len + 4);

	/*
	 * Get current time to see what century it is.
	 */
	(void) memcpy((char *)&nowtime, (char *)gmtime(&time_now),
	    sizeof (nowtime));
	/*
	 * If the year does not begin with '19' or '20', then report
	 * an error and abort.
	 */
	if ((str[0] != '1' || str[1] != '9') &&		/* 19XX */
	    (str[0] != '2' || str[1] != '0')) {		/* 20XX */
		(void) sprintf(errbuf, gettext("invalid year (%c%c%c%c)"),
		    str[0], str[1], str[2], str[3]);
		error_str = errbuf;
		free(strs);
		return (-1);
	}

	len = strlen(str);			/* may have changed */
	if (len < 8 || len > 14) {
		(void) sprintf(errbuf,
			gettext("invalid date/time length (%s)"), str);
		error_str = errbuf;
		free(strs);
		return (-1);
	}
	/* unspecified values go to 0 */
	(void) memset((void *) tme, 0, (size_t)sizeof (*tme));
	(void) strncpy(strs, str, 4);
	strs[4] = '\0';
	tme->tm_year = atoi(strs) - 1900;	/* get the year */
	(void) strncpy(strs, str + 4, 2);
	strs[2] = '\0';
	tme->tm_mon = atoi(strs) - 1;		/* get months */
	(void) strncpy(strs, str + 6, 2);
	strs[2] = '\0';
	tme->tm_mday = atoi(strs);		/* get days */
	if (len >= 10) {			/* yyyymmddhh */
		(void) strncpy(strs, str + 8, 2);
		strs[2] = '\0';
		tme->tm_hour = atoi(strs);	/* get hours */
	}
	if (len >= 12) {			/* yyyymmddhhmm */
		(void) strncpy(strs, str + 10, 2);
		strs[2] = '\0';
		tme->tm_min = atoi(strs);	/* get minutes */
	}
	if (len >= 14) {			/* yyyymmddhhmmss */
		(void) strncpy(strs, str + 12, 2);
		strs[2] = '\0';
		tme->tm_sec = atoi(strs);	/* get seconds */
	}
	free(strs);
	return (check_time(tme));		/* lastly check the ranges */
}


/*
 * .func	derive_str - derive string.
 * .desc	Derive a string representation of a time for a filename.
 *	The output is in the 14 character format yyyymmddhhmmss.
 * .call	derive_str(clock, buf).
 * .arg	clock	- seconds since epoch.
 * .arg	buf	- place to put resultant string.
 * .ret	void.
 */
void
derive_str(time_t clock, char *buf)
{
	struct tm gtime;

	(void) memcpy((void *) & gtime, (void *)gmtime(&clock), sizeof (gtime));

	(void) sprintf(buf, "%4d", gtime.tm_year + 1900);
	(void) sprintf(buf + 4,  "%.2d", gtime.tm_mon + 1);
	(void) sprintf(buf + 6,  "%.2d", gtime.tm_mday);
	(void) sprintf(buf + 8,  "%.2d", gtime.tm_hour);
	(void) sprintf(buf + 10, "%.2d", gtime.tm_min);
	(void) sprintf(buf + 12, "%.2d", gtime.tm_sec);
	buf[14] = '\0';
}


int
days_in_year(int year)
{
	if (isleap(year))
		return (366);

	return (365);
}
/*
 * 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 2010 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright 2012 Milan Jurik. All rights reserved.
 */


/*
 * Token processing for auditreduce.
 */

#include <locale.h>
#include <sys/zone.h>
#include "auditr.h"
#include "toktable.h"

extern int	re_exec2(char *);

static void	anchor_path(char *path);
static char	*collapse_path(char *s);
static void	get_string(adr_t *adr, char **p);
static int	ipc_type_match(int flag, char type);
static void	skip_string(adr_t *adr);
static int	xgeneric(adr_t *adr);

#if	AUDIT_REC
void
print_id(int id)
{
	char *suffix;

	if ((id < 0) || (id > MAXTOKEN) ||
	    (tokentable[id].func == NOFUNC)) {
		(void) fprintf(stderr,
		    "token_processing: token %d not found\n", id);
		return;
	}

	switch (id) {
	case AUT_NEWGROUPS:
		suffix = "_new";
		break;
	case AUT_ATTR32:
		suffix = "32";
		break;
	case AUT_ARG64:
	case AUT_RETURN64:
	case AUT_ATTR64:
	case AUT_HEADER64:
	case AUT_SUBJECT64:
	case AUT_PROCESS64:
	case AUT_OTHER_FILE64:
		suffix = "64";
		break;
	case AUT_SOCKET_EX:
	case AUT_IN_ADDR_EX:
		suffix = "_ex";
		break;
	case AUT_HEADER32_EX:
	case AUT_SUBJECT32_EX:
	case AUT_PROCESS32_EX:
		suffix = "32_ex";
		break;
	case AUT_HEADER64_EX:
	case AUT_SUBJECT64_EX:
	case AUT_PROCESS64_EX:
		suffix = "64_ex";
		break;
	default:
		suffix = "";
		break;
	}
	(void) fprintf(stderr, "token_processing: %s%s\n",
	    tokentable[id].t_name, suffix);
}
#endif	/* AUDIT_REC */

/*
 * Process a token in a record to determine whether the record is interesting.
 */

int
token_processing(adr_t *adr, int tokenid)
{
	if ((tokenid > 0) && (tokenid <= MAXTOKEN) &&
	    (tokentable[tokenid].func != NOFUNC)) {
#if	AUDIT_REC
		print_id(tokenid);
#endif	/* AUDIT_REC */
		return ((*tokentable[tokenid].func)(adr));
	}

	/* here if token id is not in table */
	return (-2);
}


/* There should not be any file or header tokens in the middle of a record */

/* ARGSUSED */
int
file_token(adr_t *adr)
{
	return (-2);
}

/* ARGSUSED */
int
file64_token(adr_t *adr)
{
	return (-2);
}

/* ARGSUSED */
int
header_token(adr_t *adr)
{
	return (-2);
}

/* ARGSUSED */
int
header32_ex_token(adr_t *adr)
{
	return (-2);
}

/* ARGSUSED */
int
header64_ex_token(adr_t *adr)
{
	return (-2);
}

/* ARGSUSED */
int
header64_token(adr_t *adr)
{
	return (-2);
}


/*
 * ======================================================
 *  The following token processing routines return
 *  -1: if the record is not interesting
 *  -2: if an error is found
 * ======================================================
 */

int
trailer_token(adr_t *adr)
{
	short	magic_number;
	uint32_t bytes;

	adrm_u_short(adr, (ushort_t *)&magic_number, 1);
	if (magic_number != AUT_TRAILER_MAGIC) {
		(void) fprintf(stderr, "%s\n",
		    gettext("auditreduce: Bad trailer token"));
		return (-2);
	}
	adrm_u_int32(adr, &bytes, 1);

	return (-1);
}


/*
 * Format of arbitrary data token:
 *	arbitrary data token id	adr char
 * 	how to print		adr_char
 *	basic unit		adr_char
 *	unit count		adr_char, specifying number of units of
 *	data items		depends on basic unit
 */
int
arbitrary_data_token(adr_t *adr)
{
	int	i;
	char	c1;
	short	c2;
	int32_t	c3;
	int64_t c4;
	char	how_to_print, basic_unit, unit_count;

	/* get how_to_print, basic_unit, and unit_count */
	adrm_char(adr, &how_to_print, 1);
	adrm_char(adr, &basic_unit, 1);
	adrm_char(adr, &unit_count, 1);
	for (i = 0; i < unit_count; i++) {
		switch (basic_unit) {
			/* case AUR_BYTE: has same value as AUR_CHAR */
		case AUR_CHAR:
			adrm_char(adr, &c1, 1);
			break;
		case AUR_SHORT:
			adrm_short(adr, &c2, 1);
			break;
		case AUR_INT32:
			adrm_int32(adr, (int32_t *)&c3, 1);
			break;
		case AUR_INT64:
			adrm_int64(adr, (int64_t *)&c4, 1);
			break;
		default:
			return (-2);
		}
	}
	return (-1);
}


/*
 * Format of opaque token:
 *	opaque token id		adr_char
 *	size			adr_short
 *	data			adr_char, size times
 */
int
opaque_token(adr_t *adr)
{
	skip_string(adr);
	return (-1);
}



/*
 * Format of return32 value token:
 * 	return value token id	adr_char
 *	error number		adr_char
 *	return value		adr_u_int32
 */
int
return_value32_token(adr_t *adr)
{
	char		errnum;
	uint32_t	value;

	adrm_char(adr, &errnum, 1);
	adrm_u_int32(adr, &value, 1);
	if ((flags & M_SORF) &&
	    ((global_class & mask.am_success) && (errnum == 0)) ||
	    ((global_class & mask.am_failure) && (errnum != 0))) {
		checkflags |= M_SORF;
	}
	return (-1);
}

/*
 * Format of return64 value token:
 * 	return value token id	adr_char
 *	error number		adr_char
 *	return value		adr_u_int64
 */
int
return_value64_token(adr_t *adr)
{
	char		errnum;
	uint64_t	value;

	adrm_char(adr, &errnum, 1);
	adrm_u_int64(adr, &value, 1);
	if ((flags & M_SORF) &&
	    ((global_class & mask.am_success) && (errnum == 0)) ||
	    ((global_class & mask.am_failure) && (errnum != 0))) {
		checkflags |= M_SORF;
	}
	return (-1);
}


/*
 * Format of sequence token:
 *	sequence token id	adr_char
 *	audit_count		int32_t
 */
int
sequence_token(adr_t *adr)
{
	int32_t	audit_count;

	adrm_int32(adr, &audit_count, 1);
	return (-1);
}


/*
 * Format of text token:
 *	text token id		adr_char
 * 	text			adr_string
 */
int
text_token(adr_t *adr)
{
	skip_string(adr);
	return (-1);
}


/*
 * Format of ip_addr token:
 *	ip token id	adr_char
 *	address		adr_int32
 */
int
ip_addr_token(adr_t *adr)
{
	int32_t	address;

	adrm_char(adr, (char *)&address, 4);

	return (-1);
}

/*
 * Format of ip_addr_ex token:
 *	ip token id	adr_char
 *	ip type		adr_int32
 *	ip address	adr_u_char*type
 */
int
ip_addr_ex_token(adr_t *adr)
{
	int32_t type;
	uchar_t	address[16];

	adrm_int32(adr, (int32_t *)&type, 1);
	adrm_u_char(adr, address, type);

	return (-1);
}

/*
 * Format of ip token:
 *	ip header token id	adr_char
 *	version			adr_char
 *	type of service		adr_char
 *	length			adr_short
 *	id			adr_u_short
 *	offset			adr_u_short
 *	ttl			adr_char
 *	protocol		adr_char
 *	checksum		adr_u_short
 *	source address		adr_int32
 *	destination address	adr_int32
 */
int
ip_token(adr_t *adr)
{
	char	version;
	char	type;
	short	len;
	unsigned short	id, offset, checksum;
	char	ttl, protocol;
	int32_t	src, dest;

	adrm_char(adr, &version, 1);
	adrm_char(adr, &type, 1);
	adrm_short(adr, &len, 1);
	adrm_u_short(adr, &id, 1);
	adrm_u_short(adr, &offset, 1);
	adrm_char(adr, &ttl, 1);
	adrm_char(adr, &protocol, 1);
	adrm_u_short(adr, &checksum, 1);
	adrm_char(adr, (char *)&src, 4);
	adrm_char(adr, (char *)&dest, 4);

	return (-1);
}


/*
 * Format of iport token:
 *	ip port address token id	adr_char
 *	port address			adr_short
 */
int
iport_token(adr_t *adr)
{
	short	address;

	adrm_short(adr, &address, 1);

	return (-1);
}


/*
 * Format of groups token:
 *	group token id		adr_char
 *	group list		adr_int32, 16 times
 */
int
group_token(adr_t *adr)
{
	int	gid[16];
	int	i;
	int	flag = 0;

	for (i = 0; i < 16; i++) {
		adrm_int32(adr, (int32_t *)&gid[i], 1);
		if (flags & M_GROUPR) {
			if ((unsigned short)m_groupr == gid[i])
				flag = 1;
		}
	}

	if (flags & M_GROUPR) {
		if (flag)
			checkflags |= M_GROUPR;
	}
	return (-1);
}

/*
 * Format of newgroups token:
 *	group token id		adr_char
 *	number of groups	adr_short
 *	group list		adr_int32, "number" times
 */
int
newgroup_token(adr_t *adr)
{
	gid_t	gid;
	int	i;
	short int   number;

	adrm_short(adr, &number, 1);

	for (i = 0; i < number; i++) {
		adrm_int32(adr, (int32_t *)&gid, 1);
		if (flags & M_GROUPR) {
			if (m_groupr == gid)
				checkflags |= M_GROUPR;
		}
	}

	return (-1);
}

/*
 * Format of argument32 token:
 *	argument token id	adr_char
 *	argument number		adr_char
 *	argument value		adr_int32
 *	argument description	adr_string
 */
int
argument32_token(adr_t *adr)
{
	char	arg_num;
	int32_t	arg_val;

	adrm_char(adr, &arg_num, 1);
	adrm_int32(adr, &arg_val, 1);
	skip_string(adr);

	return (-1);
}

/*
 * Format of argument64 token:
 *	argument token id	adr_char
 *	argument number		adr_char
 *	argument value		adr_int64
 *	argument description	adr_string
 */
int
argument64_token(adr_t *adr)
{
	char	arg_num;
	int64_t	arg_val;

	adrm_char(adr, &arg_num, 1);
	adrm_int64(adr, &arg_val, 1);
	skip_string(adr);

	return (-1);
}

/*
 * Format of acl token:
 *	acl token id		adr_char
 *	acl type		adr_u_int32
 *	acl value		adr_u_int32 (depends on type)
 *	file mode		adr_u_int (in octal)
 */
int
acl_token(adr_t *adr)
{

	int32_t	id;
	int32_t	mode;
	int32_t	type;

	adrm_int32(adr, &type, 1);
	adrm_int32(adr, &id, 1);
	adrm_int32(adr, &mode, 1);

	return (-1);
}

/*
 * Format of ace token:
 *	ace token id		adr_char
 *	ace who			adr_u_int32 (uid/gid)
 *	access mask		adr_u_int32
 *	ace flags		adr_u_int16
 *	ace type		adr_u_int16
 */
int
ace_token(adr_t *adr)
{
	uid_t		who;
	uint32_t	access_mask;
	uint16_t	flags, type;

	adrm_uid(adr, &who, 1);
	adrm_u_int32(adr, &access_mask, 1);
	adrm_u_short(adr, &flags, 1);
	adrm_u_short(adr, &type, 1);

	return (-1);
}

/*
 * Format of attribute token: (old pre SunOS 5.7 format)
 *	attribute token id	adr_char
 * 	mode			adr_int32 (printed in octal)
 *	uid			adr_int32
 *	gid			adr_int32
 *	file system id		adr_int32
 *	node id			adr_int32
 *	device			adr_int32
 */
int
attribute_token(adr_t *adr)
{
	int32_t	dev;
	int32_t	file_sysid;
	int32_t	gid;
	int32_t	mode;
	int32_t	nodeid;
	int32_t	uid;

	adrm_int32(adr, &mode, 1);
	adrm_int32(adr, &uid, 1);
	adrm_int32(adr, &gid, 1);
	adrm_int32(adr, &file_sysid, 1);
	adrm_int32(adr, &nodeid, 1);
	adrm_int32(adr, &dev, 1);

	if (!new_mode && (flags & M_USERE)) {
		if (m_usere == uid)
			checkflags |= M_USERE;
	}
	if (!new_mode && (flags & M_GROUPE)) {
		if (m_groupe == gid)
			checkflags |= M_GROUPE;
	}

	if (flags & M_OBJECT) {
		if ((obj_flag & OBJ_FGROUP) &&
		    (obj_group == gid))
			checkflags |= M_OBJECT;
		else if ((obj_flag & OBJ_FOWNER) &&
		    (obj_owner == uid))
			checkflags |= M_OBJECT;
	}
	return (-1);
}

/*
 * Format of attribute32 token:
 *	attribute token id	adr_char
 * 	mode			adr_int32 (printed in octal)
 *	uid			adr_int32
 *	gid			adr_int32
 *	file system id		adr_int32
 *	node id			adr_int64
 *	device			adr_int32
 */
int
attribute32_token(adr_t *adr)
{
	int32_t	dev;
	int32_t	file_sysid;
	int32_t	gid;
	int32_t	mode;
	int64_t	nodeid;
	int32_t	uid;

	adrm_int32(adr, &mode, 1);
	adrm_int32(adr, &uid, 1);
	adrm_int32(adr, &gid, 1);
	adrm_int32(adr, &file_sysid, 1);
	adrm_int64(adr, &nodeid, 1);
	adrm_int32(adr, &dev, 1);

	if (!new_mode && (flags & M_USERE)) {
		if (m_usere == uid)
			checkflags |= M_USERE;
	}
	if (!new_mode && (flags & M_GROUPE)) {
		if (m_groupe == gid)
			checkflags |= M_GROUPE;
	}

	if (flags & M_OBJECT) {
		if ((obj_flag & OBJ_FGROUP) &&
		    (obj_group == gid))
			checkflags |= M_OBJECT;
		else if ((obj_flag & OBJ_FOWNER) &&
		    (obj_owner == uid))
			checkflags |= M_OBJECT;
	}
	return (-1);
}

/*
 * Format of attribute64 token:
 *	attribute token id	adr_char
 * 	mode			adr_int32 (printed in octal)
 *	uid			adr_int32
 *	gid			adr_int32
 *	file system id		adr_int32
 *	node id			adr_int64
 *	device			adr_int64
 */
int
attribute64_token(adr_t *adr)
{
	int64_t	dev;
	int32_t	file_sysid;
	int32_t	gid;
	int32_t	mode;
	int64_t	nodeid;
	int32_t	uid;

	adrm_int32(adr, &mode, 1);
	adrm_int32(adr, &uid, 1);
	adrm_int32(adr, &gid, 1);
	adrm_int32(adr, &file_sysid, 1);
	adrm_int64(adr, &nodeid, 1);
	adrm_int64(adr, &dev, 1);

	if (!new_mode && (flags & M_USERE)) {
		if (m_usere == uid)
			checkflags |= M_USERE;
	}
	if (!new_mode && (flags & M_GROUPE)) {
		if (m_groupe == gid)
			checkflags |= M_GROUPE;
	}

	if (flags & M_OBJECT) {
		if ((obj_flag & OBJ_FGROUP) &&
		    (obj_group == gid))
			checkflags |= M_OBJECT;
		else if ((obj_flag & OBJ_FOWNER) &&
		    (obj_owner == uid))
			checkflags |= M_OBJECT;
	}
	return (-1);
}


/*
 * Format of command token:
 *	attribute token id	adr_char
 *	argc			adr_short
 *	argv len		adr_short	variable amount of argv len
 *	argv text		argv len	and text
 *	.
 *	.
 *	.
 *	envp count		adr_short	variable amount of envp len
 *	envp len		adr_short	and text
 *	envp text		envp		len
 *	.
 *	.
 *	.
 */
int
cmd_token(adr_t *adr)
{
	short	cnt;
	short	i;

	adrm_short(adr, &cnt, 1);

	for (i = 0; i < cnt; i++)
		skip_string(adr);

	adrm_short(adr, &cnt, 1);

	for (i = 0; i < cnt; i++)
		skip_string(adr);

	return (-1);
}


/*
 * Format of exit token:
 *	attribute token id	adr_char
 *	return value		adr_int32
 *	errno			adr_int32
 */
int
exit_token(adr_t *adr)
{
	int32_t	retval;
	int32_t	errno;

	adrm_int32(adr, &retval, 1);
	adrm_int32(adr, &errno, 1);
	return (-1);
}

/*
 * Format of strings array token:
 *	token id		adr_char
 *	count value		adr_int32
 *	strings			null terminated strings
 */
static int
strings_common_token(adr_t *adr)
{
	int count, i;
	char c;

	adrm_int32(adr, (int32_t *)&count, 1);
	for (i = 1; i <= count; i++) {
		adrm_char(adr, &c, 1);
		while (c != (char)0)
			adrm_char(adr, &c, 1);
	}
	/* no dump option here, since we will have variable length fields */
	return (-1);
}

int
path_attr_token(adr_t *adr)
{
	return (strings_common_token(adr));
}

int
exec_args_token(adr_t *adr)
{
	return (strings_common_token(adr));
}

int
exec_env_token(adr_t *adr)
{
	return (strings_common_token(adr));
}

/*
 * Format of liaison token:
 */
int
liaison_token(adr_t *adr)
{
	int32_t	li;

	adrm_int32(adr, &li, 1);
	return (-1);
}


/*
 * Format of path token:
 *	path				adr_string
 */
int
path_token(adr_t *adr)
{
	if ((flags & M_OBJECT) && (obj_flag == OBJ_PATH)) {
		char *path;

		get_string(adr, &path);
		if (path[0] != '/')
			/*
			 * anchor the path. user apps may not do it.
			 */
			anchor_path(path);
		/*
		 * match against the collapsed path. that is what user sees.
		 */
		if (re_exec2(collapse_path(path)) == 1)
			checkflags |= M_OBJECT;
		free(path);
	} else {
		skip_string(adr);
	}
	return (-1);
}


/*
 * Format of System V IPC permission token:
 *	System V IPC permission token id	adr_char
 * 	uid					adr_int32
 *	gid					adr_int32
 *	cuid					adr_int32
 *	cgid					adr_int32
 *	mode					adr_int32
 *	seq					adr_int32
 *	key					adr_int32
 */
int
s5_IPC_perm_token(adr_t *adr)
{
	int32_t	uid, gid, cuid, cgid, mode, seq;
	int32_t	key;

	adrm_int32(adr, &uid, 1);
	adrm_int32(adr, &gid, 1);
	adrm_int32(adr, &cuid, 1);
	adrm_int32(adr, &cgid, 1);
	adrm_int32(adr, &mode, 1);
	adrm_int32(adr, &seq, 1);
	adrm_int32(adr, &key, 1);

	if (!new_mode && (flags & M_USERE)) {
		if (m_usere == uid)
			checkflags |= M_USERE;
	}

	if (!new_mode && (flags & M_USERE)) {
		if (m_usere == cuid)
			checkflags |= M_USERE;
	}

	if (!new_mode && (flags & M_GROUPR)) {
		if (m_groupr == gid)
			checkflags |= M_GROUPR;
	}

	if (!new_mode && (flags & M_GROUPR)) {
		if (m_groupr == cgid)
			checkflags |= M_GROUPR;
	}

	if ((flags & M_OBJECT) &&
	    ((obj_owner == uid) ||
	    (obj_owner == cuid) ||
	    (obj_group == gid) ||
	    (obj_group == cgid))) {

		switch (obj_flag) {
		case OBJ_MSGGROUP:
		case OBJ_MSGOWNER:
			if (ipc_type_match(OBJ_MSG, ipc_type))
				checkflags |= M_OBJECT;
			break;
		case OBJ_SEMGROUP:
		case OBJ_SEMOWNER:
			if (ipc_type_match(OBJ_SEM, ipc_type))
				checkflags |= M_OBJECT;
			break;
		case OBJ_SHMGROUP:
		case OBJ_SHMOWNER:
			if (ipc_type_match(OBJ_SHM, ipc_type))
				checkflags |= M_OBJECT;
			break;
		}
	}
	return (-1);
}


/*
 * Format of process32 token:
 *	process token id	adr_char
 *	auid			adr_int32
 *	euid			adr_int32
 *	egid 			adr_int32
 * 	ruid			adr_int32
 *	rgid			adr_int32
 * 	pid			adr_int32
 * 	sid			adr_int32
 * 	termid			adr_int32*2
 */
int
process32_token(adr_t *adr)
{
	int32_t	auid, euid, egid, ruid, rgid, pid;
	int32_t	sid;
	int32_t port, machine;

	adrm_int32(adr, &auid, 1);
	adrm_int32(adr, &euid, 1);
	adrm_int32(adr, &egid, 1);
	adrm_int32(adr, &ruid, 1);
	adrm_int32(adr, &rgid, 1);
	adrm_int32(adr, &pid, 1);
	adrm_int32(adr, &sid, 1);
	adrm_int32(adr, &port, 1);
	adrm_int32(adr, &machine, 1);

	if (!new_mode && (flags & M_USERA)) {
		if (m_usera == auid)
			checkflags |= M_USERA;
	}
	if (!new_mode && (flags & M_USERE)) {
		if (m_usere == euid)
			checkflags |= M_USERE;
	}
	if (!new_mode && (flags & M_USERR)) {
		if (m_userr == ruid)
			checkflags |= M_USERR;
	}
	if (!new_mode && (flags & M_GROUPR)) {
		if (m_groupr == rgid)
			checkflags |= M_GROUPR;
	}
	if (!new_mode && (flags & M_GROUPE)) {
		if (m_groupe == egid)
			checkflags |= M_GROUPE;
	}

	if (flags & M_OBJECT) {
		if ((obj_flag & OBJ_PROC) &&
		    (obj_id == pid)) {
			checkflags |= M_OBJECT;
		} else if ((obj_flag & OBJ_PGROUP) &&
		    ((obj_group == egid) ||
		    (obj_group == rgid))) {
			checkflags |= M_OBJECT;
		} else if ((obj_flag & OBJ_POWNER) &&
		    ((obj_owner == euid) ||
		    (obj_group == ruid))) {
			checkflags |= M_OBJECT;
		}
	}
	return (-1);
}

/*
 * Format of process32_ex token:
 *	process token id	adr_char
 *	auid			adr_int32
 *	euid			adr_int32
 *	egid 			adr_int32
 * 	ruid			adr_int32
 *	rgid			adr_int32
 * 	pid			adr_int32
 * 	sid			adr_int32
 * 	termid
 *		port		adr_int32
 *		type		adr_int32
 *		ip address	adr_u_char*type
 */
int
process32_ex_token(adr_t *adr)
{
	int32_t	auid, euid, egid, ruid, rgid, pid;
	int32_t	sid;
	int32_t port, type;
	uchar_t addr[16];

	adrm_int32(adr, &auid, 1);
	adrm_int32(adr, &euid, 1);
	adrm_int32(adr, &egid, 1);
	adrm_int32(adr, &ruid, 1);
	adrm_int32(adr, &rgid, 1);
	adrm_int32(adr, &pid, 1);
	adrm_int32(adr, &sid, 1);
	adrm_int32(adr, &port, 1);
	adrm_int32(adr, &type, 1);
	adrm_u_char(adr, addr, type);

	if (!new_mode && (flags & M_USERA)) {
		if (m_usera == auid)
			checkflags = checkflags | M_USERA;
	}
	if (!new_mode && (flags & M_USERE)) {
		if (m_usere == euid)
			checkflags = checkflags | M_USERE;
	}
	if (!new_mode && (flags & M_USERR)) {
		if (m_userr == ruid)
			checkflags = checkflags | M_USERR;
	}
	if (!new_mode && (flags & M_GROUPR)) {
		if (m_groupr == egid)
			checkflags = checkflags | M_GROUPR;
	}
	if (!new_mode && (flags & M_GROUPE)) {
		if (m_groupe == egid)
			checkflags = checkflags | M_GROUPE;
	}

	if (flags & M_OBJECT) {
		if ((obj_flag & OBJ_PROC) &&
		    (obj_id == pid)) {
			checkflags = checkflags | M_OBJECT;
		} else if ((obj_flag & OBJ_PGROUP) &&
		    ((obj_group == egid) ||
		    (obj_group == rgid))) {
			checkflags = checkflags | M_OBJECT;
		} else if ((obj_flag & OBJ_POWNER) &&
		    ((obj_owner == euid) ||
		    (obj_group == ruid))) {
			checkflags = checkflags | M_OBJECT;
		}
	}
	return (-1);
}

/*
 * Format of process64 token:
 *	process token id	adr_char
 *	auid			adr_int32
 *	euid			adr_int32
 *	egid 			adr_int32
 * 	ruid			adr_int32
 *	rgid			adr_int32
 * 	pid			adr_int32
 * 	sid			adr_int32
 * 	termid			adr_int64+adr_int32
 */
int
process64_token(adr_t *adr)
{
	int32_t	auid, euid, egid, ruid, rgid, pid;
	int32_t	sid;
	int64_t port;
	int32_t machine;

	adrm_int32(adr, &auid, 1);
	adrm_int32(adr, &euid, 1);
	adrm_int32(adr, &egid, 1);
	adrm_int32(adr, &ruid, 1);
	adrm_int32(adr, &rgid, 1);
	adrm_int32(adr, &pid, 1);
	adrm_int32(adr, &sid, 1);
	adrm_int64(adr, &port, 1);
	adrm_int32(adr, &machine, 1);

	if (!new_mode && (flags & M_USERA)) {
		if (m_usera == auid)
			checkflags |= M_USERA;
	}
	if (!new_mode && (flags & M_USERE)) {
		if (m_usere == euid)
			checkflags |= M_USERE;
	}
	if (!new_mode && (flags & M_USERR)) {
		if (m_userr == ruid)
			checkflags |= M_USERR;
	}
	if (!new_mode && (flags & M_GROUPR)) {
		if (m_groupr == rgid)
			checkflags |= M_GROUPR;
	}
	if (!new_mode && (flags & M_GROUPE)) {
		if (m_groupe == egid)
			checkflags |= M_GROUPE;
	}

	if (flags & M_OBJECT) {
		if ((obj_flag & OBJ_PROC) &&
		    (obj_id == pid)) {
			checkflags |= M_OBJECT;
		} else if ((obj_flag & OBJ_PGROUP) &&
		    ((obj_group == egid) ||
		    (obj_group == rgid))) {
			checkflags |= M_OBJECT;
		} else if ((obj_flag & OBJ_POWNER) &&
		    ((obj_owner == euid) ||
		    (obj_group == ruid))) {
			checkflags |= M_OBJECT;
		}
	}
	return (-1);
}

/*
 * Format of process64_ex token:
 *	process token id	adr_char
 *	auid			adr_int32
 *	euid			adr_int32
 *	egid 			adr_int32
 * 	ruid			adr_int32
 *	rgid			adr_int32
 * 	pid			adr_int32
 * 	sid			adr_int32
 * 	termid
 * 		port		adr_int64
 * 		type		adr_int32
 * 		ip address	adr_u_char*type
 */
int
process64_ex_token(adr_t *adr)
{
	int32_t	auid, euid, egid, ruid, rgid, pid;
	int32_t	sid;
	int64_t port;
	int32_t type;
	uchar_t addr[16];

	adrm_int32(adr, &auid, 1);
	adrm_int32(adr, &euid, 1);
	adrm_int32(adr, &egid, 1);
	adrm_int32(adr, &ruid, 1);
	adrm_int32(adr, &rgid, 1);
	adrm_int32(adr, &pid, 1);
	adrm_int32(adr, &sid, 1);
	adrm_int64(adr, &port, 1);
	adrm_int32(adr, &type, 1);
	adrm_u_char(adr, addr, type);

	if (!new_mode && (flags & M_USERA)) {
		if (m_usera == auid)
			checkflags = checkflags | M_USERA;
	}
	if (!new_mode && (flags & M_USERE)) {
		if (m_usere == euid)
			checkflags = checkflags | M_USERE;
	}
	if (!new_mode && (flags & M_USERR)) {
		if (m_userr == ruid)
			checkflags = checkflags | M_USERR;
	}
	if (!new_mode && (flags & M_GROUPR)) {
		if (m_groupr == egid)
			checkflags = checkflags | M_GROUPR;
	}
	if (!new_mode && (flags & M_GROUPE)) {
		if (m_groupe == egid)
			checkflags = checkflags | M_GROUPE;
	}

	if (flags & M_OBJECT) {
		if ((obj_flag & OBJ_PROC) &&
		    (obj_id == pid)) {
			checkflags = checkflags | M_OBJECT;
		} else if ((obj_flag & OBJ_PGROUP) &&
		    ((obj_group == egid) ||
		    (obj_group == rgid))) {
			checkflags = checkflags | M_OBJECT;
		} else if ((obj_flag & OBJ_POWNER) &&
		    ((obj_owner == euid) ||
		    (obj_group == ruid))) {
			checkflags = checkflags | M_OBJECT;
		}
	}
	return (-1);
}

/*
 * Format of System V IPC token:
 *	System V IPC token id	adr_char
 *	object id		adr_int32
 */
int
s5_IPC_token(adr_t *adr)
{
	int32_t	ipc_id;

	adrm_char(adr, &ipc_type, 1);	/* Global */
	adrm_int32(adr, &ipc_id, 1);

	if ((flags & M_OBJECT) &&
	    ipc_type_match(obj_flag, ipc_type) &&
	    (obj_id == ipc_id))
		checkflags |= M_OBJECT;

	return (-1);
}


/*
 * Format of socket token:
 *	socket_type		adrm_short
 *	remote_port		adrm_short
 *	remote_inaddr		adrm_int32
 */
int
socket_token(adr_t *adr)
{
	short	socket_type;
	short	remote_port;
	int32_t	remote_inaddr;

	adrm_short(adr, &socket_type, 1);
	adrm_short(adr, &remote_port, 1);
	adrm_char(adr, (char *)&remote_inaddr, 4);

	if ((flags & M_OBJECT) && (obj_flag == OBJ_SOCK)) {
		if (socket_flag == SOCKFLG_MACHINE) {
			if (remote_inaddr == obj_id)
				checkflags |= M_OBJECT;
		} else if (socket_flag == SOCKFLG_PORT) {
			if (remote_port == obj_id)
				checkflags |= M_OBJECT;
		}
	}
	return (-1);
}


/*
 * Format of socket_ex token:
 *	socket_domain		adrm_short
 *	socket_type		adrm_short
 *	address_type		adrm_short
 *	local_port		adrm_short
 *	local_inaddr		adrm_u_char*address_type
 *	remote_port		adrm_short
 *	remote_inaddr		adrm_u_char*address_type
 */
int
socket_ex_token(adr_t *adr)
{
	short	socket_domain;
	short	socket_type;
	short	ip_size;
	short	local_port;
	uchar_t	local_inaddr[16];
	short	remote_port;
	uchar_t	remote_inaddr[16];
	uchar_t	*caddr = (uchar_t *)&obj_id;

	adrm_short(adr, &socket_domain, 1);
	adrm_short(adr, &socket_type, 1);
	adrm_short(adr, &ip_size, 1);

	/* validate ip size */
	if ((ip_size != AU_IPv6) && (ip_size != AU_IPv4))
		return (0);

	adrm_short(adr, &local_port, 1);
	adrm_char(adr, (char *)local_inaddr, ip_size);

	adrm_short(adr, &remote_port, 1);
	adrm_char(adr, (char *)remote_inaddr, ip_size);

	/* if IP type mis-match, then nothing to do */
	if (ip_size != ip_type)
		return (-1);

	if ((flags & M_OBJECT) && (obj_flag == OBJ_SOCK)) {
		if (socket_flag == SOCKFLG_MACHINE) {
			if (ip_type == AU_IPv6) {
				caddr = (uchar_t *)ip_ipv6;
			}
			if ((memcmp(local_inaddr, caddr, ip_type) == 0) ||
			    (memcmp(remote_inaddr, caddr, ip_type) == 0)) {
				checkflags |= M_OBJECT;
			}
		} else if (socket_flag == SOCKFLG_PORT) {
			if ((local_port == obj_id) || (remote_port == obj_id)) {
				checkflags |= M_OBJECT;
			}
		}
	}
	return (-1);
}


/*
 * Format of subject32 token:
 *	subject token id	adr_char
 *	auid			adr_int32
 *	euid			adr_int32
 *	egid 			adr_int32
 * 	ruid			adr_int32
 *	rgid			adr_int32
 * 	pid			adr_int32
 * 	sid			adr_int32
 * 	termid			adr_int32*2
 */
int
subject32_token(adr_t *adr)
{
	int32_t	auid, euid, egid, ruid, rgid, pid;
	int32_t	sid;
	int32_t port, machine;

	adrm_int32(adr, &auid, 1);
	adrm_int32(adr, &euid, 1);
	adrm_int32(adr, &egid, 1);
	adrm_int32(adr, &ruid, 1);
	adrm_int32(adr, &rgid, 1);
	adrm_int32(adr, &pid, 1);
	adrm_int32(adr, &sid, 1);
	adrm_int32(adr, &port, 1);
	adrm_int32(adr, &machine, 1);

	if (flags & M_SUBJECT) {
		if (subj_id == pid)
			checkflags |= M_SUBJECT;
	}
	if (flags & M_USERA) {
		if (m_usera == auid)
			checkflags |= M_USERA;
	}
	if (flags & M_USERE) {
		if (m_usere == euid)
			checkflags |= M_USERE;
	}
	if (flags & M_USERR) {
		if (m_userr == ruid)
			checkflags |= M_USERR;
	}
	if (flags & M_GROUPR) {
		if (m_groupr == rgid)
			checkflags |= M_GROUPR;
	}
	if (flags & M_GROUPE) {
		if (m_groupe == egid)
			checkflags |= M_GROUPE;
	}
	if (flags & M_SID) {
		if (m_sid == (au_asid_t)sid)
			checkflags |= M_SID;
	}
	return (-1);
}

/*
 * Format of subject32_ex token:
 *	subject token id	adr_char
 *	auid			adr_int32
 *	euid			adr_int32
 *	egid 			adr_int32
 * 	ruid			adr_int32
 *	rgid			adr_int32
 * 	pid			adr_int32
 * 	sid			adr_int32
 * 	termid
 * 		port		adr_int32
 * 		type		adr_int32
 * 		ip address	adr_u_char*type
 */
int
subject32_ex_token(adr_t *adr)
{
	int32_t	auid, euid, egid, ruid, rgid, pid;
	int32_t	sid;
	int32_t port, type;
	uchar_t addr[16];

	adrm_int32(adr, &auid, 1);
	adrm_int32(adr, &euid, 1);
	adrm_int32(adr, &egid, 1);
	adrm_int32(adr, &ruid, 1);
	adrm_int32(adr, &rgid, 1);
	adrm_int32(adr, &pid, 1);
	adrm_int32(adr, &sid, 1);
	adrm_int32(adr, &port, 1);
	adrm_int32(adr, &type, 1);
	adrm_u_char(adr, addr, type);

	if (flags & M_SUBJECT) {
		if (subj_id == pid)
			checkflags = checkflags | M_SUBJECT;
	}
	if (flags & M_USERA) {
		if (m_usera == auid)
			checkflags = checkflags | M_USERA;
	}
	if (flags & M_USERE) {
		if (m_usere == euid)
			checkflags = checkflags | M_USERE;
	}
	if (flags & M_USERR) {
		if (m_userr == ruid)
			checkflags = checkflags | M_USERR;
	}
	if (flags & M_GROUPR) {
		if (m_groupr == egid)
			checkflags = checkflags | M_GROUPR;
	}
	if (flags & M_GROUPE) {
		if (m_groupe == egid)
			checkflags = checkflags | M_GROUPE;
	}
	if (flags & M_SID) {
		if (m_sid == (au_asid_t)sid)
			checkflags = checkflags | M_SID;
	}
	return (-1);
}

/*
 * Format of subject64 token:
 *	subject token id	adr_char
 *	auid			adr_int32
 *	euid			adr_int32
 *	egid 			adr_int32
 * 	ruid			adr_int32
 *	rgid			adr_int32
 * 	pid			adr_int32
 * 	sid			adr_int32
 * 	termid			adr_int64+adr_int32
 */
int
subject64_token(adr_t *adr)
{
	int32_t	auid, euid, egid, ruid, rgid, pid;
	int32_t	sid;
	int64_t port;
	int32_t machine;

	adrm_int32(adr, &auid, 1);
	adrm_int32(adr, &euid, 1);
	adrm_int32(adr, &egid, 1);
	adrm_int32(adr, &ruid, 1);
	adrm_int32(adr, &rgid, 1);
	adrm_int32(adr, &pid, 1);
	adrm_int32(adr, &sid, 1);
	adrm_int64(adr, &port, 1);
	adrm_int32(adr, &machine, 1);

	if (flags & M_SUBJECT) {
		if (subj_id == pid)
			checkflags |= M_SUBJECT;
	}
	if (flags & M_USERA) {
		if (m_usera == auid)
			checkflags |= M_USERA;
	}
	if (flags & M_USERE) {
		if (m_usere == euid)
			checkflags |= M_USERE;
	}
	if (flags & M_USERR) {
		if (m_userr == ruid)
			checkflags |= M_USERR;
	}
	if (flags & M_GROUPR) {
		if (m_groupr == rgid)
			checkflags |= M_GROUPR;
	}
	if (flags & M_GROUPE) {
		if (m_groupe == egid)
			checkflags |= M_GROUPE;
	}
	if (flags & M_SID) {
		if (m_sid == (au_asid_t)sid)
			checkflags |= M_SID;
	}
	return (-1);
}

/*
 * Format of subject64_ex token:
 *	subject token id	adr_char
 *	auid			adr_int32
 *	euid			adr_int32
 *	egid 			adr_int32
 * 	ruid			adr_int32
 *	rgid			adr_int32
 * 	pid			adr_int32
 * 	sid			adr_int32
 * 	termid
 * 		port		adr_int64
 * 		type		adr_int32
 * 		ip address	adr_u_char*type
 */
int
subject64_ex_token(adr_t *adr)
{
	int32_t	auid, euid, egid, ruid, rgid, pid;
	int32_t	sid;
	int64_t port;
	int32_t type;
	uchar_t	addr[16];

	adrm_int32(adr, &auid, 1);
	adrm_int32(adr, &euid, 1);
	adrm_int32(adr, &egid, 1);
	adrm_int32(adr, &ruid, 1);
	adrm_int32(adr, &rgid, 1);
	adrm_int32(adr, &pid, 1);
	adrm_int32(adr, &sid, 1);
	adrm_int64(adr, &port, 1);
	adrm_int32(adr, &type, 1);
	adrm_u_char(adr, addr, type);

	if (flags & M_SUBJECT) {
		if (subj_id == pid)
			checkflags = checkflags | M_SUBJECT;
	}
	if (flags & M_USERA) {
		if (m_usera == auid)
			checkflags = checkflags | M_USERA;
	}
	if (flags & M_USERE) {
		if (m_usere == euid)
			checkflags = checkflags | M_USERE;
	}
	if (flags & M_USERR) {
		if (m_userr == ruid)
			checkflags = checkflags | M_USERR;
	}
	if (flags & M_GROUPR) {
		if (m_groupr == egid)
			checkflags = checkflags | M_GROUPR;
	}
	if (flags & M_GROUPE) {
		if (m_groupe == egid)
			checkflags = checkflags | M_GROUPE;
	}
	if (flags & M_SID) {
		if (m_sid == (au_asid_t)sid)
			checkflags = checkflags | M_SID;
	}
	return (-1);
}

/*
 * -----------------------------------------------------------------------
 * tid_token(): Process tid token and display contents
 *
 * Format of tid token:
 *	tid token id			adr_char
 * 	address type			adr_char
 *	For address type of AU_IPADR...
 *		remote port		adr_short
 *		local port		adr_short
 *		IP type			adr_int32
 *		IP addr			adr_int32 if IPv4
 *		IP addr			4 x adr_int32 if IPv6
 * address types other than AU_IPADR are not yet defined
 * -----------------------------------------------------------------------
 */
int
tid_token(adr_t *adr)
{
	int32_t	address[4];
	int32_t	ip_type;
	char	tid_type;
	short	rport;
	short	lport;

	adrm_char(adr, &tid_type, 1);
	switch (tid_type) {
	case AU_IPADR:
		adrm_short(adr, &rport, 1);
		adrm_short(adr, &lport, 1);
		adrm_int32(adr, &ip_type, 1);
		adrm_char(adr, (char *)&address, ip_type);
		break;
	default:
		return (0);
	}
	return (-1);
}

/*
 * -----------------------------------------------------------------------
 * zonename_token(): Process zonename token and display contents
 *
 * Format of zonename token:
 *	zonename token id		adr_char
 * 	zone name			adr_string
 * -----------------------------------------------------------------------
 */
int
zonename_token(adr_t *adr)
{
	char	*name;

	if (flags & M_ZONENAME) {
		get_string(adr, &name);
		if (strncmp(zonename, name, ZONENAME_MAX) == 0)
			checkflags |= M_ZONENAME;
		free(name);
	} else {
		skip_string(adr);
	}
	return (-1);
}

/*
 * fmri_token():
 *
 * Format of fmri token:
 * 	fmri				adr_string
 */
int
fmri_token(adr_t *adr)
{
	if ((flags & M_OBJECT) && (obj_flag == OBJ_FMRI)) {
		char	*fmri_name;

		get_string(adr, &fmri_name);

		/* match token against service instance */
		if (scf_cmp_pattern(fmri_name, &fmri) == 1) {
			checkflags |= M_OBJECT;
		}
		free(fmri_name);
	} else {
		skip_string(adr);
	}
	return (-1);
}

/*
 * Format of xatom token:
 */
int
xatom_token(adr_t *adr)
{
	skip_string(adr);

	return (-1);
}

/*
 * Format of xselect token:
 */
int
xselect_token(adr_t *adr)
{
	skip_string(adr);
	skip_string(adr);
	skip_string(adr);

	return (-1);
}

/*
 * anchor a path name with a slash
 * assume we have enough space
 */
void
anchor_path(char *path)
{
	(void) memmove((void *)(path + 1), (void *)path, strlen(path) + 1);
	*path = '/';
}


/*
 * copy path to collapsed path.
 * collapsed path does not contain:
 *	successive slashes
 *	instances of dot-slash
 *	instances of dot-dot-slash
 * passed path must be anchored with a '/'
 */
char *
collapse_path(char *s)
{
	int	id;	/* index of where we are in destination string */
	int	is;	/* index of where we are in source string */
	int	slashseen;	/* have we seen a slash */
	int	ls;		/* length of source string */

	ls = strlen(s) + 1;

	slashseen = 0;
	for (is = 0, id = 0; is < ls; is++) {
		/* thats all folks, we've reached the end of input */
		if (s[is] == '\0') {
			if (id > 1 && s[id-1] == '/') {
				--id;
			}
			s[id++] = '\0';
			break;
		}
		/* previous character was a / */
		if (slashseen) {
			if (s[is] == '/')
				continue;	/* another slash, ignore it */
		} else if (s[is] == '/') {
			/* we see a /, just copy it and try again */
			slashseen = 1;
			s[id++] = '/';
			continue;
		}
		/* /./ seen */
		if (s[is] == '.' && s[is+1] == '/') {
			is += 1;
			continue;
		}
		/* XXX/. seen */
		if (s[is] == '.' && s[is+1] == '\0') {
			if (id > 1)
				id--;
			continue;
		}
		/* XXX/.. seen */
		if (s[is] == '.' && s[is+1] == '.' && s[is+2] == '\0') {
			is += 1;
			if (id > 0)
				id--;
			while (id > 0 && s[--id] != '/')
				;
			id++;
			continue;
		}
		/* XXX/../ seen */
		if (s[is] == '.' && s[is+1] == '.' && s[is+2] == '/') {
			is += 2;
			if (id > 0)
				id--;
			while (id > 0 && s[--id] != '/')
				;
			id++;
			continue;
		}
		while (is < ls && (s[id++] = s[is++]) != '/')
			;
		is--;
	}
	return (s);
}


int
ipc_type_match(int flag, char type)
{
	if (flag == OBJ_SEM && type == AT_IPC_SEM)
		return (1);

	if (flag == OBJ_MSG && type == AT_IPC_MSG)
		return (1);

	if (flag == OBJ_SHM && type == AT_IPC_SHM)
		return (1);

	return (0);
}


void
skip_string(adr_t *adr)
{
	ushort_t	c;

	adrm_u_short(adr, &c, 1);
	adr->adr_now += c;
}


void
get_string(adr_t *adr, char **p)
{
	ushort_t	c;

	adrm_u_short(adr, &c, 1);
	*p = a_calloc(1, (size_t)c);
	adrm_char(adr, *p, c);
}


/*
 * Format of host token:
 *	host  		ard_uint32
 */
int
host_token(adr_t *adr)
{
	uint32_t host;

	adrm_u_int32(adr, &host, 1);

	return (-1);
}

/*
 * Format of useofauth token:
 *	uauth token id		adr_char
 * 	uauth			adr_string
 */
int
useofauth_token(adr_t *adr)
{
	skip_string(adr);
	return (-1);
}

/*
 * Format of user token:
 *	user token id		adr_char
 *	uid			adr_uid
 * 	username		adr_string
 */
int
user_token(adr_t *adr)
{
	uid_t	uid;

	adrm_uid(adr, &uid, 1);
	skip_string(adr);

	if ((flags & M_OBJECT) && (obj_flag == OBJ_USER) &&
	    (uid == obj_user)) {
		checkflags |= M_OBJECT;
	}

	return (-1);
}

int
xcolormap_token(adr_t *adr)
{
	return (xgeneric(adr));
}

int
xcursor_token(adr_t *adr)
{
	return (xgeneric(adr));
}

int
xfont_token(adr_t *adr)
{
	return (xgeneric(adr));
}

int
xgc_token(adr_t *adr)
{
	return (xgeneric(adr));
}

int
xpixmap_token(adr_t *adr)
{
	return (xgeneric(adr));
}

int
xwindow_token(adr_t *adr)
{
	return (xgeneric(adr));
}


/*
 * Format of xgeneric token:
 *	XID			adr_int32
 *	creator UID		adr_int32
 *
 * Includes:  xcolormap, xcursor, xfont, xgc, xpixmap, and xwindow
 */
int
xgeneric(adr_t *adr)
{
	int32_t xid;
	int32_t uid;

	adrm_int32(adr, &xid, 1);
	adrm_int32(adr, &uid, 1);

	if (flags & M_USERE) {
		if (m_usere == uid)
			checkflags = checkflags | M_USERE;
	}

	return (-1);
}


/*
 * Format of xproperty token:
 *	XID			adr_int32
 *	creator UID		adr_int32
 *	atom string		adr_string
 */
int
xproperty_token(adr_t *adr)
{
	int32_t	xid;
	int32_t uid;

	adrm_int32(adr, &xid, 1);
	adrm_int32(adr, &uid, 1);
	skip_string(adr);

	if (flags & M_USERE) {
		if (m_usere == uid)
			checkflags = checkflags | M_USERE;
	}

	return (-1);
}


/*
 * Format of xclient token:
 * 	xclient id		adr_int32
 */
int
xclient_token(adr_t *adr)
{
	int32_t	client_id;

	adrm_int32(adr, &client_id, 1);

	return (-1);
}

/*
 * Format of privilege set token:
 *	priv_set type		string
 *	priv_set		string
 */

int
privilege_token(adr_t *adr)
{
	skip_string(adr);	/* set type name */
	skip_string(adr);	/* privilege set */
	return (-1);
}

/*
 * Format of security flags token:
 *	security flag set		string
 *	security flags		string
 */

int
secflags_token(adr_t *adr)
{
	skip_string(adr);	/* set name */
	skip_string(adr);	/* security flags */
	return (-1);
}

/*
 * Format of label token:
 *      label ID                1 byte
 *      compartment length      1 byte
 *      classification          2 bytes
 *      compartment words       <compartment length> * 4 bytes
 */
int
label_token(adr_t *adr)
{
	static m_label_t *label = NULL;
	static size32_t l_size;
	int len;

	if (label == NULL) {
		label = m_label_alloc(MAC_LABEL);
		l_size = blabel_size() - 4;
	}

	if (label == NULL) {
		/* out of memory, should never happen; skip label */
		char	l;	/* length */

		adr->adr_now += sizeof (char);
		adrm_char(adr, (char *)&l, 1);
		adr->adr_now += sizeof (short) + (4 * l);
		return (-1);
	}

	adrm_char(adr, (char *)label, 4);
	len = (int)(((char *)label)[1] * 4);
	if (len > l_size) {
		return (-1);
	}
	adrm_char(adr, &((char *)label)[4], len);

	if (flags & M_LABEL) {
		if (blinrange(label, m_label))
			checkflags = checkflags | M_LABEL;
	}

	return (-1);
}


/*
 * Format of useofpriv token:
 *	success/failure		adr_char
 *	privilege(s)		adr_string
 */
/* ARGSUSED */
int
useofpriv_token(adr_t *adr)
{
	char	flag;

	adrm_char(adr, &flag, 1);
	skip_string(adr);
	return (-1);
}