|
root / base / usr / src / cmd / lofiadm / main.c
main.c C 2183 lines 55.9 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
/*
 * 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 2012 Joyent, Inc.  All rights reserved.
 *
 * Copyright 2013 Nexenta Systems, Inc. All rights reserved.
 * Copyright (c) 2014 Gary Mills
 * Copyright (c) 2016 Andrey Sokolov
 */

/*
 * lofiadm - administer lofi(4D). Very simple, add and remove file<->device
 * associations, and display status. All the ioctls are private between
 * lofi and lofiadm, and so are very simple - device information is
 * communicated via a minor number.
 */

#include <sys/types.h>
#include <sys/param.h>
#include <sys/lofi.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/modctl.h>
#include <netinet/in.h>
#include <stdio.h>
#include <fcntl.h>
#include <locale.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <stropts.h>
#include <libdevinfo.h>
#include <libgen.h>
#include <ctype.h>
#include <dlfcn.h>
#include <limits.h>
#include <security/cryptoki.h>
#include <cryptoutil.h>
#include <sys/crypto/ioctl.h>
#include <sys/crypto/ioctladmin.h>
#include <sys/cmlb.h>
#include <sys/mkdev.h>
#include "utils.h"
#include <LzmaEnc.h>

/* Only need the IV len #defines out of these files, nothing else. */
#include <aes/aes_impl.h>
#include <des/des_impl.h>
#include <blowfish/blowfish_impl.h>

static const char USAGE[] =
	"Usage: %s [-r] [-l] -a file [ device ]\n"
	"       %s [-r] -c crypto_algorithm -a file [device]\n"
	"       %s [-r] -c crypto_algorithm -k raw_key_file -a file [device]\n"
	"       %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
	"-a file [device]\n"
	"       %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
	"-k wrapped_key_file -a file [device]\n"
	"       %s [-r] -c crypto_algorithm -e -a file [device]\n"
	"       %s -d file | device\n"
	"       %s -C [gzip|gzip-6|gzip-9|lzma] [-s segment_size] file\n"
	"       %s -U file\n"
	"       %s [ file | device ]\n";

typedef struct token_spec {
	char	*name;
	char	*mfr;
	char	*serno;
	char	*key;
} token_spec_t;

typedef struct mech_alias {
	char	*alias;
	CK_MECHANISM_TYPE type;
	char	*name;		/* for ioctl */
	char	*iv_name;	/* for ioctl */
	size_t	iv_len;		/* for ioctl */
	iv_method_t iv_type;	/* for ioctl */
	size_t	min_keysize;	/* in bytes */
	size_t	max_keysize;	/* in bytes */
	token_spec_t *token;
	CK_SLOT_ID slot;
} mech_alias_t;

