|
root / base / usr / src / lib / libtsol
libtsol Plain Text 4965 lines 120.7 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
#
# 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.
#

include ../Makefile.lib

HDRS =		label.h
HDRDIR =	common
# Hammerhead: amd64-only
SUBDIRS = $(MACH64)

POFILE =	libtsol.po
MSGFILES =	common/btos.c common/private.c common/stob.c
XGETFLAGS =	-a

all :		TARGET = all
clean :	TARGET = clean
clobber :	TARGET = clobber
install	:	TARGET = install

.KEEP_STATE:

# Override so that label.h gets installed where expected.
ROOTHDRDIR=	$(ROOT)/usr/include/tsol

all clean clobber install: $(SUBDIRS)

install_h: $(ROOTHDRS)

check: $(CHECKHDRS)

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

_msg:		$(MSGDOMAINPOFILE)

$(SUBDIRS):	FRC
	@cd $@; pwd; $(MAKE) $(TARGET)

FRC:

include $(SRC)/Makefile.msg.targ
include $(SRC)/lib/Makefile.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 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# Copyright (c) 2018, Joyent, Inc.

LIBRARY =	libtsol.a
VERS =		.2

COMMONOBJS = \
	blabel.o ltos.o stol.o

NONCOMMONOBJS = \
	btohex.o btos.o call_labeld.o \
	getlabel.o getplabel.o hextob.o \
	misc.o getpathbylabel.o private.o privlib.o \
	setflabel.o stob.o zone.o \

OBJECTS = $(NONCOMMONOBJS) $(COMMONOBJS)

include ../../Makefile.lib

# install this library in the root filesystem
include ../../Makefile.rootfs

LIBS =		$(DYNLIB)
LDLIBS +=	-lsecdb -lc

SRCDIR =	../common

COMMONDIR=	$(SRC)/common/tsol

CFLAGS +=	$(CCVERBOSE)
CPPFLAGS +=	-D_REENTRANT -I$(SRCDIR) -I$(COMMONDIR)

CERRWARN +=	$(CNOWARN_UNINIT)

# not linted
SMATCH=off

.KEEP_STATE:

all: $(LIBS)


# Hammerhead: Split triple-target rule for GNU Make
objs/%.o: $(COMMONDIR)/%.c
	$(COMPILE.c) -o $@ $<
	$(POST_PROCESS_O)

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

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

include ../../Makefile.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.
#

include ../Makefile.com
include ../../Makefile.lib.64

install: all $(ROOTLIBS64) $(ROOTLINKS64) $(ROOTCOMPATLINKS64)
/*
 * 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.
 */

/*
 *      btohex.c - Binary to Hexadecimal string conversion.
 *
 *		These routines convert binary labels into canonical
 *	hexadecimal representations of the binary form.
 */

#include <stdlib.h>
#include <strings.h>
#include <tsol/label.h>
#include <sys/tsol/label_macro.h>

/* 0x + Classification + '-' + ll + '-' + Compartments + end of string */
#define	_HEX_SIZE 2+(sizeof (Classification_t)*2)+4+\
	(sizeof (Compartments_t)*2)+1

static char hex_buf[_HEX_SIZE];

/*
 *	h_alloc - Allocate data storage for a Hexadecimal label string.
 *
 *	Entry	id = Type of label to allocate storage for.
 *		     SUN_SL_ID  - Sensitivity Label.
 *		     SUN_CLR_ID - Clearance.
 *
 *	Returns	NULL, If unable to allocate storage.
 *		Address of buffer.
 *
 *	Calls	malloc;
 */

char *
h_alloc(unsigned char id)
{
	size_t size;

	switch (id) {

	case SUN_SL_ID:
		size = _HEX_SIZE;
		break;

	case SUN_CLR_ID:
		size = _HEX_SIZE;
		break;

	default:
		return (NULL);
	}

	return ((char *)malloc(size));
}


/*
 *	h_free - Free a Hexadecimal label string.
 *
 *	Entry	hex = Hexadecimal label string.
 *
 *	Returns	none.
 *
 *	Calls	free.
 */

void
h_free(char *hex)
{

	if (hex == NULL)
		return;

	free(hex);
}


/*
 *	bsltoh_r - Convert a Sensitivity Label into a Hexadecimal label string.
 *
 *	Entry	label = Sensitivity Label to be translated.
 *		hex = Buffer to place converted label.
 *		len = Length of buffer.
 *
 *	Returns	NULL, If invalid label type.
 *		Address of buffer.
 *
 *	Calls	label_to_str, strncpy.
 */

char *
bsltoh_r(const m_label_t *label, char *hex)
{
	char *h;

	if (label_to_str(label, &h, M_INTERNAL, DEF_NAMES) != 0) {
		free(h);
		return (NULL);
	}

	(void) strncpy(hex, (const char *)h, _HEX_SIZE);
	free(h);
	return (hex);
}


/*
 *	bsltoh - Convert a Sensitivity Label into a Hexadecimal label string.
 *
 *	Entry	label = Sensitivity Label to be translated.
 *
 *	Returns	NULL, If invalid label type.
 *		Address of statically allocated hex label string.
 *
 *	Calls	bsltoh_r.
 *
 *	Uses	hex_buf.
 */

char *
bsltoh(const m_label_t *label)
{

	return (bsltoh_r(label, hex_buf));
}


/*
 *	bcleartoh_r - Convert a Clearance into a Hexadecimal label string.
 *
 *	Entry	clearance = Clearance to be translated.
 *		hex = Buffer to place converted label.
 *		len = Length of buffer.
 *
 *	Returns	NULL, If invalid label type.
 *		Address of buffer.
 *
 *	Calls	label_to_str, strncpy.
 */

char *
bcleartoh_r(const m_label_t *clearance, char *hex)
{
	char *h;

	if (label_to_str(clearance, &h, M_INTERNAL, DEF_NAMES) != 0) {
		free(h);
		return (NULL);
	}

	(void) strncpy(hex, (const char *)h, _HEX_SIZE);
	free(h);
	return (hex);
}


/*
 *	bcleartoh - Convert a Clearance into a Hexadecimal label string.
 *
 *	Entry	clearance = Clearance to be translated.
 *
 *	Returns	NULL, If invalid label type.
 *		Address of statically allocated hex label string.
 *
 *	Calls	bcleartoh_r.
 *
 *	Uses	hex_buf.
 */

char *
bcleartoh(const m_label_t *clearance)
{

	return (bcleartoh_r(clearance, hex_buf));
}
/*
 * 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.
 */

/*
 *      Binary label to label string translations.
 */

#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <wchar.h>

#include <sys/mman.h>

#include <tsol/label.h>

#include "clnt.h"
#include "labeld.h"
#include <sys/tsol/label_macro.h>

#if	!defined(TEXT_DOMAIN)		/* should be defined by Makefiles */
#define	TEXT_DOMAIN "SYS_TEST"
#endif	/* TEXT_DOMAIN */

static bslabel_t slow;	/* static admin_low high sensitivity label */
static bslabel_t shigh;	/* static admin_high sensitivity label */
static bclear_t clrlow, clrhigh; /* static admin_low and admin_high Clearance */

static char	*sstring;	/* return string for sb*tos */
static size_t	ssize;		/* current size of return string */

static int
return_string(char **string, int str_len, char *val)
{
	char	*cpyptr;
	size_t	val_len = strlen(val) + 1;

	if (*string == NULL) {
		if ((*string = malloc(val_len)) == NULL)
			return (0);
	} else if (val_len > str_len) {
		**string = '\0';
		return (0);
	}

	cpyptr = *string;
	bcopy(val, cpyptr, val_len);

	return (val_len);
}

void
set_label_view(uint_t *callflags, uint_t flags)
{
	if (flags&VIEW_INTERNAL) {
		*callflags |= LABELS_VIEW_INTERNAL;
	} else if (flags&VIEW_EXTERNAL) {
		*callflags |= LABELS_VIEW_EXTERNAL;
	}
}

int
alloc_string(char **string, size_t size, char val)
{
	if (*string == NULL) {
		if ((*string = malloc(ALLOC_CHUNK)) == NULL)
			return (0);
	} else {
		if ((*string = realloc(*string, size + ALLOC_CHUNK)) == NULL) {
			**string = val;
			return (0);
		}
	}
	**string = val;
	return (ALLOC_CHUNK);
}

#define	slcall callp->param.acall.cargs.bsltos_arg
#define	slret callp->param.aret.rvals.bsltos_ret
/*
 *	bsltos - Convert Binary Sensitivity Label to Sensitivity Label string.
 *
 *	Entry	label = Binary Sensitivity Label to be converted.
 *		string = NULL ((char *) 0), if memory to be allocated,
 *			 otherwise, pointer to preallocated memory.
 *		str_len = Length of preallocated memory, else ignored.
 *		flags = Logical sum of:
 *				LONG_CLASSIFICATION or SHORT_CLASSIFICATION,
 *				LONG_WORDS or SHORT_WORDS,
 *				VIEW_INTERNAL or VIEW_EXTERNAL, and
 *				NO_CLASSIFICATION.
 *			LONG_CLASSIFICATION, use long classification names.
 *			SHORT_CLASSIFICATION, use short classification
 *						names (default).
 *			NO_CLASSIFICATION, don't translate classification.
 *			LONG_WORDS, use the long form of words (default).
 *			SHORTWORDS, use the short form of words where available.
 *			VIEW_INTERNAL, don't promote/demote admin low/high.
 *			VIEW_EXTERNAL, promote/demote admin low/high.
 *
 *	Exit	string = Sensitivity Label string, or empty string if
 *			 not enough preallocated memory.
 *
 *	Returns	-1, If unable to access label encodings database.
 *		 0, If unable to allocate string,
 *			or allocated string to short
 *			(and **string = '\0').
 *		length (including null) of Sensitivity Label string,
 *			If successful.
 *
 *	Calls	RPC - LABELS_BSLTOS, BCLHIGH, BCLLOW, BCLTOSL, BLEQUAL,
 *			BLTYPE, SETBSLABEL, UCLNT, memcpy, clnt_call,
 *			clnt_perror, malloc, strcat, strlen.
 *
 *	Uses	ADMIN_HIGH, ADMIN_LOW, shigh, slow.
 */

ssize_t
bsltos(const bslabel_t *label, char **string, size_t str_len,
    int flags)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(bsltos_call_t, 0);
	int	rval;

	if (!BLTYPE(label, SUN_SL_ID)) {
		return (-1);
	}

	call.callop = BSLTOS;
	slcall.label = *label;
	slcall.flags = (flags&NO_CLASSIFICATION) ? LABELS_NO_CLASS : 0;
	slcall.flags |= (flags&SHORT_CLASSIFICATION ||
	    !(flags&LONG_CLASSIFICATION)) ? LABELS_SHORT_CLASS : 0;
	slcall.flags |= (flags&SHORT_WORDS && !(flags&LONG_WORDS)) ?
	    LABELS_SHORT_WORDS : 0;
	set_label_view(&slcall.flags, flags);

	if ((rval = __call_labeld(&callp, &bufsize, &datasize)) == SUCCESS) {

		if (callp->reterr != 0)
			return (-1);

		/* unpack Sensitivity Label */

		rval = return_string(string, str_len, slret.slabel);

		if (callp != &call)
			(void) munmap((void *)callp, bufsize);
		return (rval);
	} else if (rval == NOSERVER) {
		/* server not present */
		/* special case admin_high and admin_low */

		if (!BLTYPE(&slow, SUN_SL_ID)) {
			/* initialize static labels */

			BSLLOW(&slow);
			BSLHIGH(&shigh);
		}

		if (BLEQUAL(label, &slow)) {
			return (return_string(string, str_len, ADMIN_LOW));
		} else if (BLEQUAL(label, &shigh)) {
			return (return_string(string, str_len, ADMIN_HIGH));
		}
	}
	return (-1);
}  /* bsltos */
#undef	slcall
#undef	slret

#define	clrcall callp->param.acall.cargs.bcleartos_arg
#define	clrret callp->param.aret.rvals.bcleartos_ret
/*
 *	bcleartos - Convert Binary Clearance to Clearance string.
 *
 *	Entry	clearance = Binary Clearance to be converted.
 *		string = NULL ((char *) 0), if memory to be allocated,
 *			 otherwise, pointer to preallocated memory.
 *		str_len = Length of preallocated memory, else ignored.
 *		flags = Logical sum of:
 *				LONG_CLASSIFICATION or SHORT_CLASSIFICATION,
 *				LONG_WORDS or SHORT_WORDS,
 *				VIEW_INTERNAL or VIEW_EXTERNAL.
 *			LONG_CLASSIFICATION, use long classification names.
 *			SHORT_CLASSIFICATION, use short classification
 *						names (default).
 *			LONG_WORDS, use the long form of words (default).
 *			SHORTWORDS, use the short form of words where available.
 *			VIEW_INTERNAL, don't promote/demote admin low/high.
 *			VIEW_EXTERNAL, promote/demote admin low/high.
 *
 *	Exit	string = Clearance string, or empty string if not
 *			enough preallocated memory.
 *
 *	Returns	-1, If unable to access label encodings database.
 *		 0, If unable to allocate string,
 *			or allocated string to short
 *			(and **string = '\0').
 *		length (including null) of Clearance string,
 *			If successful.
 *
 *	Calls	RPC - LABELS_BSLTOS, BCLHIGH, BCLLOW, BCLTOSL, BLEQUAL,
 *			BLTYPE, SETBSLABEL, UCLNT, memcpy, clnt_call,
 *			clnt_perror, malloc, strcat, strlen.
 *
 *	Uses	ADMIN_HIGH, ADMIN_LOW, clrhigh, clrlow.
 */

ssize_t
bcleartos(const bclear_t *clearance, char **string, size_t str_len,
    int flags)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(bcleartos_call_t, 0);
	int	rval;

	if (!BLTYPE(clearance, SUN_CLR_ID)) {
		return (-1);
	}

	call.callop = BCLEARTOS;
	clrcall.clear = *clearance;
	clrcall.flags = (flags&SHORT_CLASSIFICATION ||
	    !(flags&LONG_CLASSIFICATION)) ? LABELS_SHORT_CLASS : 0;
	clrcall.flags |= (flags&SHORT_WORDS && !(flags&LONG_WORDS)) ?
	    LABELS_SHORT_WORDS : 0;
	set_label_view(&clrcall.flags, flags);

	if ((rval = __call_labeld(&callp, &bufsize, &datasize)) == SUCCESS) {

		if (callp->reterr != 0)
			return (-1);

		/* unpack Clearance */

		rval = return_string(string, str_len, clrret.cslabel);

		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (rval);
	} else if (rval == NOSERVER) {
		/* server not present */
		/* special case admin_high and admin_low */

		if (!BLTYPE(&clrlow, SUN_CLR_ID)) {
			/* initialize static labels */

			BCLEARLOW(&clrlow);
			BCLEARHIGH(&clrhigh);
		}
		if (BLEQUAL(clearance, &clrlow)) {
			return (return_string(string, str_len, ADMIN_LOW));
		} else if (BLEQUAL(clearance, &clrhigh)) {
			return (return_string(string, str_len, ADMIN_HIGH));
		}
	}
	return (-1);
}  /* bcleartos */
#undef	clrcall
#undef	clrret

/*
 *	sbsltos - Convert Sensitivity Label to canonical clipped form.
 *
 *	Entry	label = Sensitivity Label to be converted.
 *		len = Maximum length of translated string, excluding NULL.
 *		      0, full string.
 *		sstring = address of string to translate into.
 *		ssize = size of memory currently allocated to sstring.
 *
 *	Exit	sstring = Newly translated string.
 *		ssize = Updated if more memory pre-allocated.
 *
 *	Returns	NULL, If error, len too small, unable to translate, or get
 *		      memory for string.
 *		Address of string containing converted value.
 *
 *	Calls	alloc_string, bsltos, strcpy.
 *
 *	Uses	ssize, sstring.
 */

