|
root / base / usr / src / common / smbclnt / smbfs_ntacl.c
smbfs_ntacl.c C 1710 lines 36.8 KB
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
/*
 * 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
 */

/*
 * ACL conversion support for smbfs
 * (To/from NT/ZFS-style ACLs.)
 */

#include <sys/types.h>
#include <sys/errno.h>
#include <sys/acl.h>
#include <sys/byteorder.h>

#if defined(_KERNEL) || defined(_FAKE_KERNEL)

#include <sys/cred.h>
#include <sys/cmn_err.h>
#include <sys/kmem.h>
#include <sys/sunddi.h>
#include <sys/vnode.h>
#include <sys/vfs.h>

#else	/* _KERNEL || _FAKE_KERNEL */

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

#endif	/* _KERNEL || _FAKE_KERNEL */

#ifdef _KERNEL
#include <sys/kidmap.h>
#else	/* _KERNEL */
#include <idmap.h>
#endif	/* _KERNEL */

#include <netsmb/mchain.h>
#include <netsmb/smb.h>
#include "smbfs_ntacl.h"

#define	NT_SD_REVISION	1
#define	NT_ACL_REVISION	2

#if defined(_KERNEL) || defined(_FAKE_KERNEL)
#define	MALLOC(size) kmem_alloc(size, KM_SLEEP)
#define	FREESZ(p, sz) kmem_free(p, sz)
#else	/* _KERNEL */
#define	MALLOC(size) malloc(size)
/*
 * Define FREESZ() as inline function so the compiler will not
 * trigger variable set but not used warning for sz in calling function.
 */
/* ARGSUSED */
static inline void
FREESZ(void *p, size_t sz __unused)
{
	free(p);
}
#endif	/* _KERNEL */

#define	ERRCHK(expr)	if ((error = expr) != 0) goto errout

/*
 * Security IDentifier (SID)
 */
static void
ifree_sid(i_ntsid_t *sid)
{
	size_t sz;

	if (sid == NULL)
		return;

	sz = I_SID_SIZE(sid->sid_subauthcount);
	FREESZ(sid, sz);
}

static int
md_get_sid(mdchain_t *mdp, i_ntsid_t **sidp)
{
	i_ntsid_t *sid = NULL;
	uint8_t revision, subauthcount;
	uint32_t *subauthp;
	size_t sidsz;
	int error, i;

	if ((error = md_get_uint8(mdp, &revision)) != 0)
		return (error);
	if ((error = md_get_uint8(mdp, &subauthcount)) != 0)
		return (error);

	sidsz = I_SID_SIZE(subauthcount);

	if ((sid = MALLOC(sidsz)) == NULL)
		return (ENOMEM);

	bzero(sid, sidsz);
	sid->sid_revision = revision;
	sid->sid_subauthcount = subauthcount;
	ERRCHK(md_get_mem(mdp, sid->sid_authority, 6, MB_MSYSTEM));

	subauthp = &sid->sid_subauthvec[0];
	for (i = 0; i < subauthcount; i++) {
		ERRCHK(md_get_uint32le(mdp, subauthp));
		subauthp++;
	}

	/* Success! */
	*sidp = sid;
	return (0);

errout:
	ifree_sid(sid);
	return (error);
}

static int
mb_put_sid(mbchain_t *mbp, i_ntsid_t *sid)
{
	uint32_t *subauthp;
	int error, i;

	if (sid == NULL)
		return (EINVAL);

	ERRCHK(mb_put_uint8(mbp, sid->sid_revision));
	ERRCHK(mb_put_uint8(mbp, sid->sid_subauthcount));
	ERRCHK(mb_put_mem(mbp, sid->sid_authority, 6, MB_MSYSTEM));

	subauthp = &sid->sid_subauthvec[0];
	for (i = 0; i < sid->sid_subauthcount; i++) {
		ERRCHK(mb_put_uint32le(mbp, *subauthp));
		subauthp++;
	}

	/* Success! */
	return (0);

errout:
	return (error);
}


/*
 * Access Control Entry (ACE)
 */
static void
ifree_ace(i_ntace_t *ace)
{

	if (ace == NULL)
		return;

	switch (ace->ace_hdr.ace_type) {
	case ACCESS_ALLOWED_ACE_TYPE:
	case ACCESS_DENIED_ACE_TYPE:
	case SYSTEM_AUDIT_ACE_TYPE:
	case SYSTEM_ALARM_ACE_TYPE:
		ifree_sid(ace->ace_v2.ace_sid);
		FREESZ(ace, sizeof (i_ntace_v2_t));
		break;
	/* other types todo */
	default:
		break;
	}
}

static int
md_get_ace(mdchain_t *mdp, i_ntace_t **acep)
{
	mdchain_t tmp_md;
	i_ntace_hdr_t ace_hdr;
	i_ntace_t *ace = NULL;
	uint16_t alloc_size;
	int error;

	/*
	 * The ACE is realy variable length,
	 * with format determined by the type.
	 *
	 * There may also be padding after it, so
	 * decode it using a copy of the mdchain,
	 * and then consume the specified length.
	 */
	tmp_md = *mdp;

	/* Fixed-size ACE header */
	ERRCHK(md_get_uint8(&tmp_md, &ace_hdr.ace_type));
	ERRCHK(md_get_uint8(&tmp_md, &ace_hdr.ace_flags));
	ERRCHK(md_get_uint16le(&tmp_md, &ace_hdr.ace_size));

	switch (ace_hdr.ace_type) {
	case ACCESS_ALLOWED_ACE_TYPE:
	case ACCESS_DENIED_ACE_TYPE:
	case SYSTEM_AUDIT_ACE_TYPE:
	case SYSTEM_ALARM_ACE_TYPE:
		alloc_size = sizeof (i_ntace_v2_t);
		if ((ace = MALLOC(alloc_size)) == NULL)
			return (ENOMEM);
		bzero(ace, alloc_size);
		/* ACE header */
		ace->ace_hdr.ace_type = ace_hdr.ace_type;
		ace->ace_hdr.ace_flags = ace_hdr.ace_flags;
		ace->ace_hdr.ace_size = alloc_size;
		/* Type-specific data. */
		ERRCHK(md_get_uint32le(&tmp_md, &ace->ace_v2.ace_rights));
		ERRCHK(md_get_sid(&tmp_md, &ace->ace_v2.ace_sid));
		break;

	/* other types todo */
	default:
		error = EIO;
		goto errout;
	}

	/* Now actually consume ace_hdr.ace_size */
	ERRCHK(md_get_mem(mdp, NULL, ace_hdr.ace_size, MB_MSYSTEM));

	/* Success! */
	*acep = ace;
	return (0);

errout:
	ifree_ace(ace);
	return (error);
}