static mech_alias_t mech_aliases[] = {
	/* Preferred one should always be listed first. */
	{ "aes-256-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
	    IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
	{ "aes-192-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
	    IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
	{ "aes-128-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
	    IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
	{ "des3-cbc", CKM_DES3_CBC, "CKM_DES3_CBC", "CKM_DES3_ECB", DES_IV_LEN,
	    IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 },
	{ "blowfish-cbc", CKM_BLOWFISH_CBC, "CKM_BLOWFISH_CBC",
	    "CKM_BLOWFISH_ECB", BLOWFISH_IV_LEN, IVM_ENC_BLKNO, ULONG_MAX,
	    0L, NULL, (CK_SLOT_ID)-1 }
	/*
	 * A cipher without an iv requirement would look like this:
	 * { "aes-xex", CKM_AES_XEX, "CKM_AES_XEX", NULL, 0,
	 *    IVM_NONE, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 }
	 */
};

int	mech_aliases_count = (sizeof (mech_aliases) / sizeof (mech_alias_t));

/* Preferred cipher, if one isn't specified on command line. */
#define	DEFAULT_CIPHER	(&mech_aliases[0])

#define	DEFAULT_CIPHER_NUM	64	/* guess # kernel ciphers available */
#define	DEFAULT_MECHINFO_NUM	16	/* guess # kernel mechs available */
#define	MIN_PASSLEN		8	/* min acceptable passphrase size */

static int gzip_compress(void *src, size_t srclen, void *dst,
	size_t *destlen, int level);
static int lzma_compress(void *src, size_t srclen, void *dst,
	size_t *destlen, int level);

lofi_compress_info_t lofi_compress_table[LOFI_COMPRESS_FUNCTIONS] = {
	{NULL,  		gzip_compress,  6,	"gzip"}, /* default */
	{NULL,			gzip_compress,	6,	"gzip-6"},
	{NULL,			gzip_compress,	9, 	"gzip-9"},
	{NULL,  		lzma_compress, 	0, 	"lzma"}
};

/* For displaying lofi mappings */
#define	FORMAT 			"%-20s     %-30s	%s\n"

#define	COMPRESS_ALGORITHM	"gzip"
#define	COMPRESS_THRESHOLD	2048
#define	SEGSIZE			131072
#define	BLOCK_SIZE		512
#define	KILOBYTE		1024
#define	MEGABYTE		(KILOBYTE * KILOBYTE)
#define	GIGABYTE		(KILOBYTE * MEGABYTE)
#define	LIBZ			"libz.so.1"

const char lofi_crypto_magic[6] = LOFI_CRYPTO_MAGIC;

static void
usage(const char *pname)
{
	(void) fprintf(stderr, gettext(USAGE), pname, pname, pname,
	    pname, pname, pname, pname, pname, pname, pname);
	exit(E_USAGE);
}

static int
gzip_compress(void *src, size_t srclen, void *dst, size_t *dstlen, int level)
{
	static int (*compress2p)(void *, ulong_t *, void *, size_t, int) = NULL;
	void *libz_hdl = NULL;

	/*
	 * The first time we are called, attempt to dlopen()
	 * libz.so.1 and get a pointer to the compress2() function
	 */
	if (compress2p == NULL) {
		if ((libz_hdl = openlib(LIBZ)) == NULL)
			die(gettext("could not find %s. "
			    "gzip compression unavailable\n"), LIBZ);

		if ((compress2p =
		    (int (*)(void *, ulong_t *, void *, size_t, int))
		    dlsym(libz_hdl, "compress2")) == NULL) {
			closelib();
			die(gettext("could not find the correct %s. "
			    "gzip compression unavailable\n"), LIBZ);
		}
	}

	if ((*compress2p)(dst, (ulong_t *)dstlen, src, srclen, level) != 0)
		return (-1);
	return (0);
}

/*ARGSUSED*/
static void
*SzAlloc(void *p, size_t size)
{
	return (malloc(size));
}

/*ARGSUSED*/
static void
SzFree(void *p, void *address, size_t size)
{
	free(address);
}

static ISzAlloc g_Alloc = {
	SzAlloc,
	SzFree
};

#define	LZMA_UNCOMPRESSED_SIZE	8
#define	LZMA_HEADER_SIZE (LZMA_PROPS_SIZE + LZMA_UNCOMPRESSED_SIZE)

/*ARGSUSED*/
static int
lzma_compress(void *src, size_t srclen, void *dst,
    size_t *dstlen, int level)
{
	CLzmaEncProps props;
	size_t outsize2;
	size_t outsizeprocessed;
	size_t outpropssize = LZMA_PROPS_SIZE;
	uint64_t t = 0;
	SRes res;
	Byte *dstp;
	int i;

	outsize2 = *dstlen;

	LzmaEncProps_Init(&props);

	/*
	 * The LZMA compressed file format is as follows -
	 *
	 * Offset Size(bytes) Description
	 * 0		1	LZMA properties (lc, lp, lp (encoded))
	 * 1		4	Dictionary size (little endian)
	 * 5		8	Uncompressed size (little endian)
	 * 13			Compressed data
	 */

	/* set the dictionary size to be 8MB */
	props.dictSize = 1 << 23;

	if (*dstlen < LZMA_HEADER_SIZE)
		return (SZ_ERROR_OUTPUT_EOF);

	dstp = (Byte *)dst;
	t = srclen;
	/*
	 * Set the uncompressed size in the LZMA header
	 * The LZMA properties (specified in 'props')
	 * will be set by the call to LzmaEncode()
	 */
	for (i = 0; i < LZMA_UNCOMPRESSED_SIZE; i++, t >>= 8) {
		dstp[LZMA_PROPS_SIZE + i] = (Byte)t;
	}

	outsizeprocessed = outsize2 - LZMA_HEADER_SIZE;
	res = LzmaEncode(dstp + LZMA_HEADER_SIZE, &outsizeprocessed,
	    src, srclen, &props, dstp, &outpropssize, 0, NULL,
	    &g_Alloc, &g_Alloc);

	if (res != 0)
		return (-1);

	*dstlen = outsizeprocessed + LZMA_HEADER_SIZE;
	return (0);
}

/*
 * Translate a lofi device name to a minor number. We might be asked
 * to do this when there is no association (such as when the user specifies
 * a particular device), so we can only look at the string.
 */
static int
name_to_minor(const char *devicename)
{
	struct stat st;

	/*
	 * If devicename does not exist, then devicename contains
	 * the name of the device to be created.
	 * Note we only allow non-labeled devices here.
	 */
	if (stat(devicename, &st)) {
		int minor, rv;

		rv = sscanf(devicename, "/dev/" LOFI_BLOCK_NAME "/%d", &minor);
		if (rv == 1)
			return (minor);
		rv = sscanf(devicename, "/dev/" LOFI_CHAR_NAME "/%d", &minor);
		if (rv == 1)
			return (minor);

		return (0);
	}

	/*
	 * For disk devices we use modctl(MODGETNAME) to read driver name
	 * for major device.
	 */
	if (st.st_mode & S_IFCHR || st.st_mode & S_IFBLK) {
		major_t maj;
		char mname[MODMAXNAMELEN];

		maj = major(st.st_rdev);

		if (modctl(MODGETNAME, mname,  MODMAXNAMELEN, &maj) == 0) {
			if (strncmp(mname, LOFI_DRIVER_NAME,
			    sizeof (LOFI_DRIVER_NAME)) == 0) {
				return (LOFI_MINOR2ID(minor(st.st_rdev)));
			}
		}
	}

	return (0);
}

/*
 * This might be the first time we've used this minor number. If so,
 * it might also be that the /dev links are in the process of being created
 * by devfsadmd (or that they'll be created "soon"). We cannot return
 * until they're there or the invoker of lofiadm might try to use them
 * and not find them. This can happen if a shell script is running on
 * an MP.
 */
static int sleeptime = 2;	/* number of seconds to sleep between stat's */
static int maxsleep = 120;	/* maximum number of seconds to sleep */

static void
make_blkdevname(struct lofi_ioctl *li, char *path, size_t len)
{
	char *r1, *r2;
	size_t l1;

	if (li->li_devpath[0] == '\0') {
		if (li->li_labeled)
			(void) strlcpy(path, "unknown", len);
		else
			(void) snprintf(path, len,
			    "/dev/" LOFI_BLOCK_NAME "/%d", li->li_id);
		return;
	}
	(void) strlcpy(path, li->li_devpath, len);
	r1 = strchr(path, 'r');
	l1 = r1 - path;
	r2 = strchr(li->li_devpath, 'r');
	(void) strlcpy(r1, r2+1, len - l1);

	if (li->li_labeled) {
		(void) strlcat(path, "p0", len);
	}
}

static void
wait_until_dev_complete(struct lofi_ioctl *li)
{
	struct stat64 buf;
	int	cursleep;
	char	blkpath[MAXPATHLEN];
	char	charpath[MAXPATHLEN];
	di_devlink_handle_t hdl;

	make_blkdevname(li, blkpath, sizeof (blkpath));
	(void) strlcpy(charpath, li->li_devpath, sizeof (charpath));

	if (li->li_labeled) {
		(void) strlcat(charpath, "p0", sizeof (charpath));
	}

	/* Check if links already present */
	if (stat64(blkpath, &buf) == 0 && stat64(charpath, &buf) == 0)
		return;

	/* First use di_devlink_init() */
	if (hdl = di_devlink_init("lofi", DI_MAKE_LINK)) {
		(void) di_devlink_fini(&hdl);
		goto out;
	}

	/*
	 * Under normal conditions, di_devlink_init(DI_MAKE_LINK) above will
	 * only fail if the caller is non-root. In that case, wait for
	 * link creation via sysevents.
	 */
	for (cursleep = 0; cursleep < maxsleep; cursleep += sleeptime) {
		if (stat64(blkpath, &buf) == 0 && stat64(charpath, &buf) == 0)
			return;
		(void) sleep(sleeptime);
	}

	/* one last try */
out:
	if (stat64(blkpath, &buf) == -1) {
		die(gettext("%s was not created"), blkpath);
	}
	if (stat64(charpath, &buf) == -1) {
		die(gettext("%s was not created"), charpath);
	}
}

/*
 * Map the file and return the minor number the driver picked for the file
 * DO NOT use this function if the filename is actually the device name.
 */
static int
lofi_map_file(int lfd, struct lofi_ioctl *li, const char *filename)
{
	int	minor;

	li->li_id = 0;
	(void) strlcpy(li->li_filename, filename, sizeof (li->li_filename));
	minor = ioctl(lfd, LOFI_MAP_FILE, li);
	if (minor == -1) {
		if (errno == ENOTSUP)
			warn(gettext("encrypting compressed files is "
			    "unsupported"));
		die(gettext("could not map file %s"), filename);
	}
	wait_until_dev_complete(li);
	return (minor);
}

/*
 * Add a device association. If devicename is NULL, let the driver
 * pick a device.
 */
static void
add_mapping(int lfd, const char *devicename, const char *filename,
    mech_alias_t *cipher, const char *rkey, size_t rksz, boolean_t rdonly,
    boolean_t label)
{
	struct lofi_ioctl li;

	bzero(&li, sizeof (li));
	li.li_readonly = rdonly;
	li.li_labeled = label;

	li.li_crypto_enabled = B_FALSE;
	if (cipher != NULL) {
		/* set up encryption for mapped file */
		li.li_crypto_enabled = B_TRUE;
		(void) strlcpy(li.li_cipher, cipher->name,
		    sizeof (li.li_cipher));
		if (rksz > sizeof (li.li_key)) {
			die(gettext("key too large"));
		}
		bcopy(rkey, li.li_key, rksz);
		li.li_key_len = rksz << 3;	/* convert to bits */

		li.li_iv_type = cipher->iv_type;
		li.li_iv_len = cipher->iv_len;	/* 0 when no iv needed */
		switch (cipher->iv_type) {
		case IVM_ENC_BLKNO:
			(void) strlcpy(li.li_iv_cipher, cipher->iv_name,
			    sizeof (li.li_iv_cipher));
			break;
		case IVM_NONE:
			/* FALLTHROUGH */
		default:
			break;
		}
	}

	if (devicename == NULL) {
		int	minor;
		char	path[MAXPATHLEN];

		/* pick one via the driver */
		minor = lofi_map_file(lfd, &li, filename);
		if (minor > 0) {
			make_blkdevname(&li, path, sizeof (path));

			/* if mapping succeeds, print the one picked */
			(void) printf("%s\n", path);
		}
		return;
	}

	/* use device we were given */
	li.li_id = name_to_minor(devicename);
	if (li.li_id == 0) {
		die(gettext("malformed device name %s\n"), devicename);
	}
	(void) strlcpy(li.li_filename, filename, sizeof (li.li_filename));

	/* if device is already in use li.li_minor won't change */
	if (ioctl(lfd, LOFI_MAP_FILE_MINOR, &li) == -1) {
		if (errno == ENOTSUP)
			warn(gettext("encrypting compressed files is "
			    "unsupported"));
		die(gettext("could not map file %s to %s"), filename,
		    devicename);
	}
	wait_until_dev_complete(&li);
}

/*
 * Remove an association. Delete by device name if non-NULL, or by
 * filename otherwise.
 */
static void
delete_mapping(int lfd, const char *devicename, const char *filename,
    boolean_t force)
{
	struct lofi_ioctl li;

	li.li_force = force;
	li.li_cleanup = B_FALSE;

	if (devicename == NULL) {
		/* delete by filename */
		(void) strlcpy(li.li_filename, filename,
		    sizeof (li.li_filename));
		li.li_id = 0;
		if (ioctl(lfd, LOFI_UNMAP_FILE, &li) == -1) {
			die(gettext("could not unmap file %s"), filename);
		}
		return;
	}

	/* delete by device */
	li.li_id = name_to_minor(devicename);
	if (li.li_id == 0) {
		die(gettext("malformed device name %s\n"), devicename);
	}
	if (ioctl(lfd, LOFI_UNMAP_FILE_MINOR, &li) == -1) {
		die(gettext("could not unmap device %s"), devicename);
	}
}

/*
 * Show filename given devicename, or devicename given filename.
 */
static void
print_one_mapping(int lfd, const char *devicename, const char *filename)
{
	struct lofi_ioctl li;
	char blkpath[MAXPATHLEN];

	if (devicename == NULL) {
		/* given filename, print devicename */
		li.li_id = 0;
		(void) strlcpy(li.li_filename, filename,
		    sizeof (li.li_filename));
		if (ioctl(lfd, LOFI_GET_MINOR, &li) == -1) {
			die(gettext("could not find device for %s"), filename);
		}
		make_blkdevname(&li, blkpath, sizeof (blkpath));
		(void) printf("%s\n", blkpath);
		return;
	}

	/* given devicename, print filename */
	li.li_id = name_to_minor(devicename);
	if (li.li_id == 0) {
		die(gettext("malformed device name %s\n"), devicename);
	}
	if (ioctl(lfd, LOFI_GET_FILENAME, &li) == -1) {
		die(gettext("could not find filename for %s"), devicename);
	}
	(void) printf("%s\n", li.li_filename);
}

/*
 * Print the list of all the mappings, including a header.
 */
static void
print_mappings(int fd)
{
	struct lofi_ioctl li;
	int	minor;
	int	maxminor;
	char	path[MAXPATHLEN];
	char	options[MAXPATHLEN] = { 0 };

	li.li_id = 0;
	if (ioctl(fd, LOFI_GET_MAXMINOR, &li) == -1) {
		die("ioctl");
	}
	maxminor = li.li_id;

	(void) printf(FORMAT, gettext("Block Device"), gettext("File"),
	    gettext("Options"));
	for (minor = 1; minor <= maxminor; minor++) {
		li.li_id = minor;
		if (ioctl(fd, LOFI_GET_FILENAME, &li) == -1) {
			if (errno == ENXIO)
				continue;
			warn("ioctl");
			break;
		}
		make_blkdevname(&li, path, sizeof (path));

		options[0] = '\0';

		/*
		 * Encrypted lofi and compressed lofi are mutually exclusive.
		 */
		if (li.li_crypto_enabled)
			(void) snprintf(options, sizeof (options),
			    gettext("Encrypted"));
		else if (li.li_algorithm[0] != '\0')
			(void) snprintf(options, sizeof (options),
			    gettext("Compressed(%s)"), li.li_algorithm);
		if (li.li_readonly) {
			if (strlen(options) != 0) {
				(void) strlcat(options, ",Readonly",
				    sizeof (options));
			} else {
				(void) snprintf(options, sizeof (options),
				    gettext("Readonly"));
			}
		}
		if (li.li_labeled) {
			if (strlen(options) != 0) {
				(void) strlcat(options, ",Labeled",
				    sizeof (options));
			} else {
				(void) snprintf(options, sizeof (options),
				    gettext("Labeled"));
			}
		}
		if (strlen(options) == 0)
			(void) snprintf(options, sizeof (options), "-");

		(void) printf(FORMAT, path, li.li_filename, options);
	}
}

/*
 * Verify the cipher selected by user.
 */
static mech_alias_t *
ciph2mech(const char *alias)
{
	int	i;

	for (i = 0; i < mech_aliases_count; i++) {
		if (strcasecmp(alias, mech_aliases[i].alias) == 0)
			return (&mech_aliases[i]);
	}
	return (NULL);
}

/*
 * Verify user selected cipher is also available in kernel.
 *
 * While traversing kernel list of mechs, if the cipher is supported in the
 * kernel for both encryption and decryption, it also picks up the min/max
 * key size.
 */
static boolean_t
kernel_cipher_check(mech_alias_t *cipher)
{
	boolean_t ciph_ok = B_FALSE;
	boolean_t iv_ok = B_FALSE;
	int	i;
	int	count;
	crypto_get_mechanism_list_t *kciphers = NULL;
	crypto_get_all_mechanism_info_t *kinfo = NULL;
	int	fd = -1;
	size_t	keymin;
	size_t	keymax;

	/* if cipher doesn't need iv generating mech, bypass that check now */
	if (cipher->iv_name == NULL)
		iv_ok = B_TRUE;

	/* allocate some space for the list of kernel ciphers */
	count = DEFAULT_CIPHER_NUM;
	kciphers = malloc(sizeof (crypto_get_mechanism_list_t) +
	    sizeof (crypto_mech_name_t) * (count - 1));
	if (kciphers == NULL)
		die(gettext("failed to allocate memory for list of "
		    "kernel mechanisms"));
	kciphers->ml_count = count;

	/* query crypto device to get list of kernel ciphers */
	if ((fd = open("/dev/crypto", O_RDWR)) == -1) {
		warn(gettext("failed to open %s"), "/dev/crypto");
		goto kcc_out;
	}

	if (ioctl(fd, CRYPTO_GET_MECHANISM_LIST, kciphers) == -1) {
		warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
		goto kcc_out;
	}

	if (kciphers->ml_return_value == CRYPTO_BUFFER_TOO_SMALL) {
		count = kciphers->ml_count;
		free(kciphers);
		kciphers = malloc(sizeof (crypto_get_mechanism_list_t) +
		    sizeof (crypto_mech_name_t) * (count - 1));
		if (kciphers == NULL) {
			warn(gettext("failed to allocate memory for list of "
			    "kernel mechanisms"));
			goto kcc_out;
		}
		kciphers->ml_count = count;

		if (ioctl(fd, CRYPTO_GET_MECHANISM_LIST, kciphers) == -1) {
			warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
			goto kcc_out;
		}
	}

	if (kciphers->ml_return_value != CRYPTO_SUCCESS) {
		warn(gettext(
		    "CRYPTO_GET_MECHANISM_LIST ioctl return value = %d\n"),
		    kciphers->ml_return_value);
		goto kcc_out;
	}

	/*
	 * scan list of kernel ciphers looking for the selected one and if
	 * it needs an iv generated using another cipher, also look for that
	 * additional cipher to be used for generating the iv
	 */
	count = kciphers->ml_count;
	for (i = 0; i < count && !(ciph_ok && iv_ok); i++) {
		if (!ciph_ok &&
		    strcasecmp(cipher->name, kciphers->ml_list[i]) == 0)
			ciph_ok = B_TRUE;
		if (!iv_ok &&
		    strcasecmp(cipher->iv_name, kciphers->ml_list[i]) == 0)
			iv_ok = B_TRUE;
	}
	free(kciphers);
	kciphers = NULL;

	if (!ciph_ok)
		warn(gettext("%s mechanism not supported in kernel\n"),
		    cipher->name);
	if (!iv_ok)
		warn(gettext("%s mechanism not supported in kernel\n"),
		    cipher->iv_name);

	if (ciph_ok) {
		/* Get the details about the user selected cipher */
		count = DEFAULT_MECHINFO_NUM;
		kinfo = malloc(sizeof (crypto_get_all_mechanism_info_t) +
		    sizeof (crypto_mechanism_info_t) * (count - 1));
		if (kinfo == NULL) {
			warn(gettext("failed to allocate memory for "
			    "kernel mechanism info"));
			goto kcc_out;
		}
		kinfo->mi_count = count;
		(void) strlcpy(kinfo->mi_mechanism_name, cipher->name,
		    CRYPTO_MAX_MECH_NAME);

		if (ioctl(fd, CRYPTO_GET_ALL_MECHANISM_INFO, kinfo) == -1) {
			warn(gettext(
			    "CRYPTO_GET_ALL_MECHANISM_INFO ioctl failed"));
			goto kcc_out;
		}

		if (kinfo->mi_return_value == CRYPTO_BUFFER_TOO_SMALL) {
			count = kinfo->mi_count;
			free(kinfo);
			kinfo = malloc(
			    sizeof (crypto_get_all_mechanism_info_t) +
			    sizeof (crypto_mechanism_info_t) * (count - 1));
			if (kinfo == NULL) {
				warn(gettext("failed to allocate memory for "
				    "kernel mechanism info"));
				goto kcc_out;
			}
			kinfo->mi_count = count;
			(void) strlcpy(kinfo->mi_mechanism_name, cipher->name,
			    CRYPTO_MAX_MECH_NAME);

			if (ioctl(fd, CRYPTO_GET_ALL_MECHANISM_INFO, kinfo) ==
			    -1) {
				warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO "
				    "ioctl failed"));
				goto kcc_out;
			}
		}

		if (kinfo->mi_return_value != CRYPTO_SUCCESS) {
			warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO ioctl "
			    "return value = %d\n"), kinfo->mi_return_value);
			goto kcc_out;
		}

		/* Set key min and max size */
		count = kinfo->mi_count;
		i = 0;
		if (i < count) {
			keymin = kinfo->mi_list[i].mi_min_key_size;
			keymax = kinfo->mi_list[i].mi_max_key_size;
			if (kinfo->mi_list[i].mi_keysize_unit &
			    CRYPTO_KEYSIZE_UNIT_IN_BITS) {
				keymin = CRYPTO_BITS2BYTES(keymin);
				keymax = CRYPTO_BITS2BYTES(keymax);

			}
			cipher->min_keysize = keymin;
			cipher->max_keysize = keymax;
		}
		free(kinfo);
		kinfo = NULL;

		if (i == count) {
			(void) close(fd);
			die(gettext(
			    "failed to find usable %s kernel mechanism, "
			    "use \"cryptoadm list -m\" to find available "
			    "mechanisms\n"),
			    cipher->name);
		}
	}

	/* Note: key min/max, unit size, usage for iv cipher are not checked. */

	return (ciph_ok && iv_ok);