char *
sbsltos(const bslabel_t *label, size_t len)
{
	ssize_t	slen;		/* length including NULL */
	wchar_t *wstring;
	int	wccount;

	if (ssize == 0) {
		/* Allocate string memory. */
		if ((ssize = alloc_string(&sstring, ssize, 's')) == 0)
			/* can't get initial memory for string */
			return (NULL);
	}

again:
	if ((slen = bsltos(label, &sstring, ssize,
	    (SHORT_CLASSIFICATION | LONG_WORDS))) <= 0) {
		/* error in translation */
		if (slen == 0) {
			if (*sstring == '\0') {
				int newsize;
				/* sstring not long enough */
				if ((newsize = alloc_string(&sstring, ssize,
				    's')) == 0) {
					/* Can't get more memory */
					return (NULL);
				}
				ssize += newsize;
				goto again;
			}
		}
		return (NULL);
	}
	if (len == 0) {
		return (sstring);
	} else if (len < MIN_SL_LEN) {
		return (NULL);
	}
	if ((wstring = malloc(slen * sizeof (wchar_t))) == NULL)
		return (NULL);
	if ((wccount = mbstowcs(wstring, sstring, slen - 1)) == -1) {
		free(wstring);
		return (NULL);
	}
	if (wccount > len) {
		wchar_t *clipp = wstring + (len - 2);

		/* Adjust string size to desired length */

		clipp[0] = L'<';
		clipp[1] = L'-';
		clipp[2] = L'\0';

		while (wcstombs(NULL, wstring, 0) >= ssize) {
			int newsize;

			/* sstring not long enough */
			if ((newsize = alloc_string(&sstring, ssize, 's')) ==
			    0) {
				/* Can't get more memory */
				return (NULL);
			}
			ssize += newsize;
		}

		if ((wccount = wcstombs(sstring, wstring, ssize)) == -1) {
			free(wstring);
			return (NULL);
		}
	}
	free(wstring);

	return (sstring);
}  /* sbsltos */

/*
 *	sbcleartos - Convert Clearance to canonical clipped form.
 *
 *	Entry	clearance = Clearance to be converted.
 *		len = Maximum length of translated string, excluding NULL.
 *		      0, full string.
 *		sstring = address of string to translate into.
 *		ssize = size of memory currently allocated to sstring.
 *
 *	Exit	sstring = Newly translated string.
 *		ssize = Updated if more memory pre-allocated.
 *
 *	Returns	NULL, If error, len too small, unable to translate, or get
 *		      memory for string.
 *		Address of string containing converted value.
 *
 *	Calls	alloc_string, bcleartos, strcpy.
 *
 *	Uses	ssize, sstring.
 */

char *
sbcleartos(const bclear_t *clearance, size_t len)
{
	ssize_t	slen;		/* length including NULL */
	wchar_t *wstring;
	int	wccount;

	if (ssize == 0) {
		/* Allocate string memory. */
		if ((ssize = alloc_string(&sstring, ssize, 'c')) == 0)
			/* can't get initial memory for string */
			return (NULL);
	}

again:
	if ((slen = bcleartos(clearance, &sstring, ssize,
	    (SHORT_CLASSIFICATION | LONG_WORDS))) <= 0) {
		/* error in translation */
		if (slen == 0) {
			if (*sstring == '\0') {
				int newsize;
				/* sstring not long enough */
				if ((newsize = alloc_string(&sstring, ssize,
				    'c')) == 0) {
					/* Can't get more memory */
					return (NULL);
				}
				ssize += newsize;
				goto again;
			}
		}
		return (NULL);
	}
	if (len == 0) {
		return (sstring);
	} else if (len < MIN_CLR_LEN) {
		return (NULL);
	}
	if ((wstring = malloc(slen * sizeof (wchar_t))) == NULL)
		return (NULL);
	if ((wccount = mbstowcs(wstring, sstring, slen - 1)) == -1) {
		free(wstring);
		return (NULL);
	}
	if (wccount > len) {
		wchar_t *clipp = wstring + (len - 2);

		/* Adjust string size to desired length */

		clipp[0] = L'<';
		clipp[1] = L'-';
		clipp[2] = L'\0';

		while (wcstombs(NULL, wstring, 0) >= ssize) {
			int newsize;

			/* sstring not long enough */
			if ((newsize = alloc_string(&sstring, ssize, 'c')) ==
			    0) {
				/* Can't get more memory */
				free(wstring);
				return (NULL);
			}
			ssize += newsize;
		}
		if ((wccount = wcstombs(sstring, wstring, ssize)) == -1) {
			free(wstring);
			return (NULL);
		}
	}
	free(wstring);

	return (sstring);
}  /* sbcleartos */
/*
 * 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.
 */

#include <door.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <synch.h>
#include <time.h>
#include <unistd.h>

#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "labeld.h"

#ifndef	DEBUG
#define	perror(e)
#endif	/* !DEBUG */

/*
 *	This is cloned from _nsc_trydoorcall used by the nscd client.
 *
 * Routine that actually performs the door call.
 * Note that we cache a file descriptor.  We do
 * the following to prevent disasters:
 *
 * 1) Never use 0, 1 or 2; if we get this from the open
 *    we dup it upwards.
 *
 * 2) Set the close on exec flags so descriptor remains available
 *    to child processes.
 *
 * 3) Verify that the door is still the same one we had before
 *    by using door_info on the client side.
 *
 *	Note that we never close the file descriptor if it isn't one
 *	we allocated; we check this with door info.  The rather tricky
 *	logic is designed to be fast in the normal case (fd is already
 *	allocated and is ok) while handling the case where the application
 *	closed it underneath us or where the nscd dies or re-execs itself
 *	and we're a multi-threaded application.  Note that we cannot protect
 *	the application if it closes the fd and it is multi-threaded.
 *
 *  int __call_labeld(label_door_op **dptr, int *ndata, int *adata);
 *
 *      *dptr	IN: points to arg buffer OUT: points to results buffer
 *      *ndata	IN: overall size of buffer OUT: overall size of buffer
 *      *adata	IN: size of call data OUT: size of return data
 *
 *  Note that *dptr may change if provided space as defined by *bufsize is
 *  inadequate.  In this case the door call mmaps more space and places
 *  the answer there and sets dptr to contain a pointer to the space, which
 *  should be freed with munmap.
 *
 *  Returns 0 if the door call reached the server, -1 if contact was not made.
 *
 */


static mutex_t	_door_lock = DEFAULTMUTEX;

int
__call_labeld(labeld_data_t **dptr, size_t *ndata, size_t *adata)
{
	static	int 		doorfd = -1;
	static	door_info_t 	real_door;
	struct stat		st;
	door_info_t 		my_door;
	door_arg_t		param;
	char			door_name[MAXPATHLEN];
	struct timespec		ts;
	int			busy = 0;	/* number of busy loops */

#ifdef	DEBUG
	labeld_data_t		*callptr = *dptr;
	int			buf_size = *ndata;
	int			return_size = *adata;
#endif	/* DEBUG */

	/*
	 * the first time in we try and open and validate the door.
	 * the validations are that the door must have been
	 * created with the label service door cookie and
	 * that it has the same door ID.  If any of these
	 * validations fail we refuse to use the door.
	 */
	ts.tv_sec = 0;		/* initialize nanosecond retry timer */
	ts.tv_nsec = 100;
	(void) mutex_lock(&_door_lock);

try_again:
	if (doorfd == -1) {
		int	tbc[3];
		int	i;

		(void) snprintf(door_name, sizeof (door_name), "%s%s",
		    DOOR_PATH, DOOR_NAME);
		if ((doorfd = open64(door_name, O_RDONLY, 0)) < 0) {
			(void) mutex_unlock(&_door_lock);
			perror("server door open");
			return (NOSERVER);
		}

		/*
		 * dup up the file descriptor if we have 0 - 2
		 * to avoid problems with shells stdin/out/err
		 */
		i = 0;
		while (doorfd < 3) { /* we have a reserved fd */
			tbc[i++] = doorfd;
			if ((doorfd = dup(doorfd)) < 0) {
				perror("couldn't dup");
				while (i--)
					(void) close(tbc[i]);
				doorfd = -1;
				(void) mutex_unlock(&_door_lock);
				return (NOSERVER);
			}
		}
		while (i--)
			(void) close(tbc[i]);

		/*
		 * mark this door descriptor as close on exec
		 */
		(void) fcntl(doorfd, F_SETFD, FD_CLOEXEC);
		if (door_info(doorfd, &real_door) < 0) {
			/*
			 * we should close doorfd because we just opened it
			 */
			perror("real door door_info");
			(void) close(doorfd);
			doorfd = -1;
			(void) mutex_unlock(&_door_lock);
			return (NOSERVER);
		}
		if (fstat(doorfd, &st) < 0) {
			perror("real door fstat");
			return (NOSERVER);
		}
#ifdef	DEBUG
		(void) printf("\treal door %s\n", door_name);
		(void) printf("\t\tuid = %d, gid = %d, mode = %o\n", st.st_uid,
		    st.st_gid, st.st_mode);
		(void) printf("\t\toutstanding requests = %d\n", st.st_nlink-1);
		(void) printf("\t\t pid = %d\n", real_door.di_target);
		(void) printf("\t\t procedure = %llx\n", real_door.di_proc);
		(void) printf("\t\t cookie = %llx\n",  real_door.di_data);
		(void) printf("\t\t attributes = %x\n",
		    real_door.di_attributes);
		if (real_door.di_attributes & DOOR_UNREF)
			(void) printf("\t\t\t UNREF\n");
		if (real_door.di_attributes & DOOR_PRIVATE)
			(void) printf("\t\t\t PRIVATE\n");
		if (real_door.di_attributes & DOOR_LOCAL)
			(void) printf("\t\t\t LOCAL\n");
		if (real_door.di_attributes & DOOR_REVOKED)
			(void) printf("\t\t\t REVOKED\n");
		if (real_door.di_attributes & DOOR_DESCRIPTOR)
			(void) printf("\t\t\t DESCRIPTOR\n");
		if (real_door.di_attributes & DOOR_RELEASE)
			(void) printf("\t\t\t RELEASE\n");
		if (real_door.di_attributes & DOOR_DELAY)
			(void) printf("\t\t\t DELAY\n");
		(void) printf("\t\t id = %llx\n", real_door.di_uniquifier);
#endif	/* DEBUG */
		if ((real_door.di_attributes & DOOR_REVOKED) ||
		    (real_door.di_data != COOKIE)) {
#ifdef	DEBUG
			(void) printf("real door revoked\n");
#endif	/* DEBUG */
			(void) close(doorfd);
			doorfd = -1;
			(void) mutex_unlock(&_door_lock);
			return (NOSERVER);
		}
	} else {
		if ((door_info(doorfd, &my_door) < 0) ||
		    (my_door.di_data != COOKIE) ||
		    (my_door.di_uniquifier != real_door.di_uniquifier)) {
			perror("my door door_info");
			/*
			 * don't close it - someone else has clobbered fd
			 */
			doorfd = -1;
			goto try_again;
		}
		if (fstat(doorfd, &st) < 0) {
			perror("my door fstat");
			goto try_again;
		}
#ifdef	DEBUG
		(void) sprintf(door_name, "%s%s", DOOR_PATH, DOOR_NAME);
		(void) printf("\tmy door %s\n", door_name);
		(void) printf("\t\tuid = %d, gid = %d, mode = %o\n", st.st_uid,
		    st.st_gid, st.st_mode);
		(void) printf("\t\toutstanding requests = %d\n", st.st_nlink-1);
		(void) printf("\t\t pid = %d\n", my_door.di_target);
		(void) printf("\t\t procedure = %llx\n", my_door.di_proc);
		(void) printf("\t\t cookie = %llx\n",  my_door.di_data);
		(void) printf("\t\t attributes = %x\n", my_door.di_attributes);
		if (my_door.di_attributes & DOOR_UNREF)
			(void) printf("\t\t\t UNREF\n");
		if (my_door.di_attributes & DOOR_PRIVATE)
			(void) printf("\t\t\t PRIVATE\n");
		if (my_door.di_attributes & DOOR_LOCAL)
			(void) printf("\t\t\t LOCAL\n");
		if (my_door.di_attributes & DOOR_REVOKED)
			(void) printf("\t\t\t REVOKED\n");
		if (my_door.di_attributes & DOOR_DESCRIPTOR)
			(void) printf("\t\t\t DESCRIPTOR\n");
		if (my_door.di_attributes & DOOR_RELEASE)
			(void) printf("\t\t\t RELEASE\n");
		if (my_door.di_attributes & DOOR_DELAY)
			(void) printf("\t\t\t DELAY\n");
		(void) printf("\t\t id = %llx\n", my_door.di_uniquifier);
#endif	/* DEBUG */
		if (my_door.di_attributes & DOOR_REVOKED) {
#ifdef	DEBUG
			(void) printf("my door revoked\n");
#endif	/* DEBUG */
			(void) close(doorfd);	/* labeld exited .... */
			doorfd = -1;	/* try and restart connection */
			goto try_again;
		}
	}
	(void) mutex_unlock(&_door_lock);

	param.data_ptr = (char *)*dptr;
	param.data_size = *adata;
	param.desc_ptr = NULL;
	param.desc_num = 0;
	param.rbuf = (char *)*dptr;
	param.rsize = *ndata;

	if (door_call(doorfd, &param) < 0) {
		if (errno == EAGAIN && busy++ < 10) {
			/* adjust backoff */
			if ((ts.tv_nsec *= 10) >= NANOSEC) {
				ts.tv_sec++;
				ts.tv_nsec = 100;
			}
			(void) nanosleep(&ts, NULL);
#ifdef	DEBUG
			(void) printf("door_call failed EAGAIN # %d\n", busy);
#endif	/* DEBUG */
			(void) mutex_lock(&_door_lock);
			goto try_again;
		}
		perror("door call");
		return (NOSERVER);
	}

	*adata = (int)param.data_size;
	*ndata = (int)param.rsize;
	/*LINTED*/
	*dptr = (labeld_data_t *)param.data_ptr;

	if (*adata == 0 || *dptr == NULL) {
#ifdef	DEBUG
		(void) printf("\tNo data returned, size = %lu, dptr = %p\n",
		    (unsigned long)*adata, (void *)*dptr);
#endif	/* DEBUG */
		return (NOSERVER);
	}
#ifdef	DEBUG
	(void) printf("call buf = %x, buf size  = %d, call size = %d\n",
	    callptr, buf_size, return_size);
	(void) printf("retn buf = %x, buf size  = %d, retn size = %d\n",
	    *dptr, *ndata, *adata);
	(void) printf("\treply status = %d\n", (*dptr)->param.aret.ret);
#endif	/* DEBUG */
	return ((*dptr)->param.aret.ret);

}  /* __call_labeld */
/*
 * 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 _CLNT_H
#define	_CLNT_H

#ifdef	__cplusplus
extern "C" {
#endif

#define	MAXCOLOR	256	/* Max size of a static color string */
#define	MIN_CMW_LEN	8	/* minimum length of clipped CMW Label */
#define	MIN_SL_LEN	3	/* minimum length of clipped SL */
#define	MIN_IL_LEN	3	/* minimum length of clipped IL */
#define	MIN_CLR_LEN	3	/* minimum length of clipped Clearance */

#define	ALLOC_CHUNK	1024	/* size of chunk for sb*tos allocs */

extern int alloc_string(char **, size_t, char);
extern void set_label_view(uint_t *, uint_t);
#ifdef	__cplusplus
}
#endif

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