static int
mb_put_ace(mbchain_t *mbp, i_ntace_t *ace)
{
	int cnt0, error;
	uint16_t ace_len, *ace_len_p;

	if (ace == NULL)
		return (EINVAL);

	cnt0 = mbp->mb_count;

	/*
	 * Put the (fixed-size) ACE header
	 * Will fill in the length later.
	 */
	ERRCHK(mb_put_uint8(mbp, ace->ace_hdr.ace_type));
	ERRCHK(mb_put_uint8(mbp, ace->ace_hdr.ace_flags));
	ace_len_p = mb_reserve(mbp, sizeof (*ace_len_p));
	if (ace_len_p == NULL) {
		error = ENOMEM;
		goto errout;
	}

	switch (ace->ace_hdr.ace_type) {
	case ACCESS_ALLOWED_ACE_TYPE:
	case ACCESS_DENIED_ACE_TYPE:
	case SYSTEM_AUDIT_ACE_TYPE:
	case SYSTEM_ALARM_ACE_TYPE:
		/* Put type-specific data. */
		ERRCHK(mb_put_uint32le(mbp, ace->ace_v2.ace_rights));
		ERRCHK(mb_put_sid(mbp, ace->ace_v2.ace_sid));
		break;

	/* other types todo */
	default:
		error = EIO;
		goto errout;
	}

	/* Fill in the (OtW) ACE length. */
	ace_len = mbp->mb_count - cnt0;
	*ace_len_p = htoles(ace_len);

	/* Success! */
	return (0);

errout:
	return (error);
}


/*
 * Access Control List (ACL)
 */

/* Not an OTW structure, so size can be at our convenience. */
#define	I_ACL_SIZE(cnt)	(sizeof (i_ntacl_t) + (cnt) * sizeof (void *))

static void
ifree_acl(i_ntacl_t *acl)
{
	i_ntace_t **acep;
	size_t sz;
	int i;

	if (acl == NULL)
		return;

	acep = &acl->acl_acevec[0];
	for (i = 0; i < acl->acl_acecount; i++) {
		ifree_ace(*acep);
		acep++;
	}
	sz = I_ACL_SIZE(acl->acl_acecount);
	FREESZ(acl, sz);
}

static int
md_get_acl(mdchain_t *mdp, i_ntacl_t **aclp)
{
	i_ntacl_t *acl = NULL;
	i_ntace_t **acep;
	uint8_t revision;
	uint16_t acl_len, acecount;
	size_t aclsz;
	int i, error;

	if ((error = md_get_uint8(mdp, &revision)) != 0)
		return (error);
	if ((error = md_get_uint8(mdp, NULL)) != 0) /* pad1 */
		return (error);
	if ((error = md_get_uint16le(mdp, &acl_len)) != 0)
		return (error);
	if ((error = md_get_uint16le(mdp, &acecount)) != 0)
		return (error);
	if ((error = md_get_uint16le(mdp, NULL)) != 0) /* pad2 */
		return (error);

	aclsz = I_ACL_SIZE(acecount);
	if ((acl = MALLOC(aclsz)) == NULL)
		return (ENOMEM);
	bzero(acl, aclsz);
	acl->acl_revision = revision;
	acl->acl_acecount = acecount;

	acep = &acl->acl_acevec[0];
	for (i = 0; i < acl->acl_acecount; i++) {
		ERRCHK(md_get_ace(mdp, acep));
		acep++;
	}
	/*
	 * There may be more data here, but
	 * the caller takes care of that.
	 */

	/* Success! */
	*aclp = acl;
	return (0);

errout:
	ifree_acl(acl);
	return (error);
}

static int
mb_put_acl(mbchain_t *mbp, i_ntacl_t *acl)
{
	i_ntace_t **acep;
	uint16_t acl_len, *acl_len_p;
	int i, cnt0, error;

	cnt0 = mbp->mb_count;

	ERRCHK(mb_put_uint8(mbp, acl->acl_revision));
	ERRCHK(mb_put_uint8(mbp, 0)); /* pad1 */
	acl_len_p = mb_reserve(mbp, sizeof (*acl_len_p));
	if (acl_len_p == NULL) {
		error = ENOMEM;
		goto errout;
	}
	ERRCHK(mb_put_uint16le(mbp, acl->acl_acecount));
	ERRCHK(mb_put_uint16le(mbp, 0)); /* pad2 */

	acep = &acl->acl_acevec[0];
	for (i = 0; i < acl->acl_acecount; i++) {
		ERRCHK(mb_put_ace(mbp, *acep));
		acep++;
	}

	/* Fill in acl_len_p */
	acl_len = mbp->mb_count - cnt0;
	*acl_len_p = htoles(acl_len);

	/* Success! */
	return (0);

errout:
	return (error);
}


/*
 * Security Descriptor
 */
void
smbfs_acl_free_sd(i_ntsd_t *sd)
{

	if (sd == NULL)
		return;

	ifree_sid(sd->sd_owner);
	ifree_sid(sd->sd_group);
	ifree_acl(sd->sd_sacl);
	ifree_acl(sd->sd_dacl);

	FREESZ(sd, sizeof (*sd));
}

/*
 * Import a raw SD (mb chain) into "internal" form.
 * (like "absolute" form per. NT docs)
 * Returns allocated data in sdp
 *
 * Note: does NOT consume all the mdp data, so the
 * caller has to take care of that if necessary.
 */
int
md_get_ntsd(mdchain_t *mdp, i_ntsd_t **sdp)
{
	i_ntsd_t *sd = NULL;
	mdchain_t top_md, tmp_md;
	uint32_t owneroff, groupoff, sacloff, dacloff;
	int error;

	if ((sd = MALLOC(sizeof (*sd))) == NULL)
		return (ENOMEM);
	bzero(sd, sizeof (*sd));

	/*
	 * Offsets below are relative to this point,
	 * so save the mdp state for use below.
	 */
	top_md = *mdp;

	ERRCHK(md_get_uint8(mdp, &sd->sd_revision));
	ERRCHK(md_get_uint8(mdp, &sd->sd_rmctl));
	ERRCHK(md_get_uint16le(mdp, &sd->sd_flags));
	ERRCHK(md_get_uint32le(mdp, &owneroff));
	ERRCHK(md_get_uint32le(mdp, &groupoff));
	ERRCHK(md_get_uint32le(mdp, &sacloff));
	ERRCHK(md_get_uint32le(mdp, &dacloff));

	/*
	 * The SD is "self-relative" on the wire,
	 * but not after this decodes it.
	 */
	sd->sd_flags &= ~SD_SELF_RELATIVE;

	/*
	 * For each section make a temporary copy of the
	 * top_md state, advance to the given offset, and
	 * pass that to the lower md_get_xxx functions.
	 * These could be marshalled in any order, but
	 * are normally found in the order shown here.
	 */
	if (sacloff) {
		tmp_md = top_md;
		md_get_mem(&tmp_md, NULL, sacloff, MB_MSYSTEM);
		ERRCHK(md_get_acl(&tmp_md, &sd->sd_sacl));
	}
	if (dacloff) {
		tmp_md = top_md;
		md_get_mem(&tmp_md, NULL, dacloff, MB_MSYSTEM);
		ERRCHK(md_get_acl(&tmp_md, &sd->sd_dacl));
	}
	if (owneroff) {
		tmp_md = top_md;
		md_get_mem(&tmp_md, NULL, owneroff, MB_MSYSTEM);
		ERRCHK(md_get_sid(&tmp_md, &sd->sd_owner));
	}
	if (groupoff) {
		tmp_md = top_md;
		md_get_mem(&tmp_md, NULL, groupoff, MB_MSYSTEM);
		ERRCHK(md_get_sid(&tmp_md, &sd->sd_group));
	}

	/* Success! */
	*sdp = sd;
	return (0);

errout:
	smbfs_acl_free_sd(sd);
	return (error);
}