kcc_out:
	if (kinfo != NULL)
		free(kinfo);
	if (kciphers != NULL)
		free(kciphers);
	if (fd != -1)
		(void) close(fd);
	return (B_FALSE);
}

/*
 * Break up token spec into its components (non-destructive)
 */
static token_spec_t *
parsetoken(char *spec)
{
#define	FLD_NAME	0
#define	FLD_MANUF	1
#define	FLD_SERIAL	2
#define	FLD_LABEL	3
#define	NFIELDS		4
#define	nullfield(i)	((field[(i)+1] - field[(i)]) <= 1)
#define	copyfield(fld, i)	\
		{							\
			int	n;					\
			(fld) = NULL;					\
			if ((n = (field[(i)+1] - field[(i)])) > 1) {	\
				if (((fld) = malloc(n)) != NULL) {	\
					(void) strncpy((fld), field[(i)], n); \
					((fld))[n - 1] = '\0';		\
				}					\
			}						\
		}

	int	i;
	char	*field[NFIELDS + 1];	/* +1 to catch extra delimiters */
	token_spec_t *ti = NULL;

	if (spec == NULL)
		return (NULL);

	/*
	 * Correct format is "[name]:[manuf]:[serial]:key". Can't use
	 * strtok because it treats ":::key" and "key:::" and "key" all
	 * as the same thing, and we can't have the :s compressed away.
	 */
	field[0] = spec;
	for (i = 1; i < NFIELDS + 1; i++) {
		field[i] = strchr(field[i-1], ':');
		if (field[i] == NULL)
			break;
		field[i]++;
	}
	if (i < NFIELDS)		/* not enough fields */
		return (NULL);
	if (field[NFIELDS] != NULL)	/* too many fields */
		return (NULL);
	field[NFIELDS] = strchr(field[NFIELDS-1], '\0') + 1;

	/* key label can't be empty */
	if (nullfield(FLD_LABEL))
		return (NULL);

	ti = malloc(sizeof (token_spec_t));
	if (ti == NULL)
		return (NULL);

	copyfield(ti->name, FLD_NAME);
	copyfield(ti->mfr, FLD_MANUF);
	copyfield(ti->serno, FLD_SERIAL);
	copyfield(ti->key, FLD_LABEL);

	/*
	 * If token specified and it only contains a key label, then
	 * search all tokens for the key, otherwise only those with
	 * matching name, mfr, and serno are used.
	 */
	/*
	 * That's how we'd like it to be, however, if only the key label
	 * is specified, default to using softtoken.  It's easier.
	 */
	if (ti->name == NULL && ti->mfr == NULL && ti->serno == NULL)
		ti->name = strdup(pkcs11_default_token());
	return (ti);
}