/*
 *	String to binary label translations.
 */

#include <ctype.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>

#include <tsol/label.h>
#include <sys/tsol/label_macro.h>

#include <sys/syscall.h>
#include <sys/tsol/tsyscall.h>

#include <sys/types.h>

/*
 * getlabel(3TSOL) - get file label
 *
 * This is the library interface to the system call.
 */

int
getlabel(const char *path, bslabel_t *label)
{
	return (syscall(SYS_labelsys, TSOL_GETLABEL, path, label));
}

/*
 * fgetlabel(3TSOL) - get file label
 *
 * This is the library interface to the system call.
 */
int
fgetlabel(int fd, bslabel_t *label)
{
	return (syscall(SYS_labelsys, TSOL_FGETLABEL, fd, label));
}
/*
 * 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 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 *	Name:		getpathbylabel.c
 *
 *	Description:	Returns the global zone pathname corresponding
 *			to the specified label. The pathname does
 *			not need to match an existing file system object.
 *
 */
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <tsol/label.h>
#include <stdlib.h>
#include <zone.h>
#include <sys/mntent.h>
#include <sys/mnttab.h>
#include <stdarg.h>

/*
 * This structure is used to chain mntent structures into a list
 * and to cache stat information for each member of the list.
 */
struct mntlist {
	struct mnttab	*mntl_mnt;
	struct mntlist	*mntl_next;
};


/*
 * Return a pointer to the trailing suffix of full that follows the prefix
 * given by pref.  If pref isn't a prefix of full, return NULL.  Apply
 * pathname semantics to the prefix test, so that pref must match at a
 * component boundary.
 */
static char *
pathsuffix(char *full, char *pref)
{
	int preflen;

	if (full == NULL || pref == NULL)
		return (NULL);

	preflen = strlen(pref);
	if (strncmp(pref, full, preflen) != 0)
		return (NULL);

	/*
	 * pref is a substring of full.  To be a subpath, it cannot cover a
	 * partial component of full.  The last clause of the test handles the
	 * special case of the root.
	 */
	if (full[preflen] != '\0' && full[preflen] != '/' && preflen > 1)
		return (NULL);

	if (preflen == 1 && full[0] == '/')
		return (full);
	else
		return (full + preflen);
}

/*
 * Return zero iff the path named by sub is a leading subpath
 * of the path named by full.
 *
 * Treat null paths as matching nothing.
 */
static int
subpath(char *full, char *sub)
{
	return (pathsuffix(full, sub) == NULL);
}

static void
tsol_mnt_free(struct mnttab *mnt)
{
	if (mnt->mnt_special)
		free(mnt->mnt_special);
	if (mnt->mnt_mountp)
		free(mnt->mnt_mountp);
	if (mnt->mnt_fstype)
		free(mnt->mnt_fstype);
	if (mnt->mnt_mntopts)
		free(mnt->mnt_mntopts);
	free(mnt);
}

static void
tsol_mlist_free(struct mntlist *mlist)
{
	struct mntlist *mlp;
	struct mntlist *oldmlp;

	mlp = mlist;
	while (mlp) {
		struct mnttab *mnt = mlp->mntl_mnt;

		if (mnt)
			tsol_mnt_free(mnt);
		oldmlp = mlp;
		mlp = mlp->mntl_next;
		free(oldmlp);
	}
}

static struct mnttab *
mntdup(struct mnttab *mnt)
{
	struct mnttab *new;

	new = (struct mnttab *)malloc(sizeof (*new));
	if (new == NULL)
		return (NULL);

	new->mnt_special = NULL;
	new->mnt_mountp = NULL;
	new->mnt_fstype = NULL;
	new->mnt_mntopts = NULL;

	new->mnt_special = strdup(mnt->mnt_special);
	if (new->mnt_special == NULL) {
		tsol_mnt_free(new);
		return (NULL);
	}
	new->mnt_mountp = strdup(mnt->mnt_mountp);
	if (new->mnt_mountp == NULL) {
		tsol_mnt_free(new);
		return (NULL);
	}
	new->mnt_fstype = strdup(mnt->mnt_fstype);
	if (new->mnt_fstype == NULL) {
		tsol_mnt_free(new);
		return (NULL);
	}
	new->mnt_mntopts = strdup(mnt->mnt_mntopts);
	if (new->mnt_mntopts == NULL) {
		tsol_mnt_free(new);
		return (NULL);
	}
	return (new);
}

static struct mntlist *
tsol_mkmntlist(void)
{
	FILE *mounted;
	struct mntlist *mntl;
	struct mntlist *mntst = NULL;
	struct mnttab mnt;

	if ((mounted = fopen(MNTTAB, "rF")) == NULL) {
		perror(MNTTAB);
		return (NULL);
	}
	resetmnttab(mounted);
	while (getmntent(mounted, &mnt) == 0) {
		mntl = (struct mntlist *)malloc(sizeof (*mntl));
		if (mntl == NULL) {
			tsol_mlist_free(mntst);
			mntst = NULL;
			break;
		}
		mntl->mntl_mnt = mntdup((struct mnttab *)(&mnt));
		if (mntl->mntl_mnt == NULL) {
			tsol_mlist_free(mntst);
			mntst = NULL;
			break;
		}
		mntl->mntl_next = mntst;
		mntst = mntl;
	}
	(void) fclose(mounted);
	return (mntst);
}

/*
 * This function attempts to convert local zone NFS mounted pathnames
 * into equivalent global zone NFS mounted pathnames. At present
 * it only works for automounted filesystems. It depends on the
 * assumption that both the local and global zone automounters
 * share the same nameservices. It also assumes that any automount
 * map used by a local zone is available to the global zone automounter.
 *
 * The algorithm used consists of three phases.
 *
 * 1. The local zone's mnttab is searched to find the automount map
 *    with the closest matching mountpath.
 *
 * 2. The matching autmount map name is looked up in the global zone's
 *    mnttab to determine the path where it should be mounted in the
 *    global zone.
 *
 * 3. A pathname covered by an appropiate autofs trigger mount in
 *    the global zone is generated as the resolved pathname
 *
 * Among the things that can go wrong is that global zone doesn't have
 * a matching automount map or the mount was not done via the automounter.
 * Either of these cases return a NULL path.
 */
#define	ZONE_OPT "zone="
static int
getnfspathbyautofs(struct mntlist *mlist, zoneid_t zoneid,
    struct mnttab *autofs_mnt, char *globalpath, char *zonepath, int global_len)
{
	struct mntlist *mlp;
	char zonematch[ZONENAME_MAX + 20];
	char zonename[ZONENAME_MAX];
	int  longestmatch;
	struct	mnttab	*mountmatch;

	if (autofs_mnt) {
		mountmatch = autofs_mnt;
		longestmatch = strlen(mountmatch->mnt_mountp);
	} else {
		/*
		 * First we need to get the zonename to look for
		 */
		if (zone_getattr(zoneid, ZONE_ATTR_NAME, zonename,
		    ZONENAME_MAX) == -1) {
			return (0);
		}

		(void) strncpy(zonematch, ZONE_OPT, sizeof (zonematch));
		(void) strlcat(zonematch, zonename, sizeof (zonematch));

		/*
		 * Find the best match for an automount map that
		 * corresponds to the local zone's pathname
		 */
		longestmatch = 0;
		for (mlp = mlist; mlp; mlp = mlp->mntl_next) {
			struct mnttab *mnt = mlp->mntl_mnt;
			int	len;
			int	matchfound;
			char	*token;
			char	*lasts;
			char	mntopts[MAXPATHLEN];

			if (subpath(globalpath, mnt->mnt_mountp) != 0)
				continue;
			if (strcmp(mnt->mnt_fstype, MNTTYPE_AUTOFS))
				continue;

			matchfound = 0;
			(void) strncpy(mntopts, mnt->mnt_mntopts, MAXPATHLEN);
			if ((token = strtok_r(mntopts, ",", &lasts)) != NULL) {
				if (strcmp(token, zonematch) == 0) {
					matchfound = 1;
				} else while ((token = strtok_r(NULL, ",",
				    &lasts)) != NULL) {
					if (strcmp(token, zonematch) == 0) {
						matchfound = 1;
						break;
					}
				}
			}
			if (matchfound) {
				len = strlen(mnt->mnt_mountp);
				if (len > longestmatch) {
					mountmatch = mnt;
					longestmatch = len;
				}
			}
		}
	}
	if (longestmatch == 0) {
		return (0);
	} else {
		/*
		 * Now we may have found the corresponding autofs mount
		 * Try to find the matching global zone autofs entry
		 */

		for (mlp = mlist; mlp; mlp = mlp->mntl_next) {
			char p[MAXPATHLEN];
			size_t zp_len;
			size_t mp_len;

			struct mnttab *mnt = mlp->mntl_mnt;

			if (strcmp(mountmatch->mnt_special,
			    mnt->mnt_special) != 0)
				continue;
			if (strcmp(mnt->mnt_fstype, MNTTYPE_AUTOFS))
				continue;
			if (strstr(mnt->mnt_mntopts, ZONE_OPT) != NULL)
				continue;
			/*
			 * OK, we have a matching global zone automap
			 * so adjust the path for the global zone.
			 */
			zp_len = strlen(zonepath);
			mp_len = strlen(mnt->mnt_mountp);
			(void) strncpy(p, globalpath + zp_len, MAXPATHLEN);
			/*
			 * If both global zone and zone-relative
			 * mountpoint match, just use the same pathname
			 */
			if (strncmp(mnt->mnt_mountp, p, mp_len) == 0) {
				(void) strncpy(globalpath, p, global_len);
				return (1);
			} else {
				(void) strncpy(p, globalpath, MAXPATHLEN);
				(void) strncpy(globalpath, mnt->mnt_mountp,
				    global_len);
				(void) strlcat(globalpath,
				    p + strlen(mountmatch->mnt_mountp),
				    global_len);
				return (1);
			}
		}
		return (0);
	}
}

/*
 * Find the pathname for the entry in mlist that corresponds to the
 * file named by path (i.e., that names a mount table entry for the
 * file system in which path lies).
 *
 * Return 0 is there an error.
 */
static int
getglobalpath(const char *path, zoneid_t zoneid, struct mntlist *mlist,
    char *globalpath)
{
	struct mntlist *mlp;
	char		lofspath[MAXPATHLEN];
	char		zonepath[MAXPATHLEN];
	int		longestmatch;
	struct	mnttab	*mountmatch;

	if (zoneid != GLOBAL_ZONEID) {
		char	*prefix;

		if ((prefix = getzonerootbyid(zoneid)) == NULL) {
			return (0);
		}
		(void) strncpy(zonepath, prefix, MAXPATHLEN);
		(void) strlcpy(globalpath, prefix, MAXPATHLEN);
		(void) strlcat(globalpath, path, MAXPATHLEN);
		free(prefix);
	} else {
		(void) strlcpy(globalpath, path, MAXPATHLEN);
	}

	for (;;) {
		longestmatch = 0;
		for (mlp = mlist; mlp; mlp = mlp->mntl_next) {
			struct mnttab *mnt = mlp->mntl_mnt;
			int	len;

			if (subpath(globalpath, mnt->mnt_mountp) != 0)
				continue;
			len = strlen(mnt->mnt_mountp);
			if (len > longestmatch) {
				mountmatch = mnt;
				longestmatch = len;
			}
		}
		/*
		 * Handle interesting mounts.
		 */
		if ((strcmp(mountmatch->mnt_fstype, MNTTYPE_NFS) == 0) ||
		    (strcmp(mountmatch->mnt_fstype, MNTTYPE_AUTOFS) == 0)) {
			if (zoneid > GLOBAL_ZONEID) {
				struct mnttab *m = NULL;

				if (strcmp(mountmatch->mnt_fstype,
				    MNTTYPE_AUTOFS) == 0)
					m = mountmatch;
				if (getnfspathbyautofs(mlist, zoneid, m,
				    globalpath, zonepath, MAXPATHLEN) == 0) {
					return (0);
				}
			}
			break;
		} else if (strcmp(mountmatch->mnt_fstype, MNTTYPE_LOFS) == 0) {
			/*
			 * count up what's left
			 */
			int	remainder;

			remainder = strlen(globalpath) - longestmatch;
			if (remainder > 0) {
				path = pathsuffix(globalpath,
				    mountmatch->mnt_mountp);
				(void) strlcpy(lofspath, path, MAXPATHLEN);
			}
			(void) strlcpy(globalpath, mountmatch->mnt_special,
			    MAXPATHLEN);
			if (remainder > 0) {
				(void) strlcat(globalpath, lofspath,
				    MAXPATHLEN);
			}
		} else {
			if ((zoneid > GLOBAL_ZONEID) &&
			    (strncmp(path, "/home/", strlen("/home/")) == 0)) {
				char zonename[ZONENAME_MAX];

				/*
				 * If this is a cross-zone reference to
				 * a home directory, it must be corrected.
				 * We should only get here if the zone's
				 * automounter hasn't yet mounted its
				 * autofs trigger on /home.
				 *
				 * Since it is likely to do so in the
				 * future, we will assume that the global
				 * zone already has an equivalent autofs
				 * mount established. By convention,
				 * this should be mounted at the
				 * /zone/<zonename>
				 */

				if (zone_getattr(zoneid, ZONE_ATTR_NAME,
				    zonename, ZONENAME_MAX) == -1) {
					return (0);
				} else {
					(void) snprintf(globalpath, MAXPATHLEN,
					    "/zone/%s%s", zonename, path);
				}
			}
			break;
		}
	}
	return (1);
}


/*
 * This function is only useful for global zone callers
 * It uses the global zone mnttab to translate local zone pathnames
 * into global zone pathnames.
 */
char *
getpathbylabel(const char *path_name, char *resolved_path, size_t bufsize,
    const bslabel_t *sl)
{
	char		ret_path[MAXPATHLEN];	/* pathname to return */
	zoneid_t	zoneid;
	struct mntlist *mlist;

	if (getzoneid() != GLOBAL_ZONEID) {
		errno = EINVAL;
		return (NULL);
	}

	if (path_name[0] != '/') {		/* need absolute pathname */
		errno = EINVAL;
		return (NULL);
	}

	if (resolved_path == NULL) {
		errno = EINVAL;
		return (NULL);
	}

	if ((zoneid = getzoneidbylabel(sl)) == -1)
		return (NULL);

	/*
	 * Construct the list of mounted file systems.
	 */

	if ((mlist = tsol_mkmntlist()) == NULL) {
		return (NULL);
	}
	if (getglobalpath(path_name, zoneid, mlist, ret_path) == 0) {
		tsol_mlist_free(mlist);
		return (NULL);
	}
	tsol_mlist_free(mlist);
	if (strlen(ret_path) >= bufsize) {
		errno = EFAULT;
		return (NULL);
	}
	return (strcpy(resolved_path, ret_path));
} /* end getpathbylabel() */
/*
 * 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.
 */

#include	<stdlib.h>
#include	<zone.h>
#include 	<tsol/label.h>
#include 	<sys/tsol/label_macro.h>
#include	<sys/types.h>
#include	<sys/zone.h>

/*
 * getplabel(3TSOL) - get process sensitivity label
 */