/*
 * Export an "internal" SD into an raw SD (mb chain).
 * (a.k.a "self-relative" form per. NT docs)
 * Returns allocated mbchain in mbp.
 */
int
mb_put_ntsd(mbchain_t *mbp, i_ntsd_t *sd)
{
	uint32_t *owneroffp, *groupoffp, *sacloffp, *dacloffp;
	uint32_t owneroff, groupoff, sacloff, dacloff;
	uint16_t flags;
	int cnt0, error;

	cnt0 = mbp->mb_count;
	owneroff = groupoff = sacloff = dacloff = 0;

	/* The SD is "self-relative" on the wire. */
	flags = sd->sd_flags | SD_SELF_RELATIVE;

	ERRCHK(mb_put_uint8(mbp, sd->sd_revision));
	ERRCHK(mb_put_uint8(mbp, sd->sd_rmctl));
	ERRCHK(mb_put_uint16le(mbp, flags));

	owneroffp = mb_reserve(mbp, sizeof (*owneroffp));
	groupoffp = mb_reserve(mbp, sizeof (*groupoffp));
	sacloffp  = mb_reserve(mbp, sizeof (*sacloffp));
	dacloffp  = mb_reserve(mbp, sizeof (*dacloffp));
	if (owneroffp == NULL || groupoffp == NULL ||
	    sacloffp == NULL || dacloffp == NULL) {
		error = ENOMEM;
		goto errout;
	}

	/*
	 * These could be marshalled in any order, but
	 * are normally found in the order shown here.
	 */
	if (sd->sd_sacl) {
		sacloff = mbp->mb_count - cnt0;
		ERRCHK(mb_put_acl(mbp, sd->sd_sacl));
	}
	if (sd->sd_dacl) {
		dacloff = mbp->mb_count - cnt0;
		ERRCHK(mb_put_acl(mbp, sd->sd_dacl));
	}
	if (sd->sd_owner) {
		owneroff = mbp->mb_count - cnt0;
		ERRCHK(mb_put_sid(mbp, sd->sd_owner));
	}
	if (sd->sd_group) {
		groupoff = mbp->mb_count - cnt0;
		ERRCHK(mb_put_sid(mbp, sd->sd_group));
	}

	/* Fill in the offsets */
	*owneroffp = htolel(owneroff);
	*groupoffp = htolel(groupoff);
	*sacloffp  = htolel(sacloff);
	*dacloffp  = htolel(dacloff);

	/* Success! */
	return (0);

errout:
	return (error);
}

/*
 * ================================================================
 * Support for ACL fetch, including conversions
 * from Windows ACLs to NFSv4-style ACLs.
 * ================================================================
 */

#define	GENERIC_RIGHTS_MASK \
	(GENERIC_RIGHT_READ_ACCESS | GENERIC_RIGHT_WRITE_ACCESS |\
	GENERIC_RIGHT_EXECUTE_ACCESS | GENERIC_RIGHT_ALL_ACCESS)

/*
 * Table for converting NT GENERIC_RIGHT_... to specific rights
 * appropriate for objects of type file.
 */
struct gen2fsr {
	uint32_t	gf_generic;
	uint32_t	gf_specific;
};
static const struct gen2fsr
smbfs_gen2fsr[] = {
	{
		GENERIC_RIGHT_READ_ACCESS,
		STD_RIGHT_SYNCHRONIZE_ACCESS |
		STD_RIGHT_READ_CONTROL_ACCESS |
		SA_RIGHT_FILE_READ_ATTRIBUTES |
		SA_RIGHT_FILE_READ_EA |
		SA_RIGHT_FILE_READ_DATA },
	{
		GENERIC_RIGHT_WRITE_ACCESS,
		STD_RIGHT_SYNCHRONIZE_ACCESS |
		STD_RIGHT_READ_CONTROL_ACCESS |
		SA_RIGHT_FILE_WRITE_ATTRIBUTES |
		SA_RIGHT_FILE_WRITE_EA |
		SA_RIGHT_FILE_APPEND_DATA |
		SA_RIGHT_FILE_WRITE_DATA },
	{
		GENERIC_RIGHT_EXECUTE_ACCESS,
		STD_RIGHT_SYNCHRONIZE_ACCESS |
		STD_RIGHT_READ_CONTROL_ACCESS |
		SA_RIGHT_FILE_READ_ATTRIBUTES |
		SA_RIGHT_FILE_EXECUTE },
	{
		GENERIC_RIGHT_ALL_ACCESS,
		STD_RIGHT_SYNCHRONIZE_ACCESS |
		STD_RIGHT_WRITE_OWNER_ACCESS |
		STD_RIGHT_WRITE_DAC_ACCESS |
		STD_RIGHT_READ_CONTROL_ACCESS |
		STD_RIGHT_DELETE_ACCESS |
		SA_RIGHT_FILE_ALL_ACCESS },
	{ 0, 0 }
};

/*
 * Table for translating ZFS ACE flags to NT ACE flags.
 * The low four bits are the same, but not others.
 */
struct zaf2naf {
	uint16_t	za_flag;
	uint8_t		na_flag;
};
static const struct zaf2naf
smbfs_zaf2naf[] = {
	{ ACE_FILE_INHERIT_ACE,		OBJECT_INHERIT_ACE_FLAG },
	{ ACE_DIRECTORY_INHERIT_ACE,	CONTAINER_INHERIT_ACE_FLAG },
	{ ACE_NO_PROPAGATE_INHERIT_ACE,	NO_PROPAGATE_INHERIT_ACE_FLAG },
	{ ACE_INHERIT_ONLY_ACE,		INHERIT_ONLY_ACE_FLAG },
	{ ACE_INHERITED_ACE,		INHERITED_ACE_FLAG },
	{ ACE_SUCCESSFUL_ACCESS_ACE_FLAG, SUCCESSFUL_ACCESS_ACE_FLAG },
	{ ACE_FAILED_ACCESS_ACE_FLAG,	FAILED_ACCESS_ACE_FLAG },
	{ 0, 0 }
};