/*
 * PBE the passphrase into a raw key
 */
static void
getkeyfromuser(mech_alias_t *cipher, char **raw_key, size_t *raw_key_sz,
    boolean_t with_confirmation)
{
	CK_SESSION_HANDLE sess;
	CK_RV	rv;
	char	*pass = NULL;
	size_t	passlen = 0;
	void	*salt = NULL;	/* don't use NULL, see note on salt below */
	size_t	saltlen = 0;
	CK_KEY_TYPE ktype;
	void	*kvalue;
	size_t	klen;

	/* did init_crypto find a slot that supports this cipher? */
	if (cipher->slot == (CK_SLOT_ID)-1 || cipher->max_keysize == 0) {
		rv = CKR_MECHANISM_INVALID;
		goto cleanup;
	}

	rv = pkcs11_mech2keytype(cipher->type, &ktype);
	if (rv != CKR_OK)
		goto cleanup;

	/*
	 * use the passphrase to generate a PBE PKCS#5 secret key and
	 * retrieve the raw key data to eventually pass it to the kernel;
	 */
	rv = C_OpenSession(cipher->slot, CKF_SERIAL_SESSION, NULL, NULL, &sess);
	if (rv != CKR_OK)
		goto cleanup;

	/* get user passphrase with 8 byte minimum */
	if (pkcs11_get_pass(NULL, &pass, &passlen, MIN_PASSLEN,
	    with_confirmation) < 0) {
		die(gettext("passphrases do not match\n"));
	}

	/*
	 * salt should not be NULL, or else pkcs11_PasswdToKey() will
	 * complain about CKR_MECHANISM_PARAM_INVALID; the following is
	 * to make up for not having a salt until a proper one is used
	 */
	salt = pass;
	saltlen = passlen;

	klen = cipher->max_keysize;
	rv = pkcs11_PasswdToKey(sess, pass, passlen, salt, saltlen, ktype,
	    cipher->max_keysize, &kvalue, &klen);

	(void) C_CloseSession(sess);

	if (rv != CKR_OK) {
		goto cleanup;
	}

	/* assert(klen == cipher->max_keysize); */
	*raw_key_sz = klen;
	*raw_key = (char *)kvalue;
	return;

cleanup:
	die(gettext("failed to generate %s key from passphrase: %s"),
	    cipher->alias, pkcs11_strerror(rv));
}

/*
 * Read raw key from file; also handles ephemeral keys.
 */
void
getkeyfromfile(const char *pathname, mech_alias_t *cipher, char **key,
    size_t *ksz)
{
	int	fd;
	struct stat sbuf;
	boolean_t notplain = B_FALSE;
	ssize_t	cursz;
	ssize_t	nread;

	/* ephemeral keys are just random data */
	if (pathname == NULL) {
		*ksz = cipher->max_keysize;
		*key = malloc(*ksz);
		if (*key == NULL)
			die(gettext("failed to allocate memory for"
			    " ephemeral key"));
		if (pkcs11_get_urandom(*key, *ksz) < 0) {
			free(*key);
			die(gettext("failed to get enough random data"));
		}
		return;
	}

	/*
	 * If the remaining section of code didn't also check for secure keyfile
	 * permissions and whether the key is within cipher min and max lengths,
	 * (or, if those things moved out of this block), we could have had:
	 *	if (pkcs11_read_data(pathname, key, ksz) < 0)
	 *		handle_error();
	 */

	if ((fd = open(pathname, O_RDONLY, 0)) == -1)
		die(gettext("open of keyfile (%s) failed"), pathname);

	if (fstat(fd, &sbuf) == -1)
		die(gettext("fstat of keyfile (%s) failed"), pathname);

	if (S_ISREG(sbuf.st_mode)) {
		if ((sbuf.st_mode & (S_IWGRP | S_IWOTH)) != 0)
			die(gettext("insecure permissions on keyfile %s\n"),
			    pathname);

		*ksz = sbuf.st_size;
		if (*ksz < cipher->min_keysize || cipher->max_keysize < *ksz) {
			warn(gettext("%s: invalid keysize: %d\n"),
			    pathname, (int)*ksz);
			die(gettext("\t%d <= keysize <= %d\n"),
			    cipher->min_keysize, cipher->max_keysize);
		}
	} else {
		*ksz = cipher->max_keysize;
		notplain = B_TRUE;
	}

	*key = malloc(*ksz);
	if (*key == NULL)
		die(gettext("failed to allocate memory for key from file"));

	for (cursz = 0, nread = 0; cursz < *ksz; cursz += nread) {
		nread = read(fd, *key, *ksz);
		if (nread > 0)
			continue;
		/*
		 * nread == 0.  If it's not a regular file we were trying to
		 * get the maximum keysize of data possible for this cipher.
		 * But if we've got at least the minimum keysize of data,
		 * round down to the nearest keysize unit and call it good.
		 * If we haven't met the minimum keysize, that's an error.
		 * If it's a regular file, nread = 0 is also an error.
		 */
		if (nread == 0 && notplain && cursz >= cipher->min_keysize) {
			*ksz = (cursz / cipher->min_keysize) *
			    cipher->min_keysize;
			break;
		}
		die(gettext("%s: can't read all keybytes"), pathname);
	}
	(void) close(fd);
}

/*
 * Read the raw key from token, or from a file that was wrapped with a
 * key from token
 */