int
getplabel(bslabel_t *label_p)
{
	zoneid_t zoneid;

	zoneid = (int)getzoneid();
	if (zoneid == GLOBAL_ZONEID) {
		bslhigh(label_p);
	} else {
		bslabel_t *sl;

		sl = getzonelabelbyid(zoneid);
		if (sl == NULL) {
			return (-1);
		} else {
			*label_p = *sl;
			free(sl);
		}
	}
	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 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 *      hextob.c - Hexadecimal string to binary label conversion.
 *
 *              These routines convert canonical hexadecimal representations
 *	of internal labels into binary form.
 *
 */

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include <tsol/label.h>
#include <sys/tsol/label_macro.h>

/*
 *	htobsl - Convert a Hexadecimal label string to a Sensitivity Label.
 *
 *	Entry	s = Hexadecimal label string to be converted.
 *
 *	Exit	label = Sensitivity Label converted, if successful.
 *			Unchanged, if not successful.
 *
 *	Returns	1, If successful.
 *		0, Otherwise.
 *
 *	Calls	str_to_label, m_label_free.
 */

int
htobsl(const char *s, m_label_t *label)
{
	m_label_t *l = NULL;

	if (str_to_label(s, &l, MAC_LABEL, L_NO_CORRECTION, NULL) == -1) {
		m_label_free(l);
		return (0);
	}
	*label = *l;
	m_label_free(l);
	return (1);
}

/*
 *	htobclear - Convert a Hexadecimal label string to a Clearance.
 *
 *	Entry	s = Hexadecimal label string to be converted.
 *
 *	Exit	clearance = Clearnace converted, if successful.
 *			    Unchanged, if not successful.
 *
 *	Returns	1, If successful.
 *		0, Otherwise.
 *
 *	Calls	str_to_label, m_label_free.
 */

int
htobclear(const char *s, m_label_t *clearance)
{
	m_label_t *c = NULL;

	if (str_to_label(s, &c, USER_CLEAR, L_NO_CORRECTION, NULL) == -1) {
		m_label_free(c);
		return (0);
	}
	*clearance = *c;
	m_label_free(c);
	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 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef	_TSOL_LABEL_H
#define	_TSOL_LABEL_H

#include <sys/types32.h>
#include <sys/tsol/label.h>
#include <priv.h>

#ifdef	__cplusplus
extern "C" {
#endif

/* Procedural Interface Structure Definitions */

struct	label_info {		/* structure returned by label_info */
	short	ilabel_len;		/* max Information Label length */
	short	slabel_len;		/* max Sensitivity Label length */
	short	clabel_len;		/* max CMW Label length */
	short	clear_len;		/* max Clearance Label length */
	short	vers_len;		/* version string length */
	short	header_len;		/* max len of banner page header */
	short	protect_as_len;		/* max len of banner page protect as */
	short	caveats_len;		/* max len of banner page caveats */
	short	channels_len;		/* max len of banner page channels */
};

typedef struct label_set_identifier {	/* valid label set identifier */
	int	type;			/* type of the set */
	char	*name;			/* name of the set if needed */
} set_id;

struct name_fields {		/* names for label builder fields */
	char	*class_name;		/* Classifications field name */
	char	*comps_name;		/* Compartments field name */
	char	*marks_name;		/* Markings field name */
};

/* Label Set Identifier Types */

/*
 * The accreditation ranges as specified in the label encodings file.
 * The name parameter is ignored.
 *
 * System Accreditation Range is all valid labels plus Admin High and Low.
 *
 * User Accreditation Range is valid user labels as defined in the
 *	ACCREDITATION RANGE: section of the label encodings file.
 */

#define	SYSTEM_ACCREDITATION_RANGE	1
#define	USER_ACCREDITATION_RANGE	2


/* System Call Interface Definitions */

extern int getlabel(const char *, m_label_t *);
extern int fgetlabel(int, m_label_t *);

extern int getplabel(m_label_t *);
extern int setflabel(const char *, m_label_t *);
extern char *getpathbylabel(const char *, char *, size_t,
    const m_label_t *sl);
extern m_label_t *getzonelabelbyid(zoneid_t);
extern m_label_t *getzonelabelbyname(const char *);
extern zoneid_t getzoneidbylabel(const m_label_t *);
extern char *getzonenamebylabel(const m_label_t *);
extern char *getzonerootbyid(zoneid_t);
extern char *getzonerootbyname(const char *);
extern char *getzonerootbylabel(const m_label_t *);
extern m_label_t *getlabelbypath(const char *);


/* Flag word values */

#define	ALL_ENTRIES		0x00000000
#define	ACCESS_RELATED		0x00000001
#define	ACCESS_MASK		0x0000FFFF
#define	ACCESS_SHIFT		0

#define	LONG_WORDS		0x00010000	/* use long names */
#define	SHORT_WORDS		0x00020000	/* use short names if present */
#define	LONG_CLASSIFICATION	0x00040000	/* use long classification */
#define	SHORT_CLASSIFICATION	0x00080000	/* use short classification */
#define	NO_CLASSIFICATION	0x00100000	/* don't translate the class */
#define	VIEW_INTERNAL		0x00200000	/* don't promote/demote */
#define	VIEW_EXTERNAL		0x00400000	/* promote/demote label */

#define	NEW_LABEL		0x00000001	/* create a full new label */
#define	NO_CORRECTION		0x00000002	/* don't correct label errors */
						/* implies NEW_LABEL */

#define	CVT_DIM			0x01		/* display word dimmed */
#define	CVT_SET			0x02		/* display word currently set */

/* Procedure Interface Definitions available to user */

/* APIs shared with the kernel are in <sys/tsol/label.h */

extern m_label_t *blabel_alloc(void);
extern void	blabel_free(m_label_t *);
extern size32_t blabel_size(void);
extern char	*bsltoh(const m_label_t *);
extern char	*bcleartoh(const m_label_t *);

extern char	*bsltoh_r(const m_label_t *, char *);
extern char	*bcleartoh_r(const m_label_t *, char *);
extern char	*h_alloc(uint8_t);
extern void	h_free(char *);

extern int	htobsl(const char *, m_label_t *);
extern int	htobclear(const char *, m_label_t *);

extern m_range_t	*getuserrange(const char *);
extern m_range_t	*getdevicerange(const char *);

extern int	set_effective_priv(priv_op_t, int, ...);
extern int	set_inheritable_priv(priv_op_t, int, ...);
extern int	set_permitted_priv(priv_op_t, int, ...);
extern int	is_system_labeled(void);

/* Procedures needed for multi-level printing */

extern int	tsol_check_admin_auth(uid_t uid);

/* APIs implemented via labeld */

extern int	blinset(const m_label_t *, const set_id *);
extern int	labelinfo(struct label_info *);
extern ssize_t	labelvers(char **, size_t);
extern char	*bltocolor(const m_label_t *);
extern char	*bltocolor_r(const m_label_t *, size_t, char *);

extern ssize_t	bsltos(const m_label_t *, char **, size_t, int);
extern ssize_t	bcleartos(const m_label_t *, char **, size_t, int);


extern char	*sbsltos(const m_label_t *, size_t);
extern char	*sbcleartos(const m_label_t *, size_t);


extern int	stobsl(const char *, m_label_t *, int, int *);
extern int	stobclear(const char *, m_label_t *, int, int *);
extern int	bslvalid(const m_label_t *);
extern int	bclearvalid(const m_label_t *);

/* DIA label conversion and parsing */

/* Conversion types */

typedef	enum _m_label_str {
	M_LABEL = 1,		/* process or user clearance */
	M_INTERNAL = 2,		/* internal form for use in public databases */
	M_COLOR = 3,		/* process label color */
	PRINTER_TOP_BOTTOM = 4,	/* DIA banner page top/bottom */
	PRINTER_LABEL = 5,	/* DIA banner page label */
	PRINTER_CAVEATS = 6,	/* DIA banner page caveats */
	PRINTER_CHANNELS = 7	/* DIA banner page handling channels */
} m_label_str_t;

/* Flags for conversion, not all flags apply to all types */
#define	DEF_NAMES	0x1
#define	SHORT_NAMES	0x3	/* short names are prefered where defined */
#define	LONG_NAMES	0x4	/* long names are prefered where defined */

extern int label_to_str(const m_label_t *, char **, const m_label_str_t,
    uint_t);
extern int l_to_str_internal(const m_label_t *, char **);

/* Parsing types */
typedef enum _m_label_type {
	MAC_LABEL = 1,		/* process or object label */
	USER_CLEAR = 2		/* user's clearance (LUB) */
} m_label_type_t;

/* Flags for parsing */

#define	L_DEFAULT		0x0
#define	L_MODIFY_EXISTING	0x1	/* start parsing with existing label */
#define	L_NO_CORRECTION		0x2	/* must be correct by l_e rules */
#define	L_CHECK_AR		0x10	/* must be in l_e AR */

/* EINVAL sub codes */

#define	M_OUTSIDE_AR		-4	/* not in l_e AR */
#define	M_BAD_STRING		-3	/* DIA L_BAD_LABEL */
	/* bad requested label type, bad previous label type */
#define	M_BAD_LABEL		-2	/* DIA L_BAD_CLASSIFICATION, */

extern int str_to_label(const char *, m_label_t **, const m_label_type_t,
    uint_t, int *);
extern int hexstr_to_label(const char *, m_label_t *);

extern m_label_t *m_label_alloc(const m_label_type_t);

extern int m_label_dup(m_label_t **, const m_label_t *);

extern void m_label_free(m_label_t *);

/* Contract Private interfaces with the label builder GUIs */

extern int	bslcvtfull(const m_label_t *, const m_range_t *, int,
    char **, char **[], char **[], char *[], int *, int *);
extern int	bslcvt(const m_label_t *, int, char **, char *[]);
extern int	bclearcvtfull(const m_label_t *, const m_range_t *, int,
    char **, char **[], char **[], char *[], int *, int *);
extern int	bclearcvt(const m_label_t *, int, char **, char *[]);

extern int	labelfields(struct name_fields *);
extern int	userdefs(m_label_t *, m_label_t *);
extern int	zonecopy(m_label_t *, char *, char *, char *, int);

#ifdef DEBUG
/* testing hook: see devfsadm.c, mkdevalloc.c and allocate.c */
#define	is_system_labeled_debug(statbufp)	\
	((stat("/ALLOCATE_FORCE_LABEL", (statbufp)) == 0) ? 1 : 0)
#else	/* DEBUG */
#define	is_system_labeled_debug(statbufp)	0
#endif	/* DEBUG */

#ifdef	__cplusplus
}
#endif

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

#ifndef	_LABELD_H
#define	_LABELD_H

#include <sys/types.h>
#include <tsol/label.h>
#include <sys/tsol/label_macro.h>

#ifdef	__cplusplus
extern "C" {
#endif

/*
 *	Definitions for the call parameters for the door-based label
 * translation service.
 */

#define	BUFSIZE	4096

#define	DOOR_PATH	"/var/tsol/doors/"
#define	DOOR_NAME	"labeld"
#define	COOKIE		0x6c616264ull	/* "labd" */

/*	Op codes */

/*	Labeld Commands */

#define	LABELDNULL	1

/*	Miscellaneous */

#define	BLINSET		10
#define	BSLVALID	11
#define	BILVALID	12
#define	BCLEARVALID	13
#define	LABELINFO	14
#define	LABELVERS	15
#define	BLTOCOLOR	16

/*	Binary to String Label Translation */

#define	BSLTOS		23
#define	BCLEARTOS	25

/*	String to Binary Label Translation */

#define	STOBSL		31
#define	STOBCLEAR	33

/*
 *	Dimming List Routines
 *	Contract private for label builders
 */

#define	BSLCVT		40
#define	BCLEARCVT	42
#define	LABELFIELDS	43
#define	UDEFS		44

#define	GETFLABEL	45
#define	SETFLABEL	46
#define	ZCOPY		47

/* NEW LABELS */
/* DIA printer banner labels */

#define	PR_CAVEATS	101
#define	PR_CHANNELS	102
#define	PR_LABEL	103
#define	PR_TOP		104

/* DIA label to string  */

#define	LTOS		105

/* DIA string to label */

#define	STOL		106

/*	Structures */

typedef	uint_t	bufp_t;		/* offset into buf[] in/out string buffer */

/* Null call */

typedef	struct {
	int	null;
} null_call_t;

typedef	struct {
	int	null;
} null_ret_t;

/* Miscellaneous interfaces */

typedef	struct {
	bslabel_t label;
	int	type;
} inset_call_t;

typedef	struct {
	int	inset;
} inset_ret_t;

typedef	struct {
	bslabel_t label;
} slvalid_call_t;

typedef	struct {
	int	valid;
} slvalid_ret_t;

typedef	struct {
	bclear_t clear;
} clrvalid_call_t;

typedef	struct {
	int	valid;
} clrvalid_ret_t;

typedef	struct {
	int	null;
} info_call_t;

typedef	struct {
	struct label_info info;
} info_ret_t;

typedef	struct {
	int	null;
} vers_call_t;

typedef	struct {
	char	vers[BUFSIZE];
} vers_ret_t;

typedef struct {
	blevel_t label;
} color_call_t;

typedef struct {
	char	color[BUFSIZE];
} color_ret_t;

/* Binary Label to String interfaces */

typedef	struct {
	bslabel_t label;
	uint_t	flags;
} bsltos_call_t;

typedef	struct {
	char	slabel[BUFSIZE];
} bsltos_ret_t;

typedef	struct {
	bclear_t clear;
	uint_t	flags;
} bcleartos_call_t;

typedef	struct {
	char	cslabel[BUFSIZE];
} bcleartos_ret_t;

/* String to Binary Label interfaces */

typedef	struct {
	bslabel_t label;
	uint_t	flags;
	char	string[BUFSIZE];
} stobsl_call_t;

typedef	struct {
	bslabel_t label;
} stobsl_ret_t;

typedef	struct {
	bclear_t clear;
	uint_t	flags;
	char	string[BUFSIZE];
} stobclear_call_t;

typedef	struct {
	bclear_t clear;
} stobclear_ret_t;

/*
 * The following Dimming List and Miscellaneous interfaces
 * implement contract private interfaces for the label builder
 * interfaces.
 */

/* Dimming List interfaces */

typedef	struct {
	bslabel_t label;
	brange_t bounds;
	uint_t	flags;
} bslcvt_call_t;

typedef	struct {
	bufp_t	string;
	bufp_t	dim;
	bufp_t	lwords;
	bufp_t	swords;
	size_t	d_len;
	size_t	l_len;
	size_t	s_len;
	int	first_comp;
	int	first_mark;
	char	buf[BUFSIZE];
} cvt_ret_t;

typedef cvt_ret_t bslcvt_ret_t;

typedef	struct {
	bclear_t clear;
	brange_t bounds;
	uint_t	flags;
} bclearcvt_call_t;

typedef cvt_ret_t bclearcvt_ret_t;

/* Miscellaneous interfaces */

typedef	struct {
	int	null;
} fields_call_t;

typedef	struct {
	bufp_t	classi;
	bufp_t	compsi;
	bufp_t	marksi;
	char	buf[BUFSIZE];
} fields_ret_t;

typedef	struct {
	int	null;
} udefs_call_t;

typedef	struct {
	bslabel_t sl;
	bclear_t  clear;
} udefs_ret_t;

typedef	struct {
	bslabel_t  sl;
	char	pathname[BUFSIZE];
} setfbcl_call_t;

typedef	struct {
	int	status;
} setfbcl_ret_t;

typedef	struct {
	bslabel_t  src_win_sl;
	int	transfer_mode;
	bufp_t  remote_dir;
	bufp_t  filename;
	bufp_t  local_dir;
	bufp_t  display;
	char    buf[BUFSIZE];
} zcopy_call_t;

typedef	struct {
	int	status;
} zcopy_ret_t;

typedef	struct {
	m_label_t label;
	uint_t	flags;
} pr_call_t;

typedef	struct {
	char	buf[BUFSIZE];
} pr_ret_t;

typedef	struct {
	m_label_t label;
	uint_t	flags;
} ls_call_t;

typedef	struct {
	char	buf[BUFSIZE];
} ls_ret_t;

typedef	struct {
	m_label_t label;
	uint_t	flags;
	char	string[BUFSIZE];
} sl_call_t;

typedef	struct {
	m_label_t label;
} sl_ret_t;

/* Labeld operation call structure */

typedef	struct {
	uint_t	op;
	union	{
		null_call_t	null_arg;

		inset_call_t	inset_arg;
		slvalid_call_t	slvalid_arg;
		clrvalid_call_t	clrvalid_arg;
		info_call_t	info_arg;
		vers_call_t	vers_arg;
		color_call_t	color_arg;

		bsltos_call_t	bsltos_arg;
		bcleartos_call_t	bcleartos_arg;

		stobsl_call_t	stobsl_arg;
		stobclear_call_t	stobclear_arg;

		bslcvt_call_t	bslcvt_arg;
		bclearcvt_call_t	bclearcvt_arg;
		fields_call_t	fields_arg;
		udefs_call_t	udefs_arg;
		setfbcl_call_t	setfbcl_arg;
		zcopy_call_t	zcopy_arg;
		pr_call_t	pr_arg;
		ls_call_t	ls_arg;
		sl_call_t	sl_arg;
	} cargs;
} labeld_call_t;

/* Labeld operation return structure */

typedef struct {
	int	ret;		/* labeld return codes */
	int	err;		/* function error codes */
	union	{
		null_ret_t	null_ret;

		inset_ret_t	inset_ret;
		slvalid_ret_t	slvalid_ret;
		clrvalid_ret_t	clrvalid_ret;
		info_ret_t	info_ret;
		vers_ret_t	vers_ret;
		color_ret_t	color_ret;

		bsltos_ret_t	bsltos_ret;
		bcleartos_ret_t	bcleartos_ret;

		stobsl_ret_t	stobsl_ret;
		stobclear_ret_t	stobclear_ret;

		bslcvt_ret_t	bslcvt_ret;
		bclearcvt_ret_t	bclearcvt_ret;
		fields_ret_t	fields_ret;
		udefs_ret_t	udefs_ret;
		setfbcl_ret_t	setfbcl_ret;
		zcopy_ret_t	zcopy_ret;
		pr_ret_t	pr_ret;
		ls_ret_t	ls_ret;
		sl_ret_t	sl_ret;
	} rvals;
} labeld_ret_t;

/* Labeld call/return structure */

typedef	struct {
	union {
		labeld_call_t	acall;
		labeld_ret_t	aret;
	} param;
} labeld_data_t;

#define	callop	param.acall.op
#define	retret	param.aret.ret
#define	reterr	param.aret.err

#define	CALL_SIZE(type, buf)	(size_t)(sizeof (type) + sizeof (int) + (buf))
#define	RET_SIZE(type, buf)	(size_t)(sizeof (type) + 2*sizeof (int) + (buf))
#define	CALL_SIZE_STR(type, buf)	CALL_SIZE(type, (-BUFSIZE +(buf)))

/* Labeld common client call function */

int
__call_labeld(labeld_data_t **dptr, size_t *ndata, size_t *adata);

/* Return Codes */

#define	SUCCESS		1	/* Call OK */
#define	NOTFOUND	-1	/* Function not found */
#define	SERVERFAULT	-2	/* Internal labeld error */
#define	NOSERVER	-3	/* No server thread available, try later */

/* Flag Translation Values */

#define	L_NEW_LABEL		0x10000000

/* GFI FLAGS */

#define	GFI_FLAG_MASK		 0x0000FFFF
#define	GFI_ACCESS_RELATED	 0x00000001

/* binary to ASCII */

#define	LABELS_NO_CLASS		 0x00010000
#define	LABELS_SHORT_CLASS	 0x00020000
#define	LABELS_SHORT_WORDS	 0x00040000

/* Label view */

#define	LABELS_VIEW_INTERNAL	 0x00100000
#define	LABELS_VIEW_EXTERNAL	 0x00200000

/* Dimming list (convert -- b*cvt* ) */

#define	LABELS_FULL_CONVERT	 0x00010000

/* ASCII to binary */

#define	LABELS_NEW_LABEL	 0x00010000
#define	LABELS_FULL_PARSE	 0x00020000
#define	LABELS_ONLY_INFO_LABEL	 0x00040000

#define	MOVE_FILE	0
#define	COPY_FILE	1
#define	LINK_FILE	2

#define	PIPEMSG_FILEOP_ERROR	1
#define	PIPEMSG_EXIST_ERROR	2
#define	PIPEMSG_DONE 		7
#define	PIPEMSG_PATH_ERROR	20
#define	PIPEMSG_ZONE_ERROR	21
#define	PIPEMSG_LABEL_ERROR	22
#define	PIPEMSG_READ_ERROR	23
#define	PIPEMSG_READONLY_ERROR  24
#define	PIPEMSG_WRITE_ERROR	25
#define	PIPEMSG_CREATE_ERROR	26
#define	PIPEMSG_DELETE_ERROR	27
#define	PIPEMSG_CANCEL		101
#define	PIPEMSG_PROCEED		102
#define	PIPEMSG_MERGE		103
#define	PIPEMSG_REPLACE_BUFFER	104
#define	PIPEMSG_RENAME_BUFFER	105
#define	PIPEMSG_MULTI_PROCEED	106
#define	PIPEMSG_RENAME_FILE	107

#ifdef	__cplusplus
}
#endif

#endif	/* _LABELD_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 (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# MAPFILE HEADER START
#
# WARNING:  STOP NOW.  DO NOT MODIFY THIS FILE.
# Object versioning must comply with the rules detailed in
#
#	usr/src/lib/README.mapfiles
#
# You should not be making modifications here until you've read the most current
# copy of that file. If you need help, contact a gatekeeper for guidance.
#
# MAPFILE HEADER END
#

$mapfile_version 2

SYMBOL_VERSION SUNW_2.1 {
    global:
	bldominates;
	blequal;
	blstrictdom;
	fgetlabel;
	getlabel;
	getplabel;
	getuserrange;
	getzoneidbylabel;
	getzonelabelbyid;
	getzonelabelbyname;
	getzonerootbyid;
	getzonerootbylabel;
	getzonerootbyname;
	label_to_str;
	m_label_alloc;
	m_label_dup;
	m_label_free;
	setflabel;
	str_to_label;
};

SYMBOL_VERSION SUNWprivate_1.1 {
    global:
	bclearcvt;
	bclearcvtfull;
	bclearhigh;
	bclearlow;
	bcleartoh;
	bcleartoh_r;
	bcleartos;
	bclearundef;
	bclearvalid;
	bisinvalid;
	blabel_alloc;
	blabel_free;
	blabel_size;
	blinrange;
	blinset;
	blmaximum;
	blminimum;
	bltocolor;
	bltocolor_r;
	bltype;
	bslcvt;
	bslcvtfull;
	bslhigh;
	bsllow;
	bsltoh;
	bsltoh_r;
	bsltos;
	bslundef;
	bslvalid;
	getlabelbypath;
	getpathbylabel;
	h_alloc;
	h_free;
	hexstr_to_label;
	htobclear;
	htobsl;
	l_to_str_internal;
	labelfields;
	labelinfo;
	labelvers;
	sbcleartos;
	sbsltos;
	setbltype;
	set_effective_priv;
	set_inheritable_priv;
	set_permitted_priv;
	stobclear;
	stobsl;
	userdefs;
	zonecopy;
    local:
	*;
};
/*
 * 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.
 */


/*
 *	Miscellaneous user interfaces to trusted label functions.
 *
 */


#include <ctype.h>
#include <stdlib.h>
#include <strings.h>

#include <sys/mman.h>

#include <tsol/label.h>

#include "labeld.h"
#include "clnt.h"
#include <sys/tsol/label_macro.h>
#include <secdb.h>
#include <user_attr.h>

static	bslabel_t slow, shigh;	/* static Admin Low and High SLs */
static	bclear_t  clow, chigh;	/* static Admin Low and High CLRs */

static char color[MAXCOLOR];


#define	incall callp->param.acall.cargs.inset_arg
#define	inret callp->param.aret.rvals.inset_ret
/*
 *	blinset - Check in a label set.
 *
 *	Entry	label = Sensitivity Label to check.
 *		id    = Label set identifier of set to check.
 *
 *	Exit	None.
 *
 *	Returns	-1, If label set unavailable, or server failure.
 *		 0, If label not in label set.
 *		 1, If label is in the label set.
 *
 *	Calls	__call_labeld(BLINSET), BLTYPE, BSLLOW, BSLHIGH.
 *
 *	Uses	slow, shigh.
 */

int
blinset(const bslabel_t *label, const set_id *id)
{
	if (id->type == SYSTEM_ACCREDITATION_RANGE) {
		if (!BLTYPE(&slow, SUN_SL_ID)) {
			/* initialize static labels. */

			BSLLOW(&slow);
			BSLHIGH(&shigh);
		}

		if (BLTYPE(label, SUN_SL_ID) &&
		    (BLEQUAL(label, &slow) || BLEQUAL(label, &shigh)))

			return (1);
	}
	if (id->type == USER_ACCREDITATION_RANGE ||
	    id->type == SYSTEM_ACCREDITATION_RANGE) {
		labeld_data_t	call;
		labeld_data_t	*callp = &call;
		size_t	bufsize = sizeof (labeld_data_t);
		size_t	datasize = CALL_SIZE(inset_call_t, 0);

		call.callop = BLINSET;
		incall.label = *label;
		incall.type = id->type;

		if (__call_labeld(&callp, &bufsize, &datasize) != SUCCESS) {
			/* process error */

			return (-1);
		}
		return (inret.inset);
	} else {
		/*
		 * Only System and User Accreditation Ranges presently
		 * implemented.
		 */
		return (-1);
	}
}
#undef	incall
#undef	inret

#define	slvcall callp->param.acall.cargs.slvalid_arg
#define	slvret callp->param.aret.rvals.slvalid_ret
/*
 *	bslvalid - Check Sensitivity Label for validity.
 *
 *	Entry	label = Sensitivity Label to check.
 *
 *	Exit	None.
 *
 *	Returns	-1, If unable to access label encodings file, or server failure.
 *		 0, If label not valid.
 *		 1, If label is valid.
 *
 *	Calls	__call_labeld(BSLVALID), BLTYPE, BSLLOW, BSLHIGH.
 *
 *	Uses	slow, shigh.
 *
 */

int
bslvalid(const bslabel_t *label)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(slvalid_call_t, 0);

	if (!BLTYPE(&slow, SUN_SL_ID)) {
		/* initialize static labels. */

		BSLLOW(&slow);
		BSLHIGH(&shigh);
	}

	if (BLTYPE(label, SUN_SL_ID) &&
	    (BLEQUAL(label, &slow) || BLEQUAL(label, &shigh))) {

		return (1);
	}

	call.callop = BSLVALID;
	slvcall.label = *label;

	if (__call_labeld(&callp, &bufsize, &datasize) != SUCCESS) {
		/* process error */

		return (-1);
	}
	return (slvret.valid);
}
#undef	slvcall
#undef	slvret

#define	clrvcall callp->param.acall.cargs.clrvalid_arg
#define	clrvret callp->param.aret.rvals.clrvalid_ret
/*
 *	bclearvalid - Check Clearance for validity.
 *
 *	Entry	clearance = Clearance to check.
 *
 *	Exit	None.
 *
 *	Returns	-1, If unable to access label encodings file, or server failure.
 *		 0, If label not valid.
 *		 1, If label is valid.
 *
 *	Calls	__call_labeld(BCLEARVALID), BLTYPE, BCLEARLOW, BCLEARHIGH.
 *
 *	Uses	clow, chigh.
 *
 */

int
bclearvalid(const bclear_t *clearance)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(clrvalid_call_t, 0);

	if (!BLTYPE(&clow, SUN_CLR_ID)) {
		/* initialize static labels. */

		BCLEARLOW(&clow);
		BCLEARHIGH(&chigh);
	}

	if (BLTYPE(clearance, SUN_CLR_ID) &&
	    (BLEQUAL(clearance, &clow) || BLEQUAL(clearance, &chigh))) {

		return (1);
	}

	call.callop = BCLEARVALID;
	clrvcall.clear = *clearance;

	if (__call_labeld(&callp, &bufsize, &datasize) != SUCCESS) {
		/* process error */

		return (-1);
	}
	return (clrvret.valid);
}
#undef	clrvcall
#undef	clrvret