/*
 * Convert an NT SID to a string. Optionally return the
 * last sub-authority (or "relative ID" -- RID) in *ridp
 * and truncate the output string after the domain part.
 * If ridp==NULL, the output string is the whole SID,
 * including both the domain and RID.
 *
 * Return length written, or -1 on error.
 */
int
smbfs_sid2str(i_ntsid_t *sid,
	char *obuf, size_t osz, uint32_t *ridp)
{
	char *s = obuf;
	uint64_t auth = 0;
	uint_t i, n;
	uint32_t subs, *ip;

	n = snprintf(s, osz, "S-%u", sid->sid_revision);
	if (n > osz)
		return (-1);
	s += n; osz -= n;

	for (i = 0; i < 6; i++)
		auth = (auth << 8) | sid->sid_authority[i];
	n = snprintf(s, osz, "-%llu", (u_longlong_t)auth);
	if (n > osz)
		return (-1);
	s += n; osz -= n;

	subs = sid->sid_subauthcount;
	if (subs < 1 || subs > 15)
		return (-1);
	if (ridp)
		subs--;

	ip = &sid->sid_subauthvec[0];
	for (; subs; subs--, ip++) {
		n = snprintf(s, osz, "-%u", *ip);
		if (n > osz)
			return (-1);
		s += n; osz -= n;
	}
	if (ridp)
		*ridp = *ip;

	/* LINTED E_PTRDIFF_OVERFLOW */
	return (s - obuf);
}

/*
 * Our interface to the idmap service.
 *
 * The idmap API is _almost_ the same between
 * kernel and user-level.  But not quite...
 * Hope this improves readability below.
 */
#ifdef	_KERNEL

#define	I_getuidbysid(GH, SPP, RID, UIDP, SP) \
	kidmap_batch_getuidbysid(GH, SPP, RID, UIDP, SP)

#define	I_getgidbysid(GH, SPP, RID, GIDP, SP) \
	kidmap_batch_getgidbysid(GH, SPP, RID, GIDP, SP)

#define	I_getpidbysid(GH, SPP, RID, PIDP, ISUP, SP) \
	kidmap_batch_getpidbysid(GH, SPP, RID, PIDP, ISUP, SP)

#define	I_getmappings kidmap_get_mappings

#else /* _KERNEL */

#define	I_getuidbysid(GH, SPP, RID, UIDP, SP) \
	idmap_get_uidbysid(GH, SPP, RID, 0, UIDP, SP)

#define	I_getgidbysid(GH, SPP, RID, GIDP, SP) \
	idmap_get_gidbysid(GH, SPP, RID, 0, GIDP, SP)

#define	I_getpidbysid(GH, SPP, RID, PIDP, ISUP, SP) \
	idmap_get_pidbysid(GH, SPP, RID, 0, PIDP, ISUP, SP)

#define	I_getmappings idmap_get_mappings

#endif /* _KERNEL */


/*
 * The idmap request types, chosen so they also
 * match the values returned in mi_isuser.
 */
#define	IDM_TYPE_ANY	-1
#define	IDM_TYPE_GROUP	0
#define	IDM_TYPE_USER	1

/*
 * A sentinel value for mi_isuser (below) to indicate
 * that the SID is the well-known "Everyone" (S-1-1-0).
 * The idmap library only uses -1, 0, 1, so this value
 * is arbitrary but must not overlap w/ idmap values.
 * XXX: Could use a way for idmap to tell us when
 * it recognizes this well-known SID.
 */
#define	IDM_EVERYONE	11

struct mapinfo2uid {
	uid_t	mi_uid; /* or gid, or pid */
	int	mi_isuser; /* IDM_TYPE */
	idmap_stat mi_status;
};

/*
 * Build an idmap request.  Cleanup is
 * handled by the caller (error or not)
 */
static int
mkrq_idmap_sid2ux(
	idmap_get_handle_t *idmap_gh,
	struct mapinfo2uid *mip,
	i_ntsid_t *sid,
	int req_type)
{
	char strbuf[256];
	char *sid_prefix;
	uint32_t	rid;
	idmap_stat	idms;

	if (smbfs_sid2str(sid, strbuf, sizeof (strbuf), &rid) < 0)
		return (EINVAL);
	sid_prefix = strbuf;

	/*
	 * Give the "Everyone" group special treatment.
	 */
	if (strcmp(sid_prefix, "S-1-1") == 0 && rid == 0) {
		/* This is "Everyone" */
		mip->mi_uid = (uid_t)-1;
		mip->mi_isuser = IDM_EVERYONE;
		mip->mi_status = 0;
		return (0);
	}

	switch (req_type) {

	case IDM_TYPE_USER:
		mip->mi_isuser = req_type;
		idms = I_getuidbysid(idmap_gh, sid_prefix, rid,
		    &mip->mi_uid, &mip->mi_status);
		break;

	case IDM_TYPE_GROUP:
		mip->mi_isuser = req_type;
		idms = I_getgidbysid(idmap_gh, sid_prefix, rid,
		    &mip->mi_uid, &mip->mi_status);
		break;

	case IDM_TYPE_ANY:
		idms = I_getpidbysid(idmap_gh, sid_prefix, rid,
		    &mip->mi_uid, &mip->mi_isuser, &mip->mi_status);
		break;

	default:
		idms = IDMAP_ERR_OTHER;
		break;
	}

	if (idms != IDMAP_SUCCESS)
		return (EINVAL);

	return (0);
}

/*
 * Convert an NT ACE to a ZFS ACE.
 * ACE type was already validated.
 */
static void
ntace2zace(ace_t *zacep, i_ntace_t *ntace, struct mapinfo2uid *mip)
{
	const struct zaf2naf *znaf;
	uid_t zwho;
	uint32_t zamask;
	uint16_t zflags;

	/*
	 * Set the "ID type" flags in the ZFS ace flags.
	 */
	zflags = 0;
	switch (mip->mi_isuser) {
	case IDM_EVERYONE:
		zflags = ACE_EVERYONE;
		zwho = (uid_t)-1;
		break;

	case IDM_TYPE_GROUP: /* it's a GID */
		zflags = ACE_IDENTIFIER_GROUP;
		zwho = mip->mi_uid;
		break;

	default:
	case IDM_TYPE_USER: /* it's a UID */
		zflags = 0;
		zwho = mip->mi_uid;
		break;
	}

	/*
	 * Translate NT ACE flags to ZFS ACE flags.
	 */
	for (znaf = smbfs_zaf2naf; znaf->za_flag; znaf++)
		if (ntace->ace_hdr.ace_flags & znaf->na_flag)
			zflags |= znaf->za_flag;

	/*
	 * The "normal" access mask bits are the same, but
	 * if the ACE has any GENERIC_RIGHT_... convert those
	 * to specific rights.  GENERIC bits are rarely seen,
	 * but reportedly can happen with inherit-only ACEs.
	 */
	zamask = ntace->ace_v2.ace_rights & ACE_ALL_PERMS;
	if (ntace->ace_v2.ace_rights & GENERIC_RIGHTS_MASK) {
		const struct gen2fsr *gf;
		for (gf = smbfs_gen2fsr; gf->gf_generic; gf++)
			if (ntace->ace_v2.ace_rights & gf->gf_generic)
				zamask |= gf->gf_specific;
	}

	/*
	 * Fill in the ZFS-style ACE
	 */
	zacep->a_who = zwho;
	zacep->a_access_mask = zamask;
	zacep->a_flags = zflags;
	zacep->a_type = ntace->ace_hdr.ace_type;
}