void
getkeyfromtoken(CK_SESSION_HANDLE sess,
    token_spec_t *token, const char *keyfile, mech_alias_t *cipher,
    char **raw_key, size_t *raw_key_sz)
{
	CK_RV	rv = CKR_OK;
	CK_BBOOL trueval = B_TRUE;
	CK_OBJECT_CLASS kclass;		/* secret key or RSA private key */
	CK_KEY_TYPE ktype;		/* from selected cipher or CKK_RSA */
	CK_KEY_TYPE raw_ktype;		/* from selected cipher */
	CK_ATTRIBUTE	key_tmpl[] = {
		{ CKA_CLASS, NULL, 0 },	/* re-used for token key and unwrap */
		{ CKA_KEY_TYPE, NULL, 0 },	/* ditto */
		{ CKA_LABEL, NULL, 0 },
		{ CKA_TOKEN, NULL, 0 },
		{ CKA_PRIVATE, NULL, 0 }
	    };
	CK_ULONG attrs = sizeof (key_tmpl) / sizeof (CK_ATTRIBUTE);
	int	i;
	char	*pass = NULL;
	size_t	passlen = 0;
	CK_OBJECT_HANDLE obj, rawobj;
	CK_ULONG num_objs = 1;		/* just want to find 1 token key */
	CK_MECHANISM unwrap = { CKM_RSA_PKCS, NULL, 0 };
	char	*rkey;
	size_t	rksz;

	if (token == NULL || token->key == NULL)
		return;

	/* did init_crypto find a slot that supports this cipher? */
	if (cipher->slot == (CK_SLOT_ID)-1 || cipher->max_keysize == 0) {
		die(gettext("failed to find any cryptographic provider, "
		    "use \"cryptoadm list -p\" to find providers: %s\n"),
		    pkcs11_strerror(CKR_MECHANISM_INVALID));
	}

	if (pkcs11_get_pass(token->name, &pass, &passlen, 0, B_FALSE) < 0)
		die(gettext("unable to get passphrase"));

	/* use passphrase to login to token */
	if (pass != NULL && passlen > 0) {
		rv = C_Login(sess, CKU_USER, (CK_UTF8CHAR_PTR)pass, passlen);
		if (rv != CKR_OK) {
			die(gettext("cannot login to the token %s: %s\n"),
			    token->name, pkcs11_strerror(rv));
		}
	}

	rv = pkcs11_mech2keytype(cipher->type, &raw_ktype);
	if (rv != CKR_OK) {
		die(gettext("failed to get key type for cipher %s: %s\n"),
		    cipher->name, pkcs11_strerror(rv));
	}

	/*
	 * If no keyfile was given, then the token key is secret key to
	 * be used for encryption/decryption.  Otherwise, the keyfile
	 * contains a wrapped secret key, and the token is actually the
	 * unwrapping RSA private key.
	 */
	if (keyfile == NULL) {
		kclass = CKO_SECRET_KEY;
		ktype = raw_ktype;
	} else {
		kclass = CKO_PRIVATE_KEY;
		ktype = CKK_RSA;
	}

	/* Find the key in the token first */
	for (i = 0; i < attrs; i++) {
		switch (key_tmpl[i].type) {
		case CKA_CLASS:
			key_tmpl[i].pValue = &kclass;
			key_tmpl[i].ulValueLen = sizeof (kclass);
			break;
		case CKA_KEY_TYPE:
			key_tmpl[i].pValue = &ktype;
			key_tmpl[i].ulValueLen = sizeof (ktype);
			break;
		case CKA_LABEL:
			key_tmpl[i].pValue = token->key;
			key_tmpl[i].ulValueLen = strlen(token->key);
			break;
		case CKA_TOKEN:
			key_tmpl[i].pValue = &trueval;
			key_tmpl[i].ulValueLen = sizeof (trueval);
			break;
		case CKA_PRIVATE:
			key_tmpl[i].pValue = &trueval;
			key_tmpl[i].ulValueLen = sizeof (trueval);
			break;
		default:
			break;
		}
	}
	rv = C_FindObjectsInit(sess, key_tmpl, attrs);
	if (rv != CKR_OK)
		die(gettext("cannot find key %s: %s\n"), token->key,
		    pkcs11_strerror(rv));
	rv = C_FindObjects(sess, &obj, 1, &num_objs);
	(void) C_FindObjectsFinal(sess);

	if (num_objs == 0) {
		die(gettext("cannot find key %s\n"), token->key);
	} else if (rv != CKR_OK) {
		die(gettext("cannot find key %s: %s\n"), token->key,
		    pkcs11_strerror(rv));
	}

	/*
	 * No keyfile means when token key is found, convert it to raw key,
	 * and done.  Otherwise still need do an unwrap to create yet another
	 * obj and that needs to be converted to raw key before we're done.
	 */
	if (keyfile == NULL) {
		/* obj contains raw key, extract it */
		rv = pkcs11_ObjectToKey(sess, obj, (void **)&rkey, &rksz,
		    B_FALSE);
		if (rv != CKR_OK) {
			die(gettext("failed to get key value for %s"
			    " from token %s, %s\n"), token->key,
			    token->name, pkcs11_strerror(rv));
		}
	} else {
		getkeyfromfile(keyfile, cipher, &rkey, &rksz);

		/*
		 * Got the wrapping RSA obj and the wrapped key from file.
		 * Unwrap the key from file with RSA obj to get rawkey obj.
		 */

		/* re-use the first two attributes of key_tmpl */
		kclass = CKO_SECRET_KEY;
		ktype = raw_ktype;

		rv = C_UnwrapKey(sess, &unwrap, obj, (CK_BYTE_PTR)rkey,
		    rksz, key_tmpl, 2, &rawobj);
		if (rv != CKR_OK) {
			die(gettext("failed to unwrap key in keyfile %s,"
			    " %s\n"), keyfile, pkcs11_strerror(rv));
		}
		/* rawobj contains raw key, extract it */
		rv = pkcs11_ObjectToKey(sess, rawobj, (void **)&rkey, &rksz,
		    B_TRUE);
		if (rv != CKR_OK) {
			die(gettext("failed to get unwrapped key value for"
			    " key in keyfile %s, %s\n"), keyfile,
			    pkcs11_strerror(rv));
		}
	}

	/* validate raw key size */
	if (rksz < cipher->min_keysize || cipher->max_keysize < rksz) {
		warn(gettext("%s: invalid keysize: %d\n"), keyfile, (int)rksz);
		die(gettext("\t%d <= keysize <= %d\n"), cipher->min_keysize,
		    cipher->max_keysize);
	}

	*raw_key_sz = rksz;
	*raw_key = (char *)rkey;
}

/*
 * Set up cipher key limits and verify PKCS#11 can be done
 * match_token_cipher is the function pointer used by
 * pkcs11_GetCriteriaSession() init_crypto.
 */
boolean_t
match_token_cipher(CK_SLOT_ID slot_id, void *args, CK_RV *rv)
{
	token_spec_t *token;
	mech_alias_t *cipher;
	CK_TOKEN_INFO tokinfo;
	CK_MECHANISM_INFO mechinfo;
	boolean_t token_match;

	/*
	 * While traversing slot list, pick up the following info per slot:
	 * - if token specified, whether it matches this slot's token info
	 * - if the slot supports the PKCS#5 PBKD2 cipher
	 *
	 * If the user said on the command line
	 *	-T tok:mfr:ser:lab -k keyfile
	 *	-c cipher -T tok:mfr:ser:lab -k keyfile
	 * the given cipher or the default cipher apply to keyfile,
	 * If the user said instead
	 *	-T tok:mfr:ser:lab
	 *	-c cipher -T tok:mfr:ser:lab
	 * the key named "lab" may or may not agree with the given
	 * cipher or the default cipher.  In those cases, cipher will
	 * be overridden with the actual cipher type of the key "lab".
	 */
	*rv = CKR_FUNCTION_FAILED;

	if (args == NULL) {
		return (B_FALSE);
	}

	cipher = (mech_alias_t *)args;
	token = cipher->token;

	if (C_GetMechanismInfo(slot_id, cipher->type, &mechinfo) != CKR_OK) {
		return (B_FALSE);
	}

	if (token == NULL) {
		if (C_GetMechanismInfo(slot_id, CKM_PKCS5_PBKD2, &mechinfo) !=
		    CKR_OK) {
			return (B_FALSE);
		}
		goto foundit;
	}

	/* does the token match the token spec? */
	if (token->key == NULL || (C_GetTokenInfo(slot_id, &tokinfo) != CKR_OK))
		return (B_FALSE);

	token_match = B_TRUE;

	if (token->name != NULL && (token->name)[0] != '\0' &&
	    strncmp((char *)token->name, (char *)tokinfo.label,
	    TOKEN_LABEL_SIZE) != 0)
		token_match = B_FALSE;
	if (token->mfr != NULL && (token->mfr)[0] != '\0' &&
	    strncmp((char *)token->mfr, (char *)tokinfo.manufacturerID,
	    TOKEN_MANUFACTURER_SIZE) != 0)
		token_match = B_FALSE;
	if (token->serno != NULL && (token->serno)[0] != '\0' &&
	    strncmp((char *)token->serno, (char *)tokinfo.serialNumber,
	    TOKEN_SERIAL_SIZE) != 0)
		token_match = B_FALSE;

	if (!token_match)
		return (B_FALSE);

foundit:
	cipher->slot = slot_id;
	return (B_TRUE);
}