#define	inforet callp->param.aret.rvals.info_ret
/*
 *	labelinfo - Get information about the label encodings file.
 *
 *	Entry	info = Address of label_info structure to update.
 *
 *	Exit	info = Updated.
 *
 *	Returns	-1, If unable to access label encodings file, or server failure.
 *		 1, If successful.
 *
 *	Calls	__call_labeld(LABELINFO).
 */

int
labelinfo(struct label_info *info)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(info_call_t, 0);
	int	rval;

	call.callop = LABELINFO;

	if ((rval = __call_labeld(&callp, &bufsize, &datasize)) != SUCCESS) {
		/* process error */

		return (-1);
	}
	*info = inforet.info;
	return (rval);
}
#undef	inforet

#define	lvret callp->param.aret.rvals.vers_ret
/*
 *	labelvers - Get version string of the label encodings file.
 *
 *	Entry	version = Address of string pointer to return.
 *		len = Length of string if pre-allocated.
 *
 *	Exit	version = Updated.
 *
 *	Returns	-1, If unable to access label encodings file, or server failure.
 *		 0, If unable to allocate version string,
 *			or pre-allocated version string to short
 *			(and **version = '\0').
 *		length (including null) of version string, If successful.
 *
 *	Calls	__call_labeld(LABELVERS)
 *			malloc, strlen.
 */

ssize_t
labelvers(char **version, size_t len)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(vers_call_t, 0);
	size_t	ver_len;

	call.callop = LABELVERS;

	if (__call_labeld(&callp, &bufsize, &datasize) != SUCCESS) {

		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (-1);
	}

	/* unpack length */

	ver_len = strlen(lvret.vers) + 1;
	if (*version == NULL) {
		if ((*version = malloc(ver_len)) == NULL) {
			if (callp != &call)
				/* release return buffer */
				(void) munmap((void *)callp, bufsize);
			return (0);
		}
	} else if (ver_len > len) {
		**version = '\0';
		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (0);
	}
	(void) strcpy(*version, lvret.vers);

	if (callp != &call)
		/* release return buffer */
		(void) munmap((void *)callp, bufsize);
	return (ver_len);
}  /* labelvers */
#undef	lvret

#define	ccall callp->param.acall.cargs.color_arg
#define	cret callp->param.aret.rvals.color_ret
/*
 *	bltocolor - get ASCII color name of label.
 *
 *	Entry	label = Sensitivity Level of color to get.
 *		size  = Size of the color_name array.
 *		color_name = Storage for ASCII color name string to be returned.
 *
 *	Exit	None.
 *
 *	Returns	NULL, If error (label encodings file not accessible,
 *			   invalid label, no color for this label).
 *		Address of color_name parameter containing ASCII color name
 *			defined for the label.
 *
 *	Calls	__call_labeld(BLTOCOLOR), strlen.
 */

char *
bltocolor_r(const blevel_t *label, size_t size, char *color_name)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(color_call_t, 0);
	char	*colorp;

	call.callop = BLTOCOLOR;
	ccall.label = *label;

	if ((__call_labeld(&callp, &bufsize, &datasize) != SUCCESS) ||
	    (callp->reterr != 0) ||
	    (strlen(cret.color) >= size)) {

		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (NULL);
	}

	colorp = strcpy(color_name, cret.color);

	if (callp != &call)
		/* release return buffer */
		(void) munmap((void *)callp, bufsize);
	return (colorp);
}  /* bltocolor_r */
#undef	ccall
#undef	cret