/*
 * Convert an internal SD to a ZFS-style ACL.
 * Note optional args: vsa/acl, uidp, gidp.
 *
 * This makes two passes over the SD, the first building a
 * "batch" request for idmap with results in mapinfo, the
 * second building a ZFS-style ACL using the idmap results.
 */
int
smbfs_acl_sd2zfs(
	i_ntsd_t *sd,
#if defined(_KERNEL) || defined(_FAKE_KERNEL)
	vsecattr_t *acl_info,
#else /* _KERNEL */
	acl_t *acl_info,
#endif /* _KERNEL */
	uid_t *uidp, gid_t *gidp)
{
	struct mapinfo2uid *mip, *mapinfo = NULL;
	int error, i, mapcnt, zacecnt, zacl_size;
	ace_t *zacep0, *zacep;
	uid_t own_uid = (uid_t)-1;
	gid_t own_gid = (gid_t)-1;
	i_ntacl_t *ntacl;
	i_ntace_t **ntacep;
	idmap_get_handle_t *idmap_gh = NULL;
	idmap_stat	idms;

	/*
	 * sanity checks
	 */
	if (acl_info) {
#if !defined(_KERNEL) && !defined(_FAKE_KERNEL)
		if (acl_info->acl_type != ACE_T ||
		    acl_info->acl_aclp != NULL ||
		    acl_info->acl_entry_size != sizeof (ace_t))
			return (EINVAL);
#endif /* !_KERNEL */
		if ((sd->sd_flags & SD_DACL_PRESENT) == 0)
			return (EINVAL);
	}

	/*
	 * How many SID mappings will we need?
	 */
	mapcnt = 0;
	if (sd->sd_owner)
		mapcnt++;
	if (sd->sd_group)
		mapcnt++;
	if ((sd->sd_flags & SD_SACL_PRESENT) &&
	    (sd->sd_sacl != NULL))
		mapcnt += sd->sd_sacl->acl_acecount;
	if ((sd->sd_flags & SD_DACL_PRESENT) &&
	    (sd->sd_dacl != NULL))
		mapcnt += sd->sd_dacl->acl_acecount;
	if (mapcnt == 0) {
		/*
		 * We have a NULL DACL, SACL, and don't
		 * have an owner or group, so there's no
		 * idmap work to do.  This is very rare,
		 * so rather than complicate things below,
		 * pretend we need one mapping slot.
		 */
		mapcnt = 1;
	}

	mapinfo = MALLOC(mapcnt * sizeof (*mapinfo));
	if (mapinfo == NULL) {
		error = ENOMEM;
		goto errout;
	}
	bzero(mapinfo, mapcnt * sizeof (*mapinfo));


	/*
	 * Get an imap "batch" request handle.
	 */
#ifdef	_KERNEL
	idmap_gh = kidmap_get_create(curproc->p_zone);
#else /* _KERNEL */
	idms = idmap_get_create(&idmap_gh);
	if (idms != IDMAP_SUCCESS) {
		error = ENOTACTIVE;
		goto errout;
	}
#endif /* _KERNEL */

	/*
	 * Build our request to the idmap deamon,
	 * getting Unix IDs for every SID.
	 */
	mip = mapinfo;
	if (sd->sd_owner) {
		error = mkrq_idmap_sid2ux(idmap_gh, mip,
		    sd->sd_owner, IDM_TYPE_USER);
		if (error)
			goto errout;
		mip++;
	}
	if (sd->sd_group) {
		error = mkrq_idmap_sid2ux(idmap_gh, mip,
		    sd->sd_group, IDM_TYPE_GROUP);
		if (error)
			goto errout;
		mip++;
	}
	if ((sd->sd_flags & SD_SACL_PRESENT) &&
	    (sd->sd_sacl != NULL)) {
		ntacl = sd->sd_sacl;
		ntacep = &ntacl->acl_acevec[0];
		for (i = 0; i < ntacl->acl_acecount; i++) {
			error = mkrq_idmap_sid2ux(idmap_gh, mip,
			    (*ntacep)->ace_v2.ace_sid, IDM_TYPE_ANY);
			if (error)
				goto errout;
			ntacep++;
			mip++;
		}
	}
	if ((sd->sd_flags & SD_DACL_PRESENT) &&
	    (sd->sd_dacl != NULL)) {
		ntacl = sd->sd_dacl;
		ntacep = &ntacl->acl_acevec[0];
		for (i = 0; i < ntacl->acl_acecount; i++) {
			error = mkrq_idmap_sid2ux(idmap_gh, mip,
			    (*ntacep)->ace_v2.ace_sid, IDM_TYPE_ANY);
			if (error)
				goto errout;
			ntacep++;
			mip++;
		}
	}

	if (mip != mapinfo) {
		idms = I_getmappings(idmap_gh);
		if (idms != IDMAP_SUCCESS) {
			/* creative error choice */
			error = EIDRM;
			goto errout;
		}
	}

	/*
	 * With any luck, we now have Unix user/group IDs
	 * for every Windows SID in the security descriptor.
	 * The remaining work is just format conversion.
	 */
	mip = mapinfo;
	if (sd->sd_owner) {
		own_uid = mip->mi_uid;
		mip++;
	}
	if (sd->sd_group) {
		own_gid = mip->mi_uid;
		mip++;
	}

	if (uidp)
		*uidp = own_uid;
	if (gidp)
		*gidp = own_gid;

	if (acl_info == NULL) {
		/* Caller only wanted uid/gid */
		goto done;
	}

	/*
	 * Build the ZFS-style ACL
	 * First, allocate the most ZFS ACEs we'll need.
	 */
	zacecnt = 0;
	if ((sd->sd_flags & SD_SACL_PRESENT) &&
	    (sd->sd_sacl != NULL))
		zacecnt += sd->sd_sacl->acl_acecount;

	/* NB, have: (sd->sd_flags & SD_DACL_PRESENT) */
	if ((sd->sd_dacl != NULL) &&
	    (sd->sd_dacl->acl_acecount > 0)) {
		zacecnt += sd->sd_dacl->acl_acecount;
	} else {
		/*
		 * DACL is NULL or empty. Either way,
		 * we'll need to add a ZFS ACE below.
		 */
		zacecnt++;
	}
	zacl_size = zacecnt * sizeof (ace_t);
	zacep0 = MALLOC(zacl_size);
	if (zacep0 == NULL) {
		error = ENOMEM;
		goto errout;
	}
	zacep = zacep0;

	if ((sd->sd_flags & SD_SACL_PRESENT) &&
	    (sd->sd_sacl != NULL)) {
		ntacl = sd->sd_sacl;
		ntacep = &ntacl->acl_acevec[0];
		for (i = 0; i < ntacl->acl_acecount; i++) {
			ntace2zace(zacep, *ntacep, mip);
			zacep++;
			ntacep++;
			mip++;
		}
	}

	/* NB, have: (sd->sd_flags & SD_DACL_PRESENT) */
	if (sd->sd_dacl != NULL) {
		ntacl = sd->sd_dacl;
		ntacep = &ntacl->acl_acevec[0];
		for (i = 0; i < ntacl->acl_acecount; i++) {
			ntace2zace(zacep, *ntacep, mip);
			zacep++;
			ntacep++;
			mip++;
		}
	}
	if (sd->sd_dacl == NULL) {
		/*
		 * The SD has a NULL DACL.  That means
		 * everyone@, full-control
		 */
		zacep->a_who = (uid_t)-1;
		zacep->a_access_mask = ACE_ALL_PERMS;
		zacep->a_flags = ACE_EVERYONE;
		zacep->a_type = ACCESS_ALLOWED_ACE_TYPE;
	} else if (sd->sd_dacl->acl_acecount == 0) {
		/*
		 * The SD has an Empty DACL.  We need
		 * at least one ACE, so add one giving
		 * the owner the usual implied access.
		 */
		zacep->a_who = (uid_t)-1;
		zacep->a_access_mask = ACE_READ_ATTRIBUTES | \
		    ACE_READ_ACL | ACE_WRITE_ACL;
		zacep->a_flags = ACE_OWNER;
		zacep->a_type = ACCESS_ALLOWED_ACE_TYPE;
	}

#if defined(_KERNEL) || defined(_FAKE_KERNEL)
	acl_info->vsa_aclcnt = zacecnt;
	acl_info->vsa_aclentp = zacep0;
	acl_info->vsa_aclentsz = zacl_size;
#else	/* _KERNEL */
	acl_info->acl_cnt = zacecnt;
	acl_info->acl_aclp = zacep0;
#endif	/* _KERNEL */

done:
	error = 0;

errout:
	if (mapinfo != NULL)
		FREESZ(mapinfo, mapcnt * sizeof (*mapinfo));
#ifdef	_KERNEL
	if (idmap_gh != NULL)
		kidmap_get_destroy(idmap_gh);
#else /* _KERNEL */
	if (idmap_gh != NULL)
		idmap_get_destroy(idmap_gh);
#endif /* _KERNEL */

	return (error);
}