/*
 * Clean up crypto loose ends
 */
static void
end_crypto(CK_SESSION_HANDLE sess)
{
	(void) C_CloseSession(sess);
	(void) C_Finalize(NULL);
}

/*
 * Set up crypto, opening session on slot that matches token and cipher
 */
static void
init_crypto(token_spec_t *token, mech_alias_t *cipher,
    CK_SESSION_HANDLE_PTR sess)
{
	CK_RV	rv;

	cipher->token = token;

	/* Turn off Metaslot so that we can see actual tokens */
	if (setenv("METASLOT_ENABLED", "false", 1) < 0) {
		die(gettext("could not disable Metaslot"));
	}

	rv = pkcs11_GetCriteriaSession(match_token_cipher, (void *)cipher,
	    sess);
	if (rv != CKR_OK) {
		end_crypto(*sess);
		if (rv == CKR_HOST_MEMORY) {
			die("malloc");
		}
		die(gettext("failed to find any cryptographic provider, "
		    "use \"cryptoadm list -p\" to find providers: %s\n"),
		    pkcs11_strerror(rv));
	}
}

/*
 * Uncompress a file.
 *
 * First map the file in to establish a device
 * association, then read from it. On-the-fly
 * decompression will automatically uncompress
 * the file if it's compressed
 *
 * If the file is mapped and a device association
 * has been established, disallow uncompressing
 * the file until it is unmapped.
 */
static void
lofi_uncompress(int lfd, const char *filename)
{
	struct lofi_ioctl li;
	char buf[MAXBSIZE];
	char devicename[32];
	char tmpfilename[MAXPATHLEN];
	char *x;
	char *dir = NULL;
	char *file = NULL;
	int minor = 0;
	struct stat64 statbuf;
	int compfd = -1;
	int uncompfd = -1;
	ssize_t rbytes;

	/*
	 * Disallow uncompressing the file if it is
	 * already mapped.
	 */
	li.li_crypto_enabled = B_FALSE;
	li.li_id = 0;
	(void) strlcpy(li.li_filename, filename, sizeof (li.li_filename));
	if (ioctl(lfd, LOFI_GET_MINOR, &li) != -1)
		die(gettext("%s must be unmapped before uncompressing"),
		    filename);

	/* Zero length files don't need to be uncompressed */
	if (stat64(filename, &statbuf) == -1)
		die(gettext("stat: %s"), filename);
	if (statbuf.st_size == 0)
		return;

	minor = lofi_map_file(lfd, &li, filename);
	(void) snprintf(devicename, sizeof (devicename), "/dev/%s/%d",
	    LOFI_BLOCK_NAME, minor);

	/* If the file isn't compressed, we just return */
	if ((ioctl(lfd, LOFI_CHECK_COMPRESSED, &li) == -1) ||
	    (li.li_algorithm[0] == '\0')) {
		delete_mapping(lfd, devicename, filename, B_TRUE);
		die("%s is not compressed\n", filename);
	}

	if ((compfd = open64(devicename, O_RDONLY | O_NONBLOCK)) == -1) {
		delete_mapping(lfd, devicename, filename, B_TRUE);
		die(gettext("open: %s"), filename);
	}
	/* Create a temp file in the same directory */
	x = strdup(filename);
	dir = strdup(dirname(x));
	free(x);
	x = strdup(filename);
	file = strdup(basename(x));
	free(x);
	(void) snprintf(tmpfilename, sizeof (tmpfilename),
	    "%s/.%sXXXXXX", dir, file);
	free(dir);
	free(file);

	if ((uncompfd = mkstemp64(tmpfilename)) == -1) {
		(void) close(compfd);
		delete_mapping(lfd, devicename, filename, B_TRUE);
		die("%s could not be uncompressed\n", filename);
	}

	/*
	 * Set the mode bits and the owner of this temporary
	 * file to be that of the original uncompressed file
	 */
	(void) fchmod(uncompfd, statbuf.st_mode);

	if (fchown(uncompfd, statbuf.st_uid, statbuf.st_gid) == -1) {
		(void) close(compfd);
		(void) close(uncompfd);
		delete_mapping(lfd, devicename, filename, B_TRUE);
		die("%s could not be uncompressed\n", filename);
	}

	/* Now read from the device in MAXBSIZE-sized chunks */
	for (;;) {
		rbytes = read(compfd, buf, sizeof (buf));

		if (rbytes <= 0)
			break;

		if (write(uncompfd, buf, rbytes) != rbytes) {
			rbytes = -1;
			break;
		}
	}

	(void) close(compfd);
	(void) close(uncompfd);

	/* Delete the mapping */
	delete_mapping(lfd, devicename, filename, B_TRUE);

	/*
	 * If an error occured while reading or writing, rbytes will
	 * be negative
	 */
	if (rbytes < 0) {
		(void) unlink(tmpfilename);
		die(gettext("could not read from %s"), filename);
	}

	/* Rename the temp file to the actual file */
	if (rename(tmpfilename, filename) == -1)
		(void) unlink(tmpfilename);
}

/*
 * Compress a file
 */