/*
 *	bltocolor - get ASCII color name of label.
 *
 *	Entry	label = Sensitivity Level of color to get.
 *
 *	Exit	None.
 *
 *	Returns	NULL, If error (label encodings file not accessible,
 *			   invalid label, no color for this label).
 *		Address of statically allocated string containing ASCII
 *			color name defined for the classification contained
 *			in label.
 *
 *	Uses	color.
 *
 *	Calls	bltocolor_r.
 */

char *
bltocolor(const blevel_t *label)
{
	return (bltocolor_r(label, sizeof (color), color));
}  /* bltocolor */

blevel_t *
blabel_alloc(void)
{
	return (m_label_alloc(MAC_LABEL));
}

void
blabel_free(blevel_t *label_p)
{
	free(label_p);
}

size32_t
blabel_size(void)
{
	return (sizeof (blevel_t));
}

/*
 *	getuserrange - get label range for user
 *
 *	Entry	username of user
 *
 *	Exit	None.
 *
 *	Returns	NULL, If memory allocation failure or userdefs failure.
 *		otherwise returns the allocates m_range_t with the
 *		user's min and max labels set.
 */

m_range_t *
getuserrange(const char *username)
{
	char		*kv_str = NULL;
	userattr_t 	*userp = NULL;
	m_range_t 	*range;
	m_label_t	*def_min, *def_clr;

	/*
	 * Get some memory
	 */

	if ((range = malloc(sizeof (m_range_t))) == NULL) {
		return (NULL);
	}
	if ((range->lower_bound = m_label_alloc(MAC_LABEL)) == NULL) {
		free(range);
		return (NULL);
	}
	def_min = range->lower_bound;
	if ((range->upper_bound = m_label_alloc(USER_CLEAR)) == NULL) {
		m_label_free(range->lower_bound);
		free(range);
		return (NULL);
	}
	def_clr = range->upper_bound;

	/* If the user has an explicit min_label or clearance, use it. */
	if ((userp = getusernam(username)) != NULL) {
		if ((kv_str = kva_match(userp->attr, USERATTR_MINLABEL))
		    != NULL) {
			(void) str_to_label(kv_str, &range->lower_bound,
			    MAC_LABEL, L_NO_CORRECTION, NULL);
			def_min = NULL;		/* don't get default later */
		}
		if ((kv_str = kva_match(userp->attr, USERATTR_CLEARANCE))
		    != NULL) {
			(void) str_to_label(kv_str, &range->upper_bound,
			    USER_CLEAR, L_NO_CORRECTION, NULL);
			def_clr = NULL;		/* don't get default later */
		}
		free_userattr(userp);
	}
	if (def_min || def_clr) {
		/* Need to use system default clearance and/or min_label */
		if ((userdefs(def_min, def_clr)) == -1) {
			m_label_free(range->lower_bound);
			m_label_free(range->upper_bound);
			free(range);
			return (NULL);
		}
	}

	return (range);
}
/*
 * 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.
 */

/*
 *	Label library contract private interfaces.
 *
 *	Binary labels to String labels with dimming word lists.
 *	Dimming word list titles.
 *	Default user labels.
 */

#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>

#include <sys/mman.h>

#include <tsol/label.h>

#include "clnt.h"
#include "labeld.h"

/*
 *	cvt memory:
 *
 * cvt:	char	*long_words[display_size];	Pointers to long words
 *	char	*short_words[display_size];	Pointers to short words
 * dim:	char	display[display_size];		Dim | Set
 *
 *	    strings associated with long and short words.
 *
 */

/*
 *	Sensitivity Label words.
 */

static	char *slcvt = NULL;
static	int   slcvtsize = 0;
static	char *sldim;

static	char *slstring = NULL;
static	int   slstringsize = 0;
static	brange_t sbounds;

/*
 *	Clearance words.
 */

static	char *clrcvt = NULL;
static	int   clrcvtsize = 0;
static	char *clrdim;

static	char *clrstring = NULL;
static	int   clrstringsize = 0;
static	brange_t cbounds;

static
int
alloc_words(char **words, const size_t size)
{
	if (*words == NULL) {
		if ((*words = malloc(size)) == NULL)
			return (0);
	} else {
		if ((*words = realloc(*words, size)) == NULL) {
			return (0);
		}
	}
	return (1);
}

/*
 *	build_strings - Build the static strings and dimming list for a
 *			converted label.
 *
 *	Entry	new_string = Newly converted string.
 *		new_words_size = Size of words associated with newly converted
 *				 label.
 *		number_of_words = Number of words associated with newly
 *				  converted label.
 *		full =	1, if static words lists to be updated.
 *			0, if only string and dimming list to be updated.
 *
 *	Exit	static_string_size = Updated if needed.
 *		static_string = Updated to new label string.
 *		static_words_size = Updated if needed.
 *		static_words = Updated to new words list, if needed.
 *		static_dimming = Updated to new dimming state.
 *		long_words = Updated to new long words pointers, if needed.
 *		short_words = Updated to new short words pointers, if needed.
 *
 *
 *	Returns	0, If unable to allocate memory.
 *		1, If successful.
 *
 *	Calls	alloc_string, alloc_words, memcpy, strcpy, strlen.
 */

static
int
build_strings(int *static_string_size, char **static_string, char *new_string,
    int *static_words_size, int new_words_size, char **static_words,
    char **static_dimming, int number_of_words, char *long_words,
    char *short_words, char *dimming_list, int full)
{
	char	**l;
	char	**s;
	char	*w;
	char	*l_w = long_words;
	char	*s_w = short_words;
	int	i;
	int	len;
	int	newsize;

	if (*static_string_size == 0) { /* Allocate string memory. */
		if ((*static_string_size = alloc_string(static_string,
		    *static_string_size, 'C')) == 0)
			/* can't get string memory for string */
			return (0);
	}

again:
	if (*static_string_size < (int)strlen(new_string)+1) {
		/* need longer string */
		if ((newsize = alloc_string(static_string, *static_string_size,
		    'C')) == 0)
			/* can't get more string memory */
			return (0);

		*static_string_size += newsize;
		goto again;
	}
	bcopy(new_string, *static_string, strlen(new_string) + 1);

	if (full) {
		if (*static_words_size < new_words_size &&
		    !alloc_words(static_words, new_words_size)) {
			/* can't get more words memory */
			return (0);
		} else {
			*static_words_size = new_words_size;
		}
		/*LINTED*/
		l = (char **)*static_words;
		s = l + number_of_words;
		*static_dimming = (char *)(s + number_of_words);
		w = *static_dimming + number_of_words;
		for (i = 0; i < number_of_words; i++) {
			*l = w;
			(void) strcpy(w, l_w);
			w += (len = strlen(l_w) + 1);
			l_w += len;
			if (*s_w == '\000') {
				*s = NULL;
				s_w++;
			} else {
				*s = w;
				(void) strcpy(w, s_w);
				w += (len = strlen(s_w) + 1);
				s_w += len;
			}

			l++;
			s++;
		}  /* for each word entry */
	}  /* if (full) */

	bcopy(dimming_list, *static_dimming, number_of_words);
	return (1);
}  /* build_strings */

#define	bsfcall callp->param.acall.cargs.bslcvt_arg
#define	bsfret callp->param.aret.rvals.bslcvt_ret
/*
 *	bslcvtfull - Convert Sensitivity Label and initialize static
 *			information.
 *
 *	Entry	label = Sensitivity Label to convert and get dimming list.
 *			This label should lie within the bounds or the
 *			results may not be meaningful.
 *		bounds = Lower and upper bounds for words lists. Must be
 *			dominated by clearance.
 *		flags = VIEW_INTERNAL, don't promote/demote admin low/high.
 *			VIEW_EXTERNAL, promote/demote admin low/high.
 *
 *	Exit	string = ASCII coded Sensitivity Label.
 *		long_words = Array of pointers to visible long word names.
 *		short_words = Array of pointers to visible short word names.
 *		display = Array of indicators as to whether the word is present
 *			  in the converted label (CVT_SET), and/or changeable
 *			  (CVT_DIM).
 *		first_compartment = Zero based index of first compartment.
 *		display_size = Number of entries in the display/words lists.
 *
 *	Returns	-1, If unable to access label encodings database, or
 *			invalid label.
 *		 0, If unable to allocate static memory.
 *		 1, If successful.
 *
 *	Calls	RPC - LABELS_BSLCONVERT, STTBLEVEL, SETBSLABEL, TCLNT,
 *			build_strings, clnt_call, clnt_perror.
 *
 *	Uses	sbounds, slrcvt, slrcvtsize, slrdim, slrstring,
 *			slrstringsize.
 */

int
bslcvtfull(const bslabel_t *label, const blrange_t *bounds, int flags,
    char **string, char **long_words[], char **short_words[], char *display[],
    int *first_compartment, int *display_size)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(bslcvt_call_t, 0);
	int	new_words_size;
	int	rval;

	call.callop = BSLCVT;
	bsfcall.label = *label;
	bsfcall.bounds.upper_bound = *bounds->upper_bound;
	bsfcall.bounds.lower_bound = *bounds->lower_bound;
	bsfcall.flags = LABELS_FULL_CONVERT;
	set_label_view(&bsfcall.flags, flags);

	if ((rval = __call_labeld(&callp, &bufsize, &datasize)) == NOSERVER) {
#ifdef	DEBUG
		(void) fprintf(stderr, "No label server.\n");
#endif	/* DEBUG */
		return (-1);
	} else if (rval != SUCCESS) {
		return (-1);
	} else {
		if (callp->reterr != 0)
			return (-1);
	}

	*first_compartment = bsfret.first_comp;
	*display_size = bsfret.d_len;

	new_words_size = bsfret.l_len + bsfret.s_len + bsfret.d_len +
	    (2 * sizeof (char *)) * bsfret.d_len;

	if (build_strings(&slstringsize, &slstring, &bsfret.buf[bsfret.string],
	    &slcvtsize, new_words_size, &slcvt, &sldim, bsfret.d_len,
	    &bsfret.buf[bsfret.lwords], &bsfret.buf[bsfret.swords],
	    &bsfret.buf[bsfret.dim], 1) != 1) {
		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (0);
	}

	/* save for bslcvt call */
	sbounds.upper_bound = *bounds->upper_bound;
	sbounds.lower_bound = *bounds->lower_bound;

	*string = slstring;
	*display = sldim;
	/*LINTED*/
	*long_words = (char **)slcvt;
	/*LINTED*/
	*short_words = (char **)(slcvt + *display_size * sizeof (char *));
	if (callp != &call)
		/* release return buffer */
		(void) munmap((void *)callp, bufsize);
	return (1);
}  /* bslcvtfull */
#undef	bsfcall
#undef	bsfret

#define	bsccall callp->param.acall.cargs.bslcvt_arg
#define	bscret callp->param.aret.rvals.bslcvt_ret
/*
 *	bslcvt - Convert Sensitivity Label and update dimming information.
 *
 *	Entry	label = Sensitivity Label to convert and get dimming list.
 *			This label should lie within the bounds of the
 *			corresponding bslcvtfull call or the results may
 *			not be meaningful.
 *		flags = VIEW_INTERNAL, don't promote/demote admin low/high.
 *			VIEW_EXTERNAL, promote/demote admin low/high.
 *
 *	Exit	string = ASCII coded Sensitivity Label.
 *		display = Array of indicators as to whether the word is present
 *			  in the converted label (CVT_SET), and/or changeable
 *			  (CVT_DIM).
 *
 *	Returns	-1, If unable to access label encodings database, or
 *			invalid label.
 *		 0, If unable to allocate static memory.
 *		 1, If successful.
 *
 *	Calls	RPC - LABELS_BSLCONVERT, SETBLEVEL, SETBSLABEL, build_strings
 *			clnt_call, clnt_perror.
 *
 *	Uses	sbounds, slrdim, slrstring.
 */

int
bslcvt(const bslabel_t *label, int flags, char **string, char *display[])
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(bslcvt_call_t, 0);
	int	rval;

	if (slcvt == NULL)
		return (-1);	/* conversion not initialized */

	call.callop = BSLCVT;
	bsccall.label = *label;
	bsccall.bounds = sbounds;	/* save from last bslcvtfull() call */
	bsccall.flags = 0;
	set_label_view(&bsccall.flags, flags);

	if ((rval = __call_labeld(&callp, &bufsize, &datasize)) == NOSERVER) {
#ifdef	DEBUG
		(void) fprintf(stderr, "No label server.\n");
#endif	/* DEBUG */
		return (-1);
	} else if (rval != SUCCESS) {
		return (-1);
	} else {
		if (callp->reterr != 0)
			return (-1);
	}

	if (build_strings(&slstringsize, &slstring, &bscret.buf[bscret.string],
	    &slcvtsize, 0, &slcvt, &sldim, bscret.d_len,
	    &bscret.buf[bscret.lwords], &bscret.buf[bscret.swords],
	    &bscret.buf[bscret.dim], 0) != 1) {
		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (0);
	}

	*string = slstring;
	*display = sldim;
	if (callp != &call)
		/* release return buffer */
		(void) munmap((void *)callp, bufsize);
	return (1);
}  /* bslcvt */
#undef	bsccall
#undef	bscret

#define	bcfcall callp->param.acall.cargs.bclearcvt_arg
#define	bcfret callp->param.aret.rvals.bclearcvt_ret
/*
 *	bclearcvtfull - Convert Clearance and initialize static information.
 *
 *	Entry	clearance = Clearance to convert and get dimming list.
 *			    This clearance should lie within the bounds or
 *			    the results may not be meaningful.
 *		bounds = Lower and upper bounds for words lists. Must be
 *			dominated by clearance.
 *		flags = VIEW_INTERNAL, don't promote/demote admin low/high.
 *			VIEW_EXTERNAL, promote/demote admin low/high.
 *
 *	Exit	string = ASCII coded Clearance.
 *		long_words = Array of pointers to visible long word names.
 *		short_words = Array of pointers to visible short word names.
 *		display = Array of indicators as to whether the word is present
 *			  in the converted label (CVT_SET), and/or changeable
 *			  (CVT_DIM).
 *		first_compartment = Zero based index of first compartment.
 *		display_size = Number of entries in the display/words lists.
 *
 *	Returns	-1, If unable to access label encodings database, or
 *			invalid label.
 *		 0, If unable to allocate static memory.
 *		 1, If successful.
 *
 *	Calls	RPC - LABELS_BCLEARCONVERT, SETBCLEAR, SETBLEVEL, TCLNT,
 *			build_strings, clnt_call, clnt_perror.
 *
 *	Uses	cbounds, clrcvt, clrcvtsize, clrdim, clrstring,
 *			clrstringsize.
 */

int
bclearcvtfull(const bclear_t *clearance, const blrange_t *bounds,
    int flags, char **string, char **long_words[], char **short_words[],
    char *display[], int *first_compartment, int *display_size)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(bclearcvt_call_t, 0);
	int	new_words_size;
	int	rval;

	call.callop = BCLEARCVT;
	bcfcall.clear = *clearance;
	bcfcall.bounds.upper_bound = *bounds->upper_bound;
	bcfcall.bounds.lower_bound = *bounds->lower_bound;
	bcfcall.flags = LABELS_FULL_CONVERT;
	set_label_view(&bcfcall.flags, flags);

	if ((rval = __call_labeld(&callp, &bufsize, &datasize)) == NOSERVER) {
#ifdef	DEBUG
		(void) fprintf(stderr, "No label server.\n");
#endif	/* DEBUG */
		return (-1);
	} else if (rval != SUCCESS) {
		return (-1);
	} else {
		if (callp->reterr != 0)
			return (-1);
	}

	*first_compartment = bcfret.first_comp;
	*display_size = bcfret.d_len;

	new_words_size = bcfret.l_len + bcfret.s_len + bcfret.d_len +
	    (2 * sizeof (char *)) * bcfret.d_len;

	if (build_strings(&clrstringsize, &clrstring,
	    &bcfret.buf[bcfret.string],
	    &clrcvtsize, new_words_size, &clrcvt,
	    &clrdim, bcfret.d_len,
	    &bcfret.buf[bcfret.lwords], &bcfret.buf[bcfret.swords],
	    &bcfret.buf[bcfret.dim], 1) != 1) {
		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (0);
	}

	/* save for bclearcvt call */
	cbounds.upper_bound = *bounds->upper_bound;
	cbounds.lower_bound = *bounds->lower_bound;

	*string = clrstring;
	*display = clrdim;
	/*LINTED*/
	*long_words = (char **)clrcvt;
	/*LINTED*/
	*short_words = (char **)(clrcvt + *display_size * sizeof (char *));
	if (callp != &call)
		/* release return buffer */
		(void) munmap((void *)callp, bufsize);
	return (1);
}  /* bclearcvtfull */
#undef	bcfcall
#undef	bcfret