/*
 * ================================================================
 * Support for ACL store, including conversions
 * from NFSv4-style ACLs to Windows ACLs.
 * ================================================================
 */

/*
 * Convert a "sid-prefix" string plus RID into an NT SID.
 *
 * If successful, sets *osid and returns zero,
 * otherwise returns an errno value.
 */
int
smbfs_str2sid(const char *sid_prefix, uint32_t *ridp, i_ntsid_t **osidp)
{
	i_ntsid_t *sid = NULL;
	u_longlong_t auth = 0;
	ulong_t sa;
	uint8_t sacnt;
	const char *p;
	char *np;
	size_t size;
	int i;
	int err;

	if (sid_prefix == NULL)
		return (EINVAL);

	p = sid_prefix;
	if (strncmp(p, "S-1-", 4) != 0)
		return (EINVAL);
	p += 4;

	/* Parse the "authority" */
#ifdef	_KERNEL
	err = ddi_strtoull(p, &np, 10, &auth);
	if (err != 0)
		return (err);
#else	/* _KERNEL */
	auth = strtoull(p, &np, 10);
	if (p == np)
		return (EINVAL);
#endif	/* _KERNEL */

	/*
	 * Count the sub-authorities.  Here, np points to
	 * the "-" before the first sub-authority.
	 */
	sacnt = 0;
	for (p = np; *p; p++) {
		if (*p == '-')
			sacnt++;
	}
	if (ridp != NULL)
		sacnt++;

	/* Allocate the internal SID. */
	size = I_SID_SIZE(sacnt);
	sid = MALLOC(size);
	if (sid == NULL)
		return (ENOMEM);
	bzero(sid, size);

	/* Fill it in. */
	sid->sid_revision = 1;
	sid->sid_subauthcount = sacnt;
	for (i = 5; i >= 0; i--) {
		sid->sid_authority[i] = auth & 0xFF;
		auth = auth >> 8;
	}

	err = EINVAL;
	if (ridp != NULL)
		sacnt--; /* Last SA not from string */
	p = np;
	for (i = 0; i < sacnt; i++) {
		if (*p != '-') {
			err = EINVAL;
			goto out;
		}
		p++;
#if defined(_KERNEL) || defined(_FAKE_KERNEL)
		err = ddi_strtoul(p, &np, 10, &sa);
		if (err != 0)
			goto out;
#else	/* _KERNEL */
		sa = strtoul(p, &np, 10);
		if (p == np) {
			err = EINVAL;
			goto out;
		}
#endif	/* _KERNEL */
		sid->sid_subauthvec[i] = (uint32_t)sa;
		p = np;
	}
	if (*p != '\0')
		goto out;
	if (ridp != NULL)
		sid->sid_subauthvec[i] = *ridp;
	err = 0;

out:
	if (err)
		FREESZ(sid, size);
	else
		*osidp = sid;

	return (err);
}

/*
 * The idmap API is _almost_ the same between
 * kernel and user-level.  But not quite...
 * Hope this improves readability below.
 */
#ifdef	_KERNEL

#define	I_getsidbyuid(GH, UID, SPP, RP, ST) \
	kidmap_batch_getsidbyuid(GH, UID, SPP, RP, ST)

#define	I_getsidbygid(GH, GID, SPP, RP, ST) \
	kidmap_batch_getsidbygid(GH, GID, SPP, RP, ST)

#else /* _KERNEL */

#define	I_getsidbyuid(GH, UID, SPP, RP, ST) \
	idmap_get_sidbyuid(GH, UID, 0, SPP, RP, ST)

#define	I_getsidbygid(GH, GID, SPP, RP, ST) \
	idmap_get_sidbygid(GH, GID, 0, SPP, RP, ST)

#endif /* _KERNEL */