static void
lofi_compress(int *lfd, const char *filename, int compress_index,
    uint32_t segsize)
{
	struct lofi_ioctl lic;
	lofi_compress_info_t *li;
	struct flock lock;
	char tmpfilename[MAXPATHLEN];
	char comp_filename[MAXPATHLEN];
	char algorithm[MAXALGLEN];
	char *x;
	char *dir = NULL, *file = NULL;
	uchar_t *uncompressed_seg = NULL;
	uchar_t *compressed_seg = NULL;
	uint32_t compressed_segsize;
	uint32_t len_compressed, count;
	uint32_t index_entries, index_sz;
	uint64_t *index = NULL;
	uint64_t offset;
	size_t real_segsize;
	struct stat64 statbuf;
	int compfd = -1, uncompfd = -1;
	int tfd = -1;
	ssize_t rbytes, wbytes, lastread;
	int i, type;

	/*
	 * Disallow compressing the file if it is
	 * already mapped
	 */
	lic.li_id = 0;
	(void) strlcpy(lic.li_filename, filename, sizeof (lic.li_filename));
	if (ioctl(*lfd, LOFI_GET_MINOR, &lic) != -1)
		die(gettext("%s must be unmapped before compressing"),
		    filename);

	/*
	 * Close the control device so other operations
	 * can use it
	 */
	(void) close(*lfd);
	*lfd = -1;

	li = &lofi_compress_table[compress_index];

	/*
	 * The size of the buffer to hold compressed data must
	 * be slightly larger than the compressed segment size.
	 *
	 * The compress functions use part of the buffer as
	 * scratch space to do calculations.
	 * Ref: http://www.zlib.net/manual.html#compress2
	 */
	compressed_segsize = segsize + (segsize >> 6);
	compressed_seg = (uchar_t *)malloc(compressed_segsize + SEGHDR);
	uncompressed_seg = (uchar_t *)malloc(segsize);

	if (compressed_seg == NULL || uncompressed_seg == NULL)
		die(gettext("No memory"));

	if ((uncompfd = open64(filename, O_RDWR|O_LARGEFILE, 0)) == -1)
		die(gettext("open: %s"), filename);

	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;

	/*
	 * Use an advisory lock to ensure that only a
	 * single lofiadm process compresses a given
	 * file at any given time
	 *
	 * A close on the file descriptor automatically
	 * closes all lock state on the file
	 */
	if (fcntl(uncompfd, F_SETLKW, &lock) == -1)
		die(gettext("fcntl: %s"), filename);

	if (fstat64(uncompfd, &statbuf) == -1) {
		(void) close(uncompfd);
		die(gettext("fstat: %s"), filename);
	}

	/* Zero length files don't need to be compressed */
	if (statbuf.st_size == 0) {
		(void) close(uncompfd);
		return;
	}

	/*
	 * Create temporary files in the same directory that
	 * will hold the intermediate data
	 */
	x = strdup(filename);
	dir = strdup(dirname(x));
	free(x);
	x = strdup(filename);
	file = strdup(basename(x));
	free(x);
	(void) snprintf(tmpfilename, sizeof (tmpfilename),
	    "%s/.%sXXXXXX", dir, file);
	(void) snprintf(comp_filename, sizeof (comp_filename),
	    "%s/.%sXXXXXX", dir, file);
	free(dir);
	free(file);

	if ((tfd = mkstemp64(tmpfilename)) == -1)
		goto cleanup;

	if ((compfd = mkstemp64(comp_filename)) == -1)
		goto cleanup;

	/*
	 * Set the mode bits and owner of the compressed
	 * file to be that of the original uncompressed file
	 */
	(void) fchmod(compfd, statbuf.st_mode);

	if (fchown(compfd, statbuf.st_uid, statbuf.st_gid) == -1)
		goto cleanup;

	/*
	 * Calculate the number of index entries required.
	 * index entries are stored as an array. adding
	 * a '2' here accounts for the fact that the last
	 * segment may not be a multiple of the segment size
	 */
	index_sz = (statbuf.st_size / segsize) + 2;
	index = malloc(sizeof (*index) * index_sz);

	if (index == NULL)
		goto cleanup;

	offset = 0;
	lastread = segsize;
	count = 0;

	/*
	 * Now read from the uncompressed file in 'segsize'
	 * sized chunks, compress what was read in and
	 * write it out to a temporary file
	 */
	for (;;) {
		rbytes = read(uncompfd, uncompressed_seg, segsize);

		if (rbytes <= 0)
			break;

		if (lastread < segsize)
			goto cleanup;

		/*
		 * Account for the first byte that
		 * indicates whether a segment is
		 * compressed or not
		 */
		real_segsize = segsize - 1;
		(void) li->l_compress(uncompressed_seg, rbytes,
		    compressed_seg + SEGHDR, &real_segsize, li->l_level);

		/*
		 * If the length of the compressed data is more
		 * than a threshold then there isn't any benefit
		 * to be had from compressing this segment - leave
		 * it uncompressed.
		 *
		 * NB. In case an error occurs during compression (above)
		 * the 'real_segsize' isn't changed. The logic below
		 * ensures that that segment is left uncompressed.
		 */
		len_compressed = real_segsize;
		if (segsize <= COMPRESS_THRESHOLD ||
		    real_segsize > (segsize - COMPRESS_THRESHOLD)) {
			(void) memcpy(compressed_seg + SEGHDR, uncompressed_seg,
			    rbytes);
			type = UNCOMPRESSED;
			len_compressed = rbytes;
		} else {
			type = COMPRESSED;
		}

		/*
		 * Set the first byte or the SEGHDR to
		 * indicate if it's compressed or not
		 */
		*compressed_seg = type;
		wbytes = write(tfd, compressed_seg, len_compressed + SEGHDR);
		if (wbytes != (len_compressed + SEGHDR)) {
			rbytes = -1;
			break;
		}

		index[count] = BE_64(offset);
		offset += wbytes;
		lastread = rbytes;
		count++;
	}

	(void) close(uncompfd);

	if (rbytes < 0)
		goto cleanup;
	/*
	 * The last index entry is a sentinel entry. It does not point to
	 * an actual compressed segment but helps in computing the size of
	 * the compressed segment. The size of each compressed segment is
	 * computed by subtracting the current index value from the next
	 * one (the compressed blocks are stored sequentially)
	 */
	index[count++] = BE_64(offset);

	/*
	 * Now write the compressed data along with the
	 * header information to this file which will
	 * later be renamed to the original uncompressed
	 * file name
	 *
	 * The header is as follows -
	 *
	 * Signature (name of the compression algorithm)
	 * Compression segment size (a multiple of 512)
	 * Number of index entries
	 * Size of the last block
	 * The array containing the index entries
	 *
	 * the header is always stored in network byte
	 * order
	 */
	(void) bzero(algorithm, sizeof (algorithm));
	(void) strlcpy(algorithm, li->l_name, sizeof (algorithm));
	if (write(compfd, algorithm, sizeof (algorithm))
	    != sizeof (algorithm))
		goto cleanup;

	segsize = htonl(segsize);
	if (write(compfd, &segsize, sizeof (segsize)) != sizeof (segsize))
		goto cleanup;

	index_entries = htonl(count);
	if (write(compfd, &index_entries, sizeof (index_entries)) !=
	    sizeof (index_entries))
		goto cleanup;

	lastread = htonl(lastread);
	if (write(compfd, &lastread, sizeof (lastread)) != sizeof (lastread))
		goto cleanup;

	for (i = 0; i < count; i++) {
		if (write(compfd, index + i, sizeof (*index)) !=
		    sizeof (*index))
			goto cleanup;
	}

	/* Header is written, now write the compressed data */
	if (lseek(tfd, 0, SEEK_SET) != 0)
		goto cleanup;

	rbytes = wbytes = 0;

	for (;;) {
		rbytes = read(tfd, compressed_seg, compressed_segsize + SEGHDR);

		if (rbytes <= 0)
			break;

		if (write(compfd, compressed_seg, rbytes) != rbytes)
			goto cleanup;
	}

	if (fstat64(compfd, &statbuf) == -1)
		goto cleanup;

	/*
	 * Round up the compressed file size to be a multiple of
	 * DEV_BSIZE. lofi(4D) likes it that way.
	 */
	if ((offset = statbuf.st_size % DEV_BSIZE) > 0) {

		offset = DEV_BSIZE - offset;

		for (i = 0; i < offset; i++)
			uncompressed_seg[i] = '\0';
		if (write(compfd, uncompressed_seg, offset) != offset)
			goto cleanup;
	}
	(void) close(compfd);
	(void) close(tfd);
	(void) unlink(tmpfilename);
cleanup:
	if (rbytes < 0) {
		if (tfd != -1)
			(void) unlink(tmpfilename);
		if (compfd != -1)
			(void) unlink(comp_filename);
		die(gettext("error compressing file %s"), filename);
	} else {
		/* Rename the compressed file to the actual file */
		if (rename(comp_filename, filename) == -1) {
			(void) unlink(comp_filename);
			die(gettext("error compressing file %s"), filename);
		}
	}
	if (compressed_seg != NULL)
		free(compressed_seg);
	if (uncompressed_seg != NULL)
		free(uncompressed_seg);
	if (index != NULL)
		free(index);
	if (compfd != -1)
		(void) close(compfd);
	if (uncompfd != -1)
		(void) close(uncompfd);
	if (tfd != -1)
		(void) close(tfd);
}

static int
lofi_compress_select(const char *algname)
{
	int i;

	for (i = 0; i < LOFI_COMPRESS_FUNCTIONS; i++) {
		if (strcmp(lofi_compress_table[i].l_name, algname) == 0)
			return (i);
	}
	return (-1);
}

static void
check_algorithm_validity(const char *algname, int *compress_index)
{
	*compress_index = lofi_compress_select(algname);
	if (*compress_index < 0)
		die(gettext("invalid algorithm name: %s\n"), algname);
}

static void
check_file_validity(const char *filename)
{
	struct stat64 buf;
	int 	error;
	int	fd;

	fd = open64(filename, O_RDONLY);
	if (fd == -1) {
		die(gettext("open: %s"), filename);
	}
	error = fstat64(fd, &buf);
	if (error == -1) {
		die(gettext("fstat: %s"), filename);
	} else if (!S_ISLOFIABLE(buf.st_mode)) {
		die(gettext("%s is not a regular file, "
		    "block, or character device\n"),
		    filename);
	} else if ((buf.st_size % DEV_BSIZE) != 0) {
		die(gettext("size of %s is not a multiple of %d\n"),
		    filename, DEV_BSIZE);
	}
	(void) close(fd);

	if (name_to_minor(filename) != 0) {
		die(gettext("cannot use %s on itself\n"), LOFI_DRIVER_NAME);
	}
}

static boolean_t
check_file_is_encrypted(const char *filename)
{
	int	fd;
	char    buf[sizeof (lofi_crypto_magic)];
	int	got;
	int	rest = sizeof (lofi_crypto_magic);

	fd = open64(filename, O_RDONLY);
	if (fd == -1)
		die(gettext("failed to open: %s"), filename);

	if (lseek(fd, CRYOFF, SEEK_SET) != CRYOFF)
		die(gettext("failed to seek to offset 0x%lx in file %s"),
		    CRYOFF, filename);

	do {
		got = read(fd, buf + sizeof (lofi_crypto_magic) - rest, rest);
		if ((got == 0) || ((got == -1) && (errno != EINTR)))
			die(gettext("failed to read crypto header"
			    " at offset 0x%lx in file %s"), CRYOFF, filename);

		if (got > 0)
			rest -= got;
	} while (rest > 0);

	while (close(fd) == -1) {
		if (errno != EINTR)
			die(gettext("failed to close file %s"), filename);
	}

	return (strncmp(buf, lofi_crypto_magic,
	    sizeof (lofi_crypto_magic)) == 0);
}