#define	bcccall callp->param.acall.cargs.bclearcvt_arg
#define	bccret callp->param.aret.rvals.bclearcvt_ret
/*
 *	bclearcvt - Convert Clearance and update dimming inforamtion.
 *
 *	Entry	clearance = Clearance to convert and get dimming list.
 *			    This clearance should lie within the bounds of the
 *			    corresponding bclearcvtfull call or the results may
 *			    not be meaningful.
 *		flags = VIEW_INTERNAL, don't promote/demote admin low/high.
 *			VIEW_EXTERNAL, promote/demote admin low/high.
 *
 *	Exit	string = ASCII coded Clearance.
 *		display = Array of indicators as to whether the word is present
 *			  in the converted label (CVT_SET), and/or changeable
 *			  (CVT_DIM).
 *
 *	Returns	-1, If unable to access label encodings database, or
 *			invalid label.
 *		 0, If unable to allocate static memory.
 *		 1, If successful.
 *
 *	Calls	RPC - LABELS_BCLEARCONVERT, SETBCLEAR, SETBLEVEL, build_strings,
 *			clnt_call, clnt_perror.
 *
 *	Uses	cbounds, clrdim, clrstring.
 */

int
bclearcvt(const bclear_t *clearance, int flags, char **string,
    char *display[])
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(bclearcvt_call_t, 0);
	int	rval;

	if (clrcvt == NULL)
		return (-1);	/* conversion not initialized */

	call.callop = BCLEARCVT;
	bcccall.clear = *clearance;
	bcccall.bounds = cbounds;	/* save from last bslcvtfull() call */
	bcccall.flags = 0;
	set_label_view(&bcccall.flags, flags);

	if ((rval = __call_labeld(&callp, &bufsize, &datasize)) == NOSERVER) {
#ifdef	DEBUG
		(void) fprintf(stderr, "No label server.\n");
#endif	/* DEBUG */
		return (-1);
	} else if (rval != SUCCESS) {
		return (-1);
	} else {
		if (callp->reterr != 0)
			return (-1);
	}

	if (build_strings(&clrstringsize, &clrstring,
	    &bccret.buf[bccret.string],
	    &clrcvtsize, 0, &clrcvt, &clrdim, bccret.d_len,
	    &bccret.buf[bccret.lwords], &bccret.buf[bccret.swords],
	    &bccret.buf[bccret.dim], 0) != 1) {
		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (0);
	}

	*string = clrstring;
	*display = clrdim;
	if (callp != &call)
		/* release return buffer */
		(void) munmap((void *)callp, bufsize);
	return (1);
}  /* bclearcvt */
#undef	bcccall
#undef	bccret

#define	lfret callp->param.aret.rvals.fields_ret
/*
 *	labelfields - Return names for the label fields.
 *
 *	Entry	None
 *
 *	Exit	fields = Updated.
 *
 *	Returns	-1, If unable to access label encodings file, or
 *			labels server failure.
 *		 0, If unable to allocate memory.
 *		 1, If successful.
 *
 *	Calls __call_labeld(LABELFIELDS).
 */

int
labelfields(struct name_fields *fields)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(fields_call_t, 0);
	int	rval;

	call.callop = LABELFIELDS;

	if ((rval = __call_labeld(&callp, &bufsize, &datasize)) != SUCCESS) {

		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (-1);
	}

	/* unpack results */

	if ((fields->class_name = strdup(&lfret.buf[lfret.classi])) == NULL) {
		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (0);
	}
	if ((fields->comps_name = strdup(&lfret.buf[lfret.compsi])) == NULL) {
		free(fields->class_name);
		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (0);
	}
	if ((fields->marks_name = strdup(&lfret.buf[lfret.marksi])) == NULL) {
		free(fields->class_name);
		free(fields->comps_name);
		if (callp != &call)
			/* release return buffer */
			(void) munmap((void *)callp, bufsize);
		return (0);
	}

	if (callp != &call)
		/* release return buffer */
		(void) munmap((void *)callp, bufsize);
	return (rval);
}  /* labelfields */
#undef	lfret

#define	udret callp->param.aret.rvals.udefs_ret
/*
 *	userdefs - Get default user Sensitivity Label and/or Clearance.
 *
 *	Entry   None.
 *
 *	Exit	sl = default user Sensitivity Label.
 *		clear = default user Clearance.
 *
 *	Returns -1, If unable to access label encodings file, or
 *			labels server failure.
 *		1, If successful.
 *
 *	Calls	__call_labeld(UDEFS).
 */

int
userdefs(bslabel_t *sl, bclear_t *clear)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(udefs_call_t, 0);
	int	rval;

	call.callop = UDEFS;

	if ((rval = __call_labeld(&callp, &bufsize, &datasize)) != SUCCESS) {
		/* process error */

		return (-1);
	}

	if (sl != NULL)
		*sl = udret.sl;
	if (clear != NULL)
		*clear = udret.clear;
	return (rval);
}  /* userdefs */
#undef	udret
/*
 * 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.
 */

#include 	<errno.h>
#include 	<priv.h>
#include 	<sys/tsol/priv.h>
#include 	<sys/varargs.h>

/*
 * set_effective_priv(op, num_priv, priv_id1, priv_id2, ... )
 *
 * Library routine to enable a user process to set its effective
 * privilege set appropriately using a single call.  User is
 * required to specify the number of privilege ids that follow as
 * arguments, rather than depending on the compiler to terminate
 * the argument list with a NULL, which may be compiler-dependent.
 */
int
set_effective_priv(priv_op_t op, int num_priv, ...)
{
	priv_set_t *priv_set;
	priv_t priv_id;
	va_list ap;
	int	status;

	priv_set = priv_allocset();
	PRIV_EMPTY(priv_set);

	va_start(ap, num_priv);
	while (num_priv--) {
		char	*priv_name;
		/*
		 * Do sanity checking on priv_id's here to assure
		 * valid inputs to privilege macros.  This checks
		 * num_priv argument as well.
		 */
		priv_id = va_arg(ap, priv_t);
		priv_name = (char *)priv_getbynum((int)(uintptr_t)priv_id);
		if (priv_name == NULL) {
			errno = EINVAL;
			priv_freeset(priv_set);
			return (-1);
		}
		(void) priv_addset(priv_set, priv_name);
	}
	va_end(ap);

	/*
	 * Depend on system call to do sanity checking on "op"
	 */
	status = setppriv(op, PRIV_EFFECTIVE, priv_set);
	priv_freeset(priv_set);
	return (status);

} /* set_effective_priv() */




/*
 * set_inheritable_priv(op, num_priv, priv_id1, priv_id2, ... )
 *
 * Library routine to enable a user process to set its inheritable
 * privilege set appropriately using a single call.  User is
 * required to specify the number of privilege ids that follow as
 * arguments, rather than depending on the compiler to terminate
 * the argument list with a NULL, which may be compiler-dependent.
 */
int
set_inheritable_priv(priv_op_t op, int num_priv, ...)
{
	priv_set_t *priv_set;
	priv_t priv_id;
	va_list ap;
	int	status;

	priv_set = priv_allocset();

	PRIV_EMPTY(priv_set);

	va_start(ap, num_priv);
	while (num_priv--) {
		/*
		 * Do sanity checking on priv_id's here to assure
		 * valid inputs to privilege macros.  This checks
		 * num_priv argument as well.
		 */
		priv_id = va_arg(ap, priv_t);
		if ((char *)priv_getbynum((int)(uintptr_t)priv_id) == NULL) {
			errno = EINVAL;
			priv_freeset(priv_set);
			return (-1);
		}
		(void) PRIV_ASSERT(priv_set, priv_id);
	}
	va_end(ap);

	/*
	 * Depend on system call to do sanity checking on "op"
	 */
	status = setppriv(op, PRIV_INHERITABLE, priv_set);
	priv_freeset(priv_set);
	return (status);

} /* set_inheritable_priv() */




/*
 * set_permitted_priv(op, num_priv, priv_id1, priv_id2, ... )
 *
 * Library routine to enable a user process to set its permitted
 * privilege set appropriately using a single call.  User is
 * required to specify the number of privilege ids that follow as
 * arguments, rather than depending on the compiler to terminate
 * the argument list with a NULL, which may be compiler-dependent.
 */
int
set_permitted_priv(priv_op_t op, int num_priv, ...)
{
	priv_set_t *priv_set;
	priv_t priv_id;
	va_list ap;
	int	status;

	priv_set = priv_allocset();

	PRIV_EMPTY(priv_set);

	va_start(ap, num_priv);
	while (num_priv--) {
		/*
		 * Do sanity checking on priv_id's here to assure
		 * valid inputs to privilege macros.  This checks
		 * num_priv argument as well.
		 */
		priv_id = va_arg(ap, priv_t);
		if ((char *)priv_getbynum((int)(uintptr_t)priv_id) == NULL) {
			errno = EINVAL;
			priv_freeset(priv_set);
			return (-1);
		}
		(void) PRIV_ASSERT(priv_set, priv_id);
	}
	va_end(ap);

	/*
	 * Depend on system call to do sanity checking on "op"
	 */
	status = setppriv(op, PRIV_PERMITTED, priv_set);
	priv_freeset(priv_set);
	return (status);

} /* set_permitted_priv() */
/*
 * 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.
 */

/*
 *	Change the label of a file
 */

#include <ctype.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <errno.h>

#include <tsol/label.h>

#include "labeld.h"
#include <sys/tsol/label_macro.h>

#include <sys/types.h>

#include <zone.h>
#include <sys/zone.h>
#include <sys/param.h>
#include <string.h>

static int abspath(char *, const char *, char *);

/*
 * setflabel(3TSOL) - set file label
 *
 * This is the library interface to the door call.
 */

#define	clcall callp->param.acall.cargs.setfbcl_arg
#define	clret callp->param.aret.rvals.setfbcl_ret
/*
 *
 *	Exit	error = If error reported, the error indicator,
 *				-1, Unable to access label encodings file;
 *				 0, Invalid binary label passed;
 *				>0, Position after the first character in
 *				    string of error, 1 indicates entire string.
 *			Otherwise, unchanged.
 *
 *	Returns	0, If error.
 *		1, If successful.
 *
 *	Calls	__call_labeld(SETFLABEL)
 *
 */

int
setflabel(const char *path, m_label_t *label)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize;
	size_t	path_len;
	static char	cwd[MAXPATHLEN];
	char		canon[MAXPATHLEN];


	/*
	 * If path is relative and we haven't already determined the current
	 * working directory, do so now.  Calculating the working directory
	 * here lets us do the work once, instead of (potentially) repeatedly
	 * in realpath().
	 */
	if (*path != '/' && cwd[0] == '\0') {
		if (getcwd(cwd, MAXPATHLEN) == NULL) {
			cwd[0] = '\0';
			return (-1);
		}
	}
	/*
	 * Find an absolute pathname in the native file system name space that
	 * corresponds to path, stuffing it into canon.
	 */
	if (abspath(cwd, path, canon) < 0)
		return (-1);

	path_len = strlen(canon) + 1;

	datasize = CALL_SIZE(setfbcl_call_t, path_len - BUFSIZE);
	datasize += 2; /* PAD */

	if (datasize > bufsize) {
		if ((callp = (labeld_data_t *)malloc(datasize)) == NULL) {
			return (-1);
		}
		bufsize = datasize;
	}

	callp->callop = SETFLABEL;

	clcall.sl = *label;
	(void) strcpy(clcall.pathname, canon);

	if (__call_labeld(&callp, &bufsize, &datasize) == SUCCESS) {
		int err = callp->reterr;

		if (callp != &call) {
			/* free allocated buffer */
			free(callp);
		}
		/*
		 * reterr == 0, OK,
		 * reterr < 0, invalid binary label,
		 */
		if (err == 0) {
			if (clret.status > 0) {
				errno = clret.status;
				return (-1);
			} else {
				return (0);
			}
		} else if (err < 0) {
			err = 0;
		}
		errno = ECONNREFUSED;
		return (-1);
	} else {
		if (callp != &call) {
			/* free allocated buffer */
			free(callp);
		}
		/* server not present */
		errno = ECONNREFUSED;
		return (-1);
	}
}  /* setflabel */

#undef	clcall
#undef	clret

#define	clcall callp->param.acall.cargs.zcopy_arg
#define	clret callp->param.aret.rvals.zcopy_ret
/*
 *
 *	Exit	status = result of zone copy request
 *				-1, Copy not confirmed
 *			Otherwise, unchanged.
 *
 *	Returns	0, If error.
 *		1, If successful.
 *
 *	Calls	__call_labeld(ZCOPY)
 *
 */
int
zonecopy(m_label_t *src_win_sl, char *remote_dir, char *filename,
    char *local_dir, int  transfer_mode)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t		bufsize = sizeof (labeld_data_t);
	size_t		datasize;
	size_t		strings;
	size_t		remote_dir_len;
	size_t		filename_len;
	size_t		local_dir_len;
	size_t		display_len;
	char		*display;

	remote_dir_len = strlen(remote_dir) + 1;
	filename_len = strlen(filename) + 1;
	local_dir_len = strlen(local_dir) + 1;

	if ((display = getenv("DISPLAY")) == NULL)
		display = "";
	display_len = strlen(display) + 1;

	strings = remote_dir_len + filename_len + local_dir_len + display_len;

	datasize = CALL_SIZE(zcopy_call_t, strings - BUFSIZE);

	datasize += 4; /* PAD */

	if (datasize > bufsize) {
		if ((callp = (labeld_data_t *)malloc(datasize)) == NULL) {
			return (0);
		}
		bufsize = datasize;
	}

	strings = 0;
	callp->callop = ZCOPY;

	clcall.src_win_sl = *src_win_sl;
	clcall.transfer_mode = transfer_mode;
	clcall.remote_dir = strings;
	strings += remote_dir_len;
	clcall.filename = strings;
	strings += filename_len;
	clcall.local_dir = strings;
	strings += local_dir_len;
	clcall.display = strings;

	(void) strcpy(&clcall.buf[clcall.remote_dir], remote_dir);
	(void) strcpy(&clcall.buf[clcall.filename], filename);
	(void) strcpy(&clcall.buf[clcall.local_dir], local_dir);
	(void) strcpy(&clcall.buf[clcall.display], display);

	if (__call_labeld(&callp, &bufsize, &datasize) == SUCCESS) {
		int err = callp->reterr;

		if (callp != &call) {
			/* free allocated buffer */
			free(callp);
		}
		/*
		 * reterr == 0, OK,
		 * reterr < 0, transer not confirmed
		 */
		if (err == 0) {
			return (clret.status);
		} else if (err < 0) {
			err = 0;
		}
		return (PIPEMSG_CANCEL);
	} else {
		if (callp != &call) {
			/* free allocated buffer */
			free(callp);
		}
		/* server not present */
		return (PIPEMSG_CANCEL);
	}
}