struct mapinfo2sid {
	/* Yet another kernel vs. user difference. */
#ifdef	_KERNEL
	const char *mi_dsid;	/* domain SID */
#else /* _KERNEL */
	char *mi_dsid;
#endif /* _KERNEL */
	uint32_t mi_rid;	/* relative ID */
	idmap_stat mi_status;
};

/*
 * Build an idmap request.  Cleanup is
 * handled by the caller (error or not)
 */
static int
mkrq_idmap_ux2sid(
	idmap_get_handle_t *idmap_gh,
	struct mapinfo2sid *mip,
	uid_t	uid, /* or gid */
	int req_type)
{
	idmap_stat	idms;

	switch (req_type) {

	case IDM_TYPE_USER:
		if (uid == (uid_t)-1)
			return (EINVAL);
		idms = I_getsidbyuid(idmap_gh, uid,
		    &mip->mi_dsid, &mip->mi_rid, &mip->mi_status);
		break;

	case IDM_TYPE_GROUP:
		if (uid == (uid_t)-1)
			return (EINVAL);
		idms = I_getsidbygid(idmap_gh, uid,
		    &mip->mi_dsid, &mip->mi_rid, &mip->mi_status);
		break;

	case IDM_EVERYONE:
		mip->mi_dsid = "S-1-1";
		mip->mi_rid = 0;
		mip->mi_status = 0;
		idms = IDMAP_SUCCESS;
		break;

	default:
		idms = IDMAP_ERR_OTHER;
		break;
	}

	if (idms != IDMAP_SUCCESS)
		return (EINVAL);

	return (0);
}

/*
 * Convert a ZFS ACE to an NT ACE.
 * ACE type was already validated.
 */
static int
zace2ntace(i_ntace_t **ntacep, ace_t *zacep, struct mapinfo2sid *mip)
{
	const struct zaf2naf *znaf;
	uint8_t aflags;
	uint16_t alloc_size;
	uint32_t rights;
	i_ntace_t *ntace = NULL;
	i_ntsid_t *sid = NULL;
	int error;

	if (mip->mi_dsid == NULL || mip->mi_status != 0) {
		return (EINVAL);
	}

	/*
	 * Translate ZFS ACE flags to NT ACE flags.
	 */
	aflags = 0;
	for (znaf = smbfs_zaf2naf; znaf->za_flag; znaf++)
		if (zacep->a_flags & znaf->za_flag)
			aflags |= znaf->na_flag;

	/*
	 * The access rights bits are OK as-is.
	 */
	rights = zacep->a_access_mask;

	/*
	 * Make sure we can get the SID.
	 * Note: allocates sid.
	 */
	error = smbfs_str2sid(mip->mi_dsid, &mip->mi_rid, &sid);
	if (error)
		return (error);

	/*
	 * Allocate the NT ACE and fill it in.
	 */
	alloc_size = sizeof (i_ntace_v2_t);
	if ((ntace = MALLOC(alloc_size)) == NULL) {
		ifree_sid(sid);
		return (ENOMEM);
	}
	bzero(ntace, alloc_size);

	ntace->ace_hdr.ace_type = zacep->a_type;
	ntace->ace_hdr.ace_flags = aflags;
	ntace->ace_hdr.ace_size = alloc_size;
	ntace->ace_v2.ace_rights = rights;
	ntace->ace_v2.ace_sid = sid;

	*ntacep = ntace;
	return (0);
}

/*
 * Convert a ZFS-style ACL to an internal SD.
 * Set owner/group too if selector indicates.
 * Always need to pass uid+gid, either the new
 * (when setting them) or existing, so that any
 * owner@ or group@ ACEs can be translated.
 *
 * This makes two passes over the ZFS ACL.  The first builds a
 * "batch" request for idmap with results in mapinfo, and the
 * second builds the NT SD using the idmap SID results.
 */