static uint32_t
convert_to_num(const char *str)
{
	int len;
	uint32_t segsize, mult = 1;

	len = strlen(str);
	if (len && isalpha(str[len - 1])) {
		switch (str[len - 1]) {
		case 'k':
		case 'K':
			mult = KILOBYTE;
			break;
		case 'b':
		case 'B':
			mult = BLOCK_SIZE;
			break;
		case 'm':
		case 'M':
			mult = MEGABYTE;
			break;
		case 'g':
		case 'G':
			mult = GIGABYTE;
			break;
		default:
			die(gettext("invalid segment size %s\n"), str);
		}
	}

	segsize = atol(str);
	segsize *= mult;

	return (segsize);
}

int
main(int argc, char *argv[])
{
	int	lfd;
	int	c;
	const char *devicename = NULL;
	const char *filename = NULL;
	const char *algname = COMPRESS_ALGORITHM;
	int	openflag;
	int	minor;
	int	compress_index;
	uint32_t segsize = SEGSIZE;
	static char *lofictl = "/dev/" LOFI_CTL_NAME;
	boolean_t force = B_FALSE;
	const char *pname;
	boolean_t errflag = B_FALSE;
	boolean_t addflag = B_FALSE;
	boolean_t labelflag = B_FALSE;
	boolean_t rdflag = B_FALSE;
	boolean_t deleteflag = B_FALSE;
	boolean_t ephflag = B_FALSE;
	boolean_t compressflag = B_FALSE;
	boolean_t uncompressflag = B_FALSE;
	/* the next two work together for -c, -k, -T, -e options only */
	boolean_t need_crypto = B_FALSE;	/* if any -c, -k, -T, -e */
	boolean_t cipher_only = B_TRUE;		/* if -c only */
	const char *keyfile = NULL;
	mech_alias_t *cipher = NULL;
	token_spec_t *token = NULL;
	char	*rkey = NULL;
	size_t	rksz = 0;
	char realfilename[MAXPATHLEN];

	pname = getpname(argv[0]);

	(void) setlocale(LC_ALL, "");
	(void) textdomain(TEXT_DOMAIN);

	while ((c = getopt(argc, argv, "a:c:Cd:efk:lrs:T:U")) != EOF) {
		switch (c) {
		case 'a':
			addflag = B_TRUE;
			if ((filename = realpath(optarg, realfilename)) == NULL)
				die("%s", optarg);
			if (((argc - optind) > 0) && (*argv[optind] != '-')) {
				/* optional device */
				devicename = argv[optind];
				optind++;
			}
			break;
		case 'C':
			compressflag = B_TRUE;
			if (((argc - optind) > 1) && (*argv[optind] != '-')) {
				/* optional algorithm */
				algname = argv[optind];
				optind++;
			}
			check_algorithm_validity(algname, &compress_index);
			break;
		case 'c':
			/* is the chosen cipher allowed? */
			if ((cipher = ciph2mech(optarg)) == NULL) {
				errflag = B_TRUE;
				warn(gettext("cipher %s not allowed\n"),
				    optarg);
			}
			need_crypto = B_TRUE;
			/* cipher_only is already set */
			break;
		case 'd':
			deleteflag = B_TRUE;
			minor = name_to_minor(optarg);
			if (minor != 0)
				devicename = optarg;
			else {
				if ((filename = realpath(optarg,
				    realfilename)) == NULL)
					die("%s", optarg);
			}
			break;
		case 'e':
			ephflag = B_TRUE;
			need_crypto = B_TRUE;
			cipher_only = B_FALSE;	/* need to unset cipher_only */
			break;
		case 'f':
			force = B_TRUE;
			break;
		case 'k':
			keyfile = optarg;
			need_crypto = B_TRUE;
			cipher_only = B_FALSE;	/* need to unset cipher_only */
			break;
		case 'l':
			labelflag = B_TRUE;
			break;
		case 'r':
			rdflag = B_TRUE;
			break;
		case 's':
			segsize = convert_to_num(optarg);
			if (segsize < DEV_BSIZE || !ISP2(segsize))
				die(gettext("segment size %s is invalid "
				    "or not a multiple of minimum block "
				    "size %ld\n"), optarg, DEV_BSIZE);
			break;
		case 'T':
			if ((token = parsetoken(optarg)) == NULL) {
				errflag = B_TRUE;
				warn(
				    gettext("invalid token key specifier %s\n"),
				    optarg);
			}
			need_crypto = B_TRUE;
			cipher_only = B_FALSE;	/* need to unset cipher_only */
			break;
		case 'U':
			uncompressflag = B_TRUE;
			break;
		case '?':
		default:
			errflag = B_TRUE;
			break;
		}
	}

	/* Check for mutually exclusive combinations of options */
	if (errflag ||
	    (addflag && deleteflag) ||
	    (labelflag && !addflag) ||
	    (rdflag && !addflag) ||
	    (!addflag && need_crypto) ||
	    (need_crypto && labelflag) ||
	    ((compressflag || uncompressflag) &&
	    (labelflag || addflag || deleteflag)))
		usage(pname);

	/* ephemeral key, and key from either file or token are incompatible */
	if (ephflag && (keyfile != NULL || token != NULL)) {
		die(gettext("ephemeral key cannot be used with keyfile"
		    " or token key\n"));
	}

	/*
	 * "-c" but no "-k", "-T", "-e", or "-T -k" means derive key from
	 * command line passphrase
	 */

	switch (argc - optind) {
	case 0: /* no more args */
		if (compressflag || uncompressflag)	/* needs filename */
			usage(pname);
		break;
	case 1:
		if (addflag || deleteflag)
			usage(pname);
		/* one arg means compress/uncompress the file ... */
		if (compressflag || uncompressflag) {
			if ((filename = realpath(argv[optind],
			    realfilename)) == NULL)
				die("%s", argv[optind]);
		/* ... or without options means print the association */
		} else {
			minor = name_to_minor(argv[optind]);
			if (minor != 0)
				devicename = argv[optind];
			else {
				if ((filename = realpath(argv[optind],
				    realfilename)) == NULL)
					die("%s", argv[optind]);
			}
		}
		break;
	default:
		usage(pname);
		break;
	}

	if (addflag || compressflag || uncompressflag)
		check_file_validity(filename);

	if (filename && !valid_abspath(filename))
		exit(E_ERROR);

	/*
	 * Here, we know the arguments are correct, the filename is an
	 * absolute path, it exists and is a regular file. We don't yet
	 * know that the device name is ok or not.
	 */

	openflag = O_EXCL;
	if (addflag || deleteflag || compressflag || uncompressflag)
		openflag |= O_RDWR;
	else
		openflag |= O_RDONLY;
	lfd = open(lofictl, openflag);
	if (lfd == -1) {
		if ((errno == EPERM) || (errno == EACCES)) {
			die(gettext("you do not have permission to perform "
			    "that operation.\n"));
		} else {
			die(gettext("open: %s"), lofictl);
		}
		/*NOTREACHED*/
	}

	/*
	 * No passphrase is needed for ephemeral key, or when key is
	 * in a file and not wrapped by another key from a token.
	 * However, a passphrase is needed in these cases:
	 * 1. cipher with no ephemeral key, key file, or token,
	 *    in which case the passphrase is used to build the key
	 * 2. token with an optional cipher or optional key file,
	 *    in which case the passphrase unlocks the token
	 * If only the cipher is specified, reconfirm the passphrase
	 * to ensure the user hasn't mis-entered it.  Otherwise, the
	 * token will enforce the token passphrase.
	 */
	if (need_crypto) {
		CK_SESSION_HANDLE	sess;

		/* pick a cipher if none specified */
		if (cipher == NULL)
			cipher = DEFAULT_CIPHER;

		if (!kernel_cipher_check(cipher))
			die(gettext(
			    "use \"cryptoadm list -m\" to find available "
			    "mechanisms\n"));

		init_crypto(token, cipher, &sess);

		if (cipher_only) {
			getkeyfromuser(cipher, &rkey, &rksz,
			    !check_file_is_encrypted(filename));
		} else if (token != NULL) {
			getkeyfromtoken(sess, token, keyfile, cipher,
			    &rkey, &rksz);
		} else {
			/* this also handles ephemeral keys */
			getkeyfromfile(keyfile, cipher, &rkey, &rksz);
		}

		end_crypto(sess);
	}

	/*
	 * Now to the real work.
	 */
	if (addflag)
		add_mapping(lfd, devicename, filename, cipher, rkey, rksz,
		    rdflag, labelflag);
	else if (compressflag)
		lofi_compress(&lfd, filename, compress_index, segsize);
	else if (uncompressflag)
		lofi_uncompress(lfd, filename);
	else if (deleteflag)
		delete_mapping(lfd, devicename, filename, force);
	else if (filename || devicename)
		print_one_mapping(lfd, devicename, filename);
	else
		print_mappings(lfd);

	if (lfd != -1)
		(void) close(lfd);
	closelib();
	return (E_SUCCESS);
}