/*
 * Convert the path given in raw to canonical, absolute, symlink-free
 * form, storing the result in the buffer named by canon, which must be
 * at least MAXPATHLEN bytes long.  If wd is non-NULL, assume that it
 * points to a path for the current working directory and use it instead
 * of invoking getcwd; accepting this value as an argument lets our caller
 * cache the value, so that realpath (called from this routine) doesn't have
 * to recalculate it each time it's given a relative pathname.
 *
 * Return 0 on success, -1 on failure.
 */
int
abspath(char *wd, const char *raw, char *canon)
{
	char		absbuf[MAXPATHLEN];

	/*
	 * Preliminary sanity check.
	 */
	if (raw == NULL || canon == NULL)
		return (-1);

	/*
	 * If the path is relative, convert it to absolute form,
	 * using wd if it's been supplied.
	 */
	if (raw[0] != '/') {
		char	*limit = absbuf + sizeof (absbuf);
		char	*d;

		/* Fill in working directory. */
		if (wd != NULL)
			(void) strncpy(absbuf, wd, sizeof (absbuf));
		else if (getcwd(absbuf, strlen(absbuf)) == NULL)
			return (-1);

		/* Add separating slash. */
		d = absbuf + strlen(absbuf);
		if (d < limit)
			*d++ = '/';

		/* Glue on the relative part of the path. */
		while (d < limit && (*d++ = *raw++))
			continue;

		raw = absbuf;
	}

	/*
	 * Call realpath to canonicalize and resolve symlinks.
	 */
	return (realpath(raw, canon) == NULL ? -1 : 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 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 *	String to binary label translations.
 */

#include <ctype.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>

#include <tsol/label.h>

#include "labeld.h"
#include <sys/tsol/label_macro.h>

#undef	CALL_SIZE
#define	CALL_SIZE(type, buf)	(size_t)(sizeof (type) - BUFSIZE + sizeof (int)\
	+ (buf))

#if	!defined(TEXT_DOMAIN)		/* should be defined by Makefiles */
#define	TEXT_DOMAIN "SYS_TEST"
#endif	/* TEXT_DOMAIN */

/* short hands */

#define	IS_ADMIN_LOW(sl) \
	((strncasecmp(sl, ADMIN_LOW, (sizeof (ADMIN_LOW) - 1)) == 0))

#define	IS_ADMIN_HIGH(sh) \
	((strncasecmp(sh, ADMIN_HIGH, (sizeof (ADMIN_HIGH) - 1)) == 0))

#define	ISHEX(f, s) \
	(((((f) & NEW_LABEL) == ((f) | NEW_LABEL)) || \
	(((f) & NO_CORRECTION) == ((f) | NO_CORRECTION))) && \
	(((s)[0] == '0') && (((s)[1] == 'x') || ((s)[1] == 'X'))))

#define	slcall callp->param.acall.cargs.stobsl_arg
#define	slret callp->param.aret.rvals.stobsl_ret
/*
 *	stobsl - Translate Sensitivity Label string to a Binary Sensitivity
 *		Label.
 *
 *	Entry	string = Sensitivity Label string to be translated.
 *		label = Address of Binary Sensitivity Label to be initialized or
 *			updated.
 *		flags = Flags to control translation:
 *			NO_CORRECTION implies NEW_LABEL.
 *			NEW_LABEL, Initialize the label to a valid empty
 *				Sensitivity Label structure.
 *			NO_CORRECTION, Initialize the label to a valid
 *				empty Sensitivity Label structure.
 *				Prohibit correction to the Sensitivity Label.
 *			Other, pass existing Sensitivity Label through for
 *				modification.
 *
 *	Exit	label = Translated (updated) Binary Sensitivity Label.
 *		error = If error reported, the error indicator,
 *				-1, Unable to access label encodings file;
 *				 0, Invalid binary label passed;
 *				>0, Position after the first character in
 *				    string of error, 1 indicates entire string.
 *			Otherwise, unchanged.
 *
 *	Returns	0, If error.
 *		1, If successful.
 *
 *	Calls	__call_labeld(STOBSL), ISHEX, htobsl, strlen,
 *			isspace,
 *			strncasecmp.
 *
 *	Uses	ADMIN_HIGH, ADMIN_LOW.
 */

int
stobsl(const char *string, bslabel_t *label, int flags, int *error)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(stobsl_call_t, strlen(string) + 1);
	int	rval;
	char	*s = (char *)string;

	while (isspace(*s))
		s++;
	/* accept a leading '[' */
	if (*s == '[') {
		s++;
		while (isspace(*s))
			s++;
	}
	if (ISHEX(flags, s)) {
		if (htobsl(s, label)) {
			return (1);
		} else {
			if (error != NULL)
				*error = 1;
			return (0);
		}
	}

	if (datasize > bufsize) {
		if ((callp = malloc(datasize)) == NULL) {
			if (error != NULL)
				*error = -1;
			return (0);
		}
		bufsize = datasize;
	}
	callp->callop = STOBSL;
	slcall.flags  = (flags&NEW_LABEL) ? LABELS_NEW_LABEL : 0;
	slcall.flags |= (flags&NO_CORRECTION) ? LABELS_FULL_PARSE : 0;
	slcall.label = *label;
	(void) strcpy(slcall.string, string);

	if ((rval = __call_labeld(&callp, &bufsize, &datasize)) == SUCCESS) {
		int err = callp->reterr;

		if (callp != &call) {
			/* free allocated buffer */
			free(callp);
		}
		/*
		 * reterr == 0, OK,
		 * reterr < 0, invalid binary label,
		 * reterr > 0 error position, 1 == whole string
		 */
		if (err == 0) {
			*label = slret.label;
			return (1);
		} else if (err < 0) {
			err = 0;
		}
		if (error != NULL)
			*error = err;
		return (0);
	} else if (rval == NOSERVER) {
		if (callp != &call) {
			/* free allocated buffer */
			free(callp);
		}
		/* server not present */
		/* special case Admin High and Admin Low */
		if (IS_ADMIN_LOW(s)) {
			BSLLOW(label);
		} else if (IS_ADMIN_HIGH(s)) {
			BSLHIGH(label);
		} else {
			goto err1;
		}
		return (1);
	}
	if (callp != &call) {
		/* free allocated buffer */
		free(callp);
	}
err1:
	if (error != NULL)
		*error = -1;
	return (0);
}  /* stobsl */
#undef	slcall
#undef	slret

#define	clrcall callp->param.acall.cargs.stobclear_arg
#define	clrret callp->param.aret.rvals.stobclear_ret
/*
 *	stobclear - Translate Clearance string to a Binary Clearance.
 *
 *	Entry	string = Clearance string to be translated.
 *		clearance = Address of Binary Clearance to be initialized or
 *			updated.
 *		flags = Flags to control translation:
 *			NO_CORRECTION implies NEW_LABEL.
 *			NEW_LABEL, Initialize the label to a valid empty
 *				Sensitivity Label structure.
 *			NO_CORRECTION, Initialize the label to a valid
 *				empty Sensitivity Label structure.
 *				Prohibit correction to the Sensitivity Label.
 *			Other, pass existing Sensitivity Label through for
 *				modification.
 *
 *	Exit	clearance = Translated (updated) Binary Clearance.
 *		error = If error reported, the error indicator,
 *				-1, Unable to access label encodings file;
 *				 0, Invalid binary label passed;
 *				>0, Position after the first character in
 *				    string of error, 1 indicates entire string.
 *			Otherwise, unchanged.
 *
 *	Returns	0, If error.
 *		1, If successful.
 *
 *	Calls	__call_labeld(STOBCLEAR), ISHEX, htobsl, strlen,
 *			isspace,
 *			strncasecmp.
 *
 *	Uses	ADMIN_HIGH, ADMIN_LOW.
 */

int
stobclear(const char *string, bclear_t *clearance, int flags, int *error)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize = CALL_SIZE(stobclear_call_t, strlen(string) + 1);
	int	rval;

	if (ISHEX(flags, string)) {
		if (htobclear(string, clearance)) {
			return (1);
		} else {
			if (error != NULL)
				*error = 1;
			return (0);
		}
	}

	if (datasize > bufsize) {
		if ((callp = malloc(datasize)) == NULL) {
			if (error != NULL)
				*error = -1;
			return (0);
		}
		bufsize = datasize;
	}
	callp->callop = STOBCLEAR;
	clrcall.flags  = (flags&NEW_LABEL) ? LABELS_NEW_LABEL : 0;
	clrcall.flags |= (flags&NO_CORRECTION) ? LABELS_FULL_PARSE : 0;
	clrcall.clear = *clearance;
	(void) strcpy(clrcall.string, string);

	if ((rval = __call_labeld(&callp, &bufsize, &datasize)) == SUCCESS) {
		int err = callp->reterr;

		if (callp != &call) {
			/* free allocated buffer */
			free(callp);
		}
		/*
		 * reterr == 0, OK,
		 * reterr < 0, invalid binary label,
		 * reterr > 0 error position, 1 == whole string
		 */
		if (err == 0) {
			*clearance = clrret.clear;
			return (1);
		} else if (err < 0) {
			err = 0;
		}
		if (error != NULL)
			*error = err;
		return (0);
	} else if (rval == NOSERVER) {
		char *s = (char *)string;

		if (callp != &call) {
			/* free allocated buffer */
			free(callp);
		}
		/* server not present */
		/* special case Admin High and Admin Low */
		while (isspace(*s))
			s++;
		if (IS_ADMIN_LOW(s)) {
			BCLEARLOW(clearance);
		} else if (IS_ADMIN_HIGH(s)) {
			BCLEARHIGH(clearance);
		} else {
			goto err1;
		}
		return (1);
	}
	if (callp != &call) {
		/* free allocated buffer */
		free(callp);
	}
err1:
	if (error != NULL)
		*error = -1;
	return (0);
}  /* stobclear */
#undef	clrcall
#undef	clrret
/*
 * 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.
 */

#include	<stdlib.h>
#include	<strings.h>
#include	<zone.h>
#include	<errno.h>
#include	<sys/types.h>
#include 	<sys/tsol/label_macro.h>

/*
 * Get label from zone name
 */
m_label_t *
getzonelabelbyname(const char *zone)
{
	zoneid_t	zoneid;

	if ((zoneid = getzoneidbyname(zone)) == -1) {
		errno = EINVAL;
		return (NULL);
	}
	return (getzonelabelbyid(zoneid));
}

/*
 * Get label from zone id
 */
m_label_t *
getzonelabelbyid(zoneid_t zoneid)
{
	m_label_t 	*slabel;

	if ((slabel = m_label_alloc(MAC_LABEL)) == NULL)
		return (NULL);

	if (zone_getattr(zoneid, ZONE_ATTR_SLBL, slabel,
	    sizeof (m_label_t)) < 0) {
		m_label_free(slabel);
		errno = EINVAL;
		return (NULL);
	}

	return (slabel);
}

/*
 * Get zone id from label
 */

zoneid_t
getzoneidbylabel(const m_label_t *label)
{
	m_label_t	admin_low;
	m_label_t	admin_high;
	zoneid_t	zoneid;
	zoneid_t 	*zids;
	uint_t		nzents;
	uint_t		nzents_saved;
	int		i;

	bsllow(&admin_low);
	bslhigh(&admin_high);

	/* Check for admin_low or admin_high; both are global zone */
	if (blequal(label, &admin_low) || blequal(label, &admin_high))
		return (GLOBAL_ZONEID);

	nzents = 0;
	if (zone_list(NULL, &nzents) != 0)
		return (-1);

again:
	if (nzents == 0) {
		errno = EINVAL;
		return (-1);
	}

	/*
	 * Add a small amount of padding here to avoid spinning in a tight loop
	 * if there's a process running somewhere that's creating lots of zones
	 * all at once.
	 */
	nzents += 8;
	if ((zids = malloc(nzents * sizeof (zoneid_t))) == NULL)
		return (-1);
	nzents_saved = nzents;

	if (zone_list(zids, &nzents) != 0) {
		free(zids);
		return (-1);
	}
	if (nzents > nzents_saved) {
		/* list changed, try again */
		free(zids);
		goto again;
	}

	for (i = 0; i < nzents; i++) {
		m_label_t	test_sl;

		if (zids[i] == GLOBAL_ZONEID)
			continue;

		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, &test_sl,
		    sizeof (m_label_t)) < 0)
			continue;	/* Badly configured zone info */

		if (blequal(label, &test_sl) != 0) {
			zoneid = zids[i];
			free(zids);
			return (zoneid);
		}
	}
	free(zids);
	errno = EINVAL;
	return (-1);
}

/*
 * Get zoneroot for a zoneid
 */

char *
getzonerootbyid(zoneid_t zoneid)
{
	char zoneroot[MAXPATHLEN];

	if (zone_getattr(zoneid, ZONE_ATTR_ROOT, zoneroot,
	    sizeof (zoneroot)) == -1) {
		return (NULL);
	}

	return (strdup(zoneroot));
}

/*
 * Get zoneroot for a zonename
 */

char *
getzonerootbyname(const char *zone)
{
	zoneid_t	zoneid;

	if ((zoneid = getzoneidbyname(zone)) == -1)
		return (NULL);
	return (getzonerootbyid(zoneid));
}

/*
 * Get zoneroot for a label
 */

char *
getzonerootbylabel(const m_label_t *label)
{
	zoneid_t	zoneid;

	if ((zoneid = getzoneidbylabel(label)) == -1)
		return (NULL);
	return (getzonerootbyid(zoneid));
}

/*
 * Get label of path relative to global zone
 *
 * This function must be called from the global zone
 */

m_label_t *
getlabelbypath(const char *path)
{
	m_label_t	*slabel;
	zoneid_t 	*zids;
	uint_t		nzents;
	uint_t		nzents_saved;
	int		i;

	if (getzoneid() != GLOBAL_ZONEID) {
		errno = EINVAL;
		return (NULL);
	}

	nzents = 0;
	if (zone_list(NULL, &nzents) != 0)
		return (NULL);

again:
	/* Add a small amount of padding to avoid loops */
	nzents += 8;
	zids = malloc(nzents * sizeof (zoneid_t));
	if (zids == NULL)
		return (NULL);

	nzents_saved = nzents;

	if (zone_list(zids, &nzents) != 0) {
		free(zids);
		return (NULL);
	}
	if (nzents > nzents_saved) {
		/* list changed, try again */
		free(zids);
		goto again;
	}

	slabel = m_label_alloc(MAC_LABEL);
	if (slabel == NULL) {
		free(zids);
		return (NULL);
	}

	for (i = 0; i < nzents; i++) {
		char	zoneroot[MAXPATHLEN];
		int	zonerootlen;

		if (zids[i] == GLOBAL_ZONEID)
			continue;

		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zoneroot,
		    sizeof (zoneroot)) == -1)
			continue;	/* Badly configured zone info */

		/*
		 * Need to handle the case for the /dev directory which is
		 * parallel to the zone's root directory.  So we back up
		 * 4 bytes - the strlen of "root".
		 */
		if ((zonerootlen = strlen(zoneroot)) <= 4)
			continue;	/* Badly configured zone info */
		if (strncmp(path, zoneroot, zonerootlen - 4) == 0) {
			/*
			 * If we get a match, the file is in a labeled zone.
			 * Return the label of that zone.
			 */
			if (zone_getattr(zids[i], ZONE_ATTR_SLBL, slabel,
			    sizeof (m_label_t)) < 0)
				continue;	/* Badly configured zone info */

			free(zids);
			return (slabel);
		}
	}
	free(zids);
	bsllow(slabel);
	return (slabel);
}