int
smbfs_acl_zfs2sd(
#if defined(_KERNEL) || defined(_FAKE_KERNEL)
	vsecattr_t *acl_info,
#else /* _KERNEL */
	acl_t *acl_info,
#endif /* _KERNEL */
	uid_t own_uid,
	gid_t own_gid,
	uint32_t selector,
	i_ntsd_t **sdp)
{
	struct mapinfo2sid *mip, *mip_acl, *mapinfo = NULL;
	int aclsz, error, i, mapcnt;
	int dacl_acecnt = 0;
	int sacl_acecnt = 0;
	int zacecnt = 0;
	ace_t *zacevec = NULL;
	ace_t *zacep;
	i_ntsd_t *sd = NULL;
	i_ntacl_t *acl = NULL;
	i_ntace_t **acep = NULL;
	idmap_get_handle_t *idmap_gh = NULL;
	idmap_stat	idms;

	/*
	 * First, get all the UID+GID to SID mappings.
	 * How many?  Also sanity checks.
	 */
	mapcnt = 0;
	if (selector & OWNER_SECURITY_INFORMATION) {
		if (own_uid == (uid_t)-1)
			return (EINVAL);
		mapcnt++;
	}
	if (selector & GROUP_SECURITY_INFORMATION) {
		if (own_gid == (gid_t)-1)
			return (EINVAL);
		mapcnt++;
	}
	if (selector & (DACL_SECURITY_INFORMATION |
	    SACL_SECURITY_INFORMATION)) {
		if (acl_info == NULL)
			return (EINVAL);
		if (own_uid == (uid_t)-1)
			return (EINVAL);
		if (own_gid == (gid_t)-1)
			return (EINVAL);
#if defined(_KERNEL) || defined(_FAKE_KERNEL)
		if ((acl_info->vsa_mask & VSA_ACE) == 0)
			return (EINVAL);
		zacecnt = acl_info->vsa_aclcnt;
		zacevec = acl_info->vsa_aclentp;
#else	/* _KERNEL */
		if (acl_info->acl_type != ACE_T ||
		    acl_info->acl_entry_size != sizeof (ace_t))
			return (EINVAL);
		zacecnt = acl_info->acl_cnt;
		zacevec = acl_info->acl_aclp;
#endif	/* _KERNEL */
		if (zacecnt == 0 || zacevec == NULL)
			return (EINVAL);
		mapcnt += zacecnt;
	}
	if (mapcnt == 0)
		return (EINVAL);
	mapinfo = MALLOC(mapcnt * sizeof (*mapinfo));
	if (mapinfo == NULL)
		return (ENOMEM);
	bzero(mapinfo, mapcnt * sizeof (*mapinfo));
	/* no more returns until errout */

	/*
	 * Get an imap "batch" request handle.
	 */
#ifdef	_KERNEL
	idmap_gh = kidmap_get_create(curproc->p_zone);
#else /* _KERNEL */
	idms = idmap_get_create(&idmap_gh);
	if (idms != IDMAP_SUCCESS) {
		error = ENOTACTIVE;
		goto errout;
	}
#endif /* _KERNEL */

	/*
	 * Build our request to the idmap deamon,
	 * getting SIDs for every Unix UID/GID.
	 * Also count DACL and SACL ACEs here.
	 */
	mip = mapinfo;
	if (selector & OWNER_SECURITY_INFORMATION) {
		error = mkrq_idmap_ux2sid(idmap_gh, mip,
		    own_uid, IDM_TYPE_USER);
		if (error)
			goto errout;
		mip++;
	}
	if (selector & GROUP_SECURITY_INFORMATION) {
		error = mkrq_idmap_ux2sid(idmap_gh, mip,
		    own_gid, IDM_TYPE_GROUP);
		if (error)
			goto errout;
		mip++;
	}
	if (selector & (DACL_SECURITY_INFORMATION |
	    SACL_SECURITY_INFORMATION)) {
		int rqtype;
		uid_t uid;

		zacep = zacevec;
		for (i = 0; i < zacecnt; i++) {

			switch (zacep->a_type) {
			case ACE_ACCESS_ALLOWED_ACE_TYPE:
			case ACE_ACCESS_DENIED_ACE_TYPE:
				dacl_acecnt++;
				break;
			case ACE_SYSTEM_AUDIT_ACE_TYPE:
			case ACE_SYSTEM_ALARM_ACE_TYPE:
				sacl_acecnt++;
				break;
			/* other types todo */
			}

			if (zacep->a_flags & ACE_EVERYONE) {
				rqtype = IDM_EVERYONE;
				uid = (uid_t)-1;
			} else if (zacep->a_flags & ACE_GROUP) {
				/* owning group (a_who = -1) */
				rqtype = IDM_TYPE_GROUP;
				uid = (uid_t)own_gid;
			} else if (zacep->a_flags & ACE_OWNER) {
				/* owning user (a_who = -1) */
				rqtype = IDM_TYPE_USER;
				uid = (uid_t)own_uid;
			} else if (zacep->a_flags & ACE_IDENTIFIER_GROUP) {
				/* regular group */
				rqtype = IDM_TYPE_GROUP;
				uid = zacep->a_who;
			} else {
				rqtype = IDM_TYPE_USER;
				uid = zacep->a_who;
			}

			error = mkrq_idmap_ux2sid(idmap_gh, mip, uid, rqtype);
			if (error)
				goto errout;
			zacep++;
			mip++;
		}
	}

	idms = I_getmappings(idmap_gh);
	if (idms != IDMAP_SUCCESS) {
		/* creative error choice */
		error = EIDRM;
		goto errout;
	}

	/*
	 * With any luck, we now have a Windows SID for
	 * every Unix UID or GID in the NFS/ZFS ACL.
	 * The remaining work is just format conversion,
	 * memory allocation, etc.
	 */
	if ((sd = MALLOC(sizeof (*sd))) == NULL) {
		error = ENOMEM;
		goto errout;
	}
	bzero(sd, sizeof (*sd));
	sd->sd_revision = NT_SD_REVISION;

	mip = mapinfo;
	if (selector & OWNER_SECURITY_INFORMATION) {
		error = smbfs_str2sid(mip->mi_dsid, &mip->mi_rid,
		    &sd->sd_owner);
		mip++;
	}
	if (selector & GROUP_SECURITY_INFORMATION) {
		error = smbfs_str2sid(mip->mi_dsid, &mip->mi_rid,
		    &sd->sd_group);
		mip++;
	}

	/*
	 * If setting both DACL and SACL, we will
	 * make two passes starting here in mapinfo.
	 */
	mip_acl = mip;

	if (selector & DACL_SECURITY_INFORMATION) {
		/*
		 * Caller wants to set the DACL.
		 */
		aclsz = I_ACL_SIZE(dacl_acecnt);
		if ((acl = MALLOC(aclsz)) == NULL) {
			error = ENOMEM;
			goto errout;
		}
		bzero(acl, aclsz);

		acl->acl_revision = NT_ACL_REVISION;
		acl->acl_acecount = (uint16_t)dacl_acecnt;
		acep = &acl->acl_acevec[0];

		/* 1st pass - scan for DACL ACE types. */
		mip = mip_acl;
		zacep = zacevec;
		for (i = 0; i < zacecnt; i++) {

			switch (zacep->a_type) {
			case ACE_ACCESS_ALLOWED_ACE_TYPE:
			case ACE_ACCESS_DENIED_ACE_TYPE:
				error = zace2ntace(acep, zacep, mip);
				if (error != 0)
					goto errout;
				acep++;
				break;

			case ACE_SYSTEM_AUDIT_ACE_TYPE:
			case ACE_SYSTEM_ALARM_ACE_TYPE:
				break;
			/* other types todo */
			}
			zacep++;
			mip++;
		}
		sd->sd_dacl = acl;
		acl = NULL;
		sd->sd_flags |= SD_DACL_PRESENT;
	}

	if (selector & SACL_SECURITY_INFORMATION) {
		/*
		 * Caller wants to set the SACL.
		 */
		aclsz = I_ACL_SIZE(sacl_acecnt);
		if ((acl = MALLOC(aclsz)) == NULL) {
			error = ENOMEM;
			goto errout;
		}
		bzero(acl, aclsz);

		acl->acl_revision = NT_ACL_REVISION;
		acl->acl_acecount = (uint16_t)sacl_acecnt;
		acep = &acl->acl_acevec[0];

		/* 2nd pass - scan for SACL ACE types. */
		mip = mip_acl;
		zacep = zacevec;
		for (i = 0; i < zacecnt; i++) {

			switch (zacep->a_type) {
			case ACE_ACCESS_ALLOWED_ACE_TYPE:
			case ACE_ACCESS_DENIED_ACE_TYPE:
				break;

			case ACE_SYSTEM_AUDIT_ACE_TYPE:
			case ACE_SYSTEM_ALARM_ACE_TYPE:
				error = zace2ntace(acep, zacep, mip);
				if (error != 0)
					goto errout;
				acep++;
				break;
			/* other types todo */
			}
			zacep++;
			mip++;
		}
		sd->sd_sacl = acl;
		acl = NULL;
		sd->sd_flags |= SD_SACL_PRESENT;
	}

	*sdp = sd;
	error = 0;

errout:
	if (error != 0) {
		if (acl != NULL)
			ifree_acl(acl);
		if (sd != NULL)
			smbfs_acl_free_sd(sd);
	}
	if (mapinfo != NULL)
		FREESZ(mapinfo, mapcnt * sizeof (*mapinfo));
#ifdef	_KERNEL
	if (idmap_gh != NULL)
		kidmap_get_destroy(idmap_gh);
#else /* _KERNEL */
	if (idmap_gh != NULL)
		idmap_get_destroy(idmap_gh);
#endif /* _KERNEL */

	return (error);
}