summaryrefslogtreecommitdiff
path: root/usr/src/lib/smbsrv/libmlsvc/common/smb_share.c
blob: d42622dfcaeea50bd62b5b8c41fea29e99c1b3e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
/*
 * 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.
 */

/*
 * SMB/CIFS share cache implementation.
 */

#include <errno.h>
#include <synch.h>
#include <stdlib.h>
#include <strings.h>
#include <syslog.h>
#include <thread.h>
#include <pthread.h>
#include <assert.h>
#include <libshare.h>
#include <libzfs.h>
#include <priv_utils.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <pwd.h>
#include <signal.h>

#include <smbsrv/libsmb.h>
#include <smbsrv/libsmbns.h>
#include <smbsrv/libmlsvc.h>
#include <smbsrv/smb_share.h>
#include <smbsrv/smb.h>
#include <mlsvc.h>

#define	SMB_SHR_ERROR_THRESHOLD		3

#define	SMB_SHR_CSC_BUFSZ		64

static struct {
	char *value;
	uint32_t flag;
} cscopt[] = {
	{ "disabled",	SMB_SHRF_CSC_DISABLED },
	{ "manual",	SMB_SHRF_CSC_MANUAL },
	{ "auto",	SMB_SHRF_CSC_AUTO },
	{ "vdo",	SMB_SHRF_CSC_VDO }
};

/*
 * Cache functions and vars
 */
#define	SMB_SHR_HTAB_SZ			1024

/*
 * Cache handle
 *
 * Shares cache is a hash table.
 *
 * sc_cache		pointer to hash table handle
 * sc_cache_lck		synchronize cache read/write accesses
 * sc_state		cache state machine values
 * sc_nops		number of inflight/pending cache operations
 * sc_mtx		protects handle fields
 */
typedef struct smb_shr_cache {
	HT_HANDLE	*sc_cache;
	rwlock_t	sc_cache_lck;
	mutex_t		sc_mtx;
	cond_t		sc_cv;
	uint32_t	sc_state;
	uint32_t	sc_nops;
} smb_shr_cache_t;

/*
 * Cache states
 */
#define	SMB_SHR_CACHE_STATE_NONE	0
#define	SMB_SHR_CACHE_STATE_CREATED	1
#define	SMB_SHR_CACHE_STATE_DESTROYING	2

/*
 * Cache lock modes
 */
#define	SMB_SHR_CACHE_RDLOCK	0
#define	SMB_SHR_CACHE_WRLOCK	1

static smb_shr_cache_t smb_shr_cache;

static uint32_t smb_shr_cache_create(void);
static void smb_shr_cache_destroy(void);
static uint32_t smb_shr_cache_lock(int);
static void smb_shr_cache_unlock(void);
static int smb_shr_cache_count(void);
static smb_share_t *smb_shr_cache_iterate(smb_shriter_t *);

static smb_share_t *smb_shr_cache_findent(char *);
static uint32_t smb_shr_cache_addent(smb_share_t *);
static void smb_shr_cache_delent(char *);
static void smb_shr_cache_freent(HT_ITEM *);

/*
 * sharemgr functions
 */
static void *smb_shr_sa_loadall(void *);
static void smb_shr_sa_loadgrp(sa_group_t);
static uint32_t smb_shr_sa_load(sa_share_t, sa_resource_t);
static uint32_t smb_shr_sa_loadbyname(char *);
static uint32_t smb_shr_sa_get(sa_share_t, sa_resource_t, smb_share_t *);

/*
 * .ZFS management functions
 */
static void smb_shr_zfs_add(smb_share_t *);
static void smb_shr_zfs_remove(smb_share_t *);
static void smb_shr_zfs_rename(smb_share_t *, smb_share_t *);

/*
 * share publishing
 */
#define	SMB_SHR_PUBLISH		0
#define	SMB_SHR_UNPUBLISH	1

typedef struct smb_shr_pitem {
	list_node_t	spi_lnd;
	char		spi_name[MAXNAMELEN];
	char		spi_container[MAXPATHLEN];
	char		spi_op;
} smb_shr_pitem_t;

/*
 * publish queue states
 */
#define	SMB_SHR_PQS_NOQUEUE	0
#define	SMB_SHR_PQS_READY	1	/* the queue is ready */
#define	SMB_SHR_PQS_PUBLISHING	2	/* publisher thread is running */
#define	SMB_SHR_PQS_STOPPING	3

/*
 * share publishing queue
 */
typedef struct smb_shr_pqueue {
	list_t		spq_list;
	mutex_t		spq_mtx;
	cond_t		spq_cv;
	uint32_t	spq_state;
} smb_shr_pqueue_t;

static smb_shr_pqueue_t ad_queue;

static int smb_shr_publisher_start(void);
static void smb_shr_publisher_stop(void);
static void smb_shr_publisher_send(smb_ads_handle_t *, list_t *, const char *);
static void smb_shr_publisher_queue(const char *, const char *, char);
static void *smb_shr_publisher(void *);
static void smb_shr_publisher_flush(list_t *);
static void smb_shr_publish(const char *, const char *);
static void smb_shr_unpublish(const char *, const char *);

/*
 * Utility/helper functions
 */
static uint32_t smb_shr_lookup(char *, smb_share_t *);
static uint32_t smb_shr_addipc(void);
static void smb_shr_set_oemname(smb_share_t *);
static int smb_shr_enable_all_privs(void);
static int smb_shr_expand_subs(char **, smb_share_t *, smb_execsub_info_t *);
static char **smb_shr_tokenize_cmd(char *);
static void smb_shr_sig_abnormal_term(int);
static void smb_shr_sig_child(int);
static void smb_shr_get_exec_info(void);
static void smb_shr_set_exec_flags(smb_share_t *);
static void smb_shr_sa_guest_option(const char *, smb_share_t *);


/*
 * libshare handle and synchronization
 */
typedef struct smb_sa_handle {
	sa_handle_t	sa_handle;
	mutex_t		sa_mtx;
	boolean_t	sa_in_service;
} smb_sa_handle_t;

static smb_sa_handle_t smb_sa_handle;

static int smb_shr_exec_flags;
static char smb_shr_exec_map[MAXPATHLEN];
static char smb_shr_exec_unmap[MAXPATHLEN];
static mutex_t smb_shr_exec_mtx;

/*
 * Semaphore held during temporary, process-wide changes
 * such as process privileges.  It is a seamaphore and
 * not a mutex so a child of fork can reset it.
 */
static sema_t smb_proc_sem = DEFAULTSEMA;

/*
 * Creates and initializes the cache and starts the publisher
 * thread.
 */
int
smb_shr_start(void)
{
	(void) mutex_lock(&smb_sa_handle.sa_mtx);
	smb_sa_handle.sa_in_service = B_TRUE;
	(void) mutex_unlock(&smb_sa_handle.sa_mtx);

	if (smb_shr_cache_create() != NERR_Success)
		return (ENOMEM);

	if (smb_shr_addipc() != NERR_Success)
		return (ENOMEM);

	return (smb_shr_publisher_start());
}

void
smb_shr_stop(void)
{
	smb_shr_cache_destroy();
	smb_shr_publisher_stop();

	(void) mutex_lock(&smb_sa_handle.sa_mtx);
	smb_sa_handle.sa_in_service = B_FALSE;

	if (smb_sa_handle.sa_handle != NULL) {
		sa_fini(smb_sa_handle.sa_handle);
		smb_sa_handle.sa_handle = NULL;
	}

	(void) mutex_unlock(&smb_sa_handle.sa_mtx);
}

/*
 * Get a handle and exclusive access to the libshare API.
 */
sa_handle_t
smb_shr_sa_enter(void)
{
	(void) mutex_lock(&smb_sa_handle.sa_mtx);
	if (!smb_sa_handle.sa_in_service) {
		(void) mutex_unlock(&smb_sa_handle.sa_mtx);
		return (NULL);
	}

	if (smb_sa_handle.sa_handle == NULL) {
		smb_sa_handle.sa_handle = sa_init(SA_INIT_SHARE_API);
		if (smb_sa_handle.sa_handle == NULL) {
			syslog(LOG_ERR, "share: failed to get libshare handle");
			(void) mutex_unlock(&smb_sa_handle.sa_mtx);
			return (NULL);
		}
	}

	return (smb_sa_handle.sa_handle);
}

/*
 * Release exclusive access to the libshare API.
 */
void
smb_shr_sa_exit(void)
{
	(void) mutex_unlock(&smb_sa_handle.sa_mtx);
}

/*
 * Launches a thread to populate the share cache by share information
 * stored in sharemgr
 */
int
smb_shr_load(void)
{
	pthread_t load_thr;
	pthread_attr_t tattr;
	int rc;

	(void) pthread_attr_init(&tattr);
	(void) pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
	rc = pthread_create(&load_thr, &tattr, smb_shr_sa_loadall, 0);
	(void) pthread_attr_destroy(&tattr);

	smb_shr_get_exec_info();

	return (rc);
}

/*
 * Return the total number of shares
 */
int
smb_shr_count(void)
{
	int n_shares = 0;

	if (smb_shr_cache_lock(SMB_SHR_CACHE_RDLOCK) == NERR_Success) {
		n_shares = smb_shr_cache_count();
		smb_shr_cache_unlock();
	}

	return (n_shares);
}

/*
 * smb_shr_iterinit
 *
 * Initialize given iterator for traversing hash table.
 */
void
smb_shr_iterinit(smb_shriter_t *shi)
{
	bzero(shi, sizeof (smb_shriter_t));
	shi->si_first = B_TRUE;
}

/*
 * smb_shr_iterate
 *
 * Iterate on the shares in the hash table. The iterator must be initialized
 * before the first iteration. On subsequent calls, the iterator must be
 * passed unchanged.
 *
 * Returns NULL on failure or when all shares are visited, otherwise
 * returns information of visited share.
 */
smb_share_t *
smb_shr_iterate(smb_shriter_t *shi)
{
	smb_share_t *share = NULL;
	smb_share_t *cached_si;

	if (shi == NULL)
		return (NULL);

	if (smb_shr_cache_lock(SMB_SHR_CACHE_RDLOCK) == NERR_Success) {
		if ((cached_si = smb_shr_cache_iterate(shi)) != NULL) {
			share = &shi->si_share;
			bcopy(cached_si, share, sizeof (smb_share_t));
			smb_shr_set_exec_flags(share);
		}
		smb_shr_cache_unlock();
	}

	return (share);
}

/*
 * Adds the given share to cache, publishes the share in ADS
 * if it has an AD container, calls kernel to take a hold on
 * the shared file system. If it can't take a hold on the
 * shared file system, it's either because shared directory
 * does not exist or some other error has occurred, in any
 * case the share is removed from the cache.
 *
 * If the specified share is an autohome share which already
 * exists in the cache, just increments the reference count.
 */
uint32_t
smb_shr_add(smb_share_t *si)
{
	smb_share_t *cached_si;
	uint32_t status;
	int rc;

	assert(si != NULL);

	if (!smb_shr_chkname(si->shr_name))
		return (ERROR_INVALID_NAME);

	if (smb_shr_cache_lock(SMB_SHR_CACHE_WRLOCK) != NERR_Success)
		return (NERR_InternalError);

	cached_si = smb_shr_cache_findent(si->shr_name);
	if (cached_si) {
		if (si->shr_flags & SMB_SHRF_AUTOHOME) {
			cached_si->shr_refcnt++;
			status = NERR_Success;
		} else {
			status = NERR_DuplicateShare;
		}
		smb_shr_cache_unlock();
		return (status);
	}

	if ((status = smb_shr_cache_addent(si)) != NERR_Success) {
		smb_shr_cache_unlock();
		return (status);
	}

	/* don't hold the lock across door call */
	smb_shr_cache_unlock();

	/* call kernel to take a hold on the shared file system */
	rc = smb_kmod_share(si->shr_path, si->shr_name);

	if (rc == 0) {
		smb_shr_publish(si->shr_name, si->shr_container);

		/* If path is ZFS, add the .zfs/shares/<share> entry. */
		smb_shr_zfs_add(si);

		return (NERR_Success);
	}

	if (smb_shr_cache_lock(SMB_SHR_CACHE_WRLOCK) == NERR_Success) {
		smb_shr_cache_delent(si->shr_name);
		smb_shr_cache_unlock();
	}

	/*
	 * rc == ENOENT means the shared directory doesn't exist
	 */
	return ((rc == ENOENT) ? NERR_UnknownDevDir : NERR_InternalError);
}

/*
 * Removes the specified share from cache, removes it from AD
 * if it has an AD container, and calls the kernel to release
 * the hold on the shared file system.
 *
 * If this is an autohome share then decrement the reference
 * count. If it reaches 0 then it proceeds with removing steps.
 */
uint32_t
smb_shr_remove(char *sharename)
{
	smb_share_t *si;
	char path[MAXPATHLEN];
	char container[MAXPATHLEN];

	assert(sharename != NULL);

	if (!smb_shr_chkname(sharename))
		return (ERROR_INVALID_NAME);

	if (smb_shr_cache_lock(SMB_SHR_CACHE_WRLOCK) != NERR_Success)
		return (NERR_InternalError);

	if ((si = smb_shr_cache_findent(sharename)) == NULL) {
		smb_shr_cache_unlock();
		return (NERR_NetNameNotFound);
	}

	if (si->shr_type & STYPE_IPC) {
		/* IPC$ share cannot be removed */
		smb_shr_cache_unlock();
		return (ERROR_ACCESS_DENIED);
	}

	if (si->shr_flags & SMB_SHRF_AUTOHOME) {
		if ((--si->shr_refcnt) > 0) {
			smb_shr_cache_unlock();
			return (NERR_Success);
		}
	}

	/*
	 * If path is ZFS, remove the .zfs/shares/<share> entry.  Need
	 * to remove before cleanup of cache occurs.
	 */
	smb_shr_zfs_remove(si);

	(void) strlcpy(path, si->shr_path, sizeof (path));
	(void) strlcpy(container, si->shr_container, sizeof (container));
	smb_shr_cache_delent(sharename);
	smb_shr_cache_unlock();

	smb_shr_unpublish(sharename, container);

	/* call kernel to release the hold on the shared file system */
	(void) smb_kmod_unshare(path, sharename);

	return (NERR_Success);
}

/*
 * Rename a share. Check that the current name exists and the new name
 * doesn't exist. The rename is performed by deleting the current share
 * definition and creating a new share with the new name.
 */
uint32_t
smb_shr_rename(char *from_name, char *to_name)
{
	smb_share_t *from_si;
	smb_share_t to_si;
	uint32_t status;

	assert((from_name != NULL) && (to_name != NULL));

	if (!smb_shr_chkname(from_name) || !smb_shr_chkname(to_name))
		return (ERROR_INVALID_NAME);

	if (smb_shr_cache_lock(SMB_SHR_CACHE_WRLOCK) != NERR_Success)
		return (NERR_InternalError);

	if ((from_si = smb_shr_cache_findent(from_name)) == NULL) {
		smb_shr_cache_unlock();
		return (NERR_NetNameNotFound);
	}

	if (from_si->shr_type & STYPE_IPC) {
		/* IPC$ share cannot be renamed */
		smb_shr_cache_unlock();
		return (ERROR_ACCESS_DENIED);
	}

	if (smb_shr_cache_findent(to_name) != NULL) {
		smb_shr_cache_unlock();
		return (NERR_DuplicateShare);
	}

	bcopy(from_si, &to_si, sizeof (smb_share_t));
	(void) strlcpy(to_si.shr_name, to_name, sizeof (to_si.shr_name));

	/* If path is ZFS, rename the .zfs/shares/<share> entry. */
	smb_shr_zfs_rename(from_si, &to_si);

	if ((status = smb_shr_cache_addent(&to_si)) != NERR_Success) {
		smb_shr_cache_unlock();
		return (status);
	}

	smb_shr_cache_delent(from_name);
	smb_shr_cache_unlock();

	smb_shr_unpublish(from_name, to_si.shr_container);
	smb_shr_publish(to_name, to_si.shr_container);

	return (NERR_Success);
}

/*
 * Load the information for the specified share into the supplied share
 * info structure.
 *
 * First looks up the cache to see if the specified share exists, if there
 * is a miss then it looks up sharemgr.
 */
uint32_t
smb_shr_get(char *sharename, smb_share_t *si)
{
	uint32_t status;

	if (sharename == NULL || *sharename == '\0')
		return (NERR_NetNameNotFound);

	if ((status = smb_shr_lookup(sharename, si)) == NERR_Success)
		return (status);

	if ((status = smb_shr_sa_loadbyname(sharename)) == NERR_Success)
		status = smb_shr_lookup(sharename, si);

	return (status);
}

/*
 * Modifies an existing share. Properties that can be modified are:
 *
 *   o comment
 *   o AD container
 *   o host access
 *   o abe
 */
uint32_t
smb_shr_modify(smb_share_t *new_si)
{
	smb_share_t *si;
	boolean_t adc_changed = B_FALSE;
	char old_container[MAXPATHLEN];
	uint32_t catia, cscflg, access, abe;

	assert(new_si != NULL);

	if (smb_shr_cache_lock(SMB_SHR_CACHE_WRLOCK) != NERR_Success)
		return (NERR_InternalError);

	if ((si = smb_shr_cache_findent(new_si->shr_name)) == NULL) {
		smb_shr_cache_unlock();
		return (NERR_NetNameNotFound);
	}

	if (si->shr_type & STYPE_IPC) {
		/* IPC$ share cannot be modified */
		smb_shr_cache_unlock();
		return (ERROR_ACCESS_DENIED);
	}

	(void) strlcpy(si->shr_cmnt, new_si->shr_cmnt, sizeof (si->shr_cmnt));

	adc_changed = (strcmp(new_si->shr_container, si->shr_container) != 0);
	if (adc_changed) {
		/* save current container - needed for unpublishing */
		(void) strlcpy(old_container, si->shr_container,
		    sizeof (old_container));
		(void) strlcpy(si->shr_container, new_si->shr_container,
		    sizeof (si->shr_container));
	}

	abe = (new_si->shr_flags & SMB_SHRF_ABE);
	si->shr_flags &= ~SMB_SHRF_ABE;
	si->shr_flags |= abe;

	catia = (new_si->shr_flags & SMB_SHRF_CATIA);
	si->shr_flags &= ~SMB_SHRF_CATIA;
	si->shr_flags |= catia;

	cscflg = (new_si->shr_flags & SMB_SHRF_CSC_MASK);
	si->shr_flags &= ~SMB_SHRF_CSC_MASK;
	si->shr_flags |= cscflg;

	if (new_si->shr_flags & SMB_SHRF_GUEST_OK)
		si->shr_flags |= SMB_SHRF_GUEST_OK;
	else
		si->shr_flags &= ~SMB_SHRF_GUEST_OK;

	access = (new_si->shr_flags & SMB_SHRF_ACC_ALL);
	si->shr_flags &= ~SMB_SHRF_ACC_ALL;
	si->shr_flags |= access;

	if (access & SMB_SHRF_ACC_NONE)
		(void) strlcpy(si->shr_access_none, new_si->shr_access_none,
		    sizeof (si->shr_access_none));

	if (access & SMB_SHRF_ACC_RO)
		(void) strlcpy(si->shr_access_ro, new_si->shr_access_ro,
		    sizeof (si->shr_access_ro));

	if (access & SMB_SHRF_ACC_RW)
		(void) strlcpy(si->shr_access_rw, new_si->shr_access_rw,
		    sizeof (si->shr_access_rw));

	smb_shr_cache_unlock();

	if (adc_changed) {
		smb_shr_unpublish(new_si->shr_name, old_container);
		smb_shr_publish(new_si->shr_name, new_si->shr_container);
	}

	return (NERR_Success);
}

/*
 * smb_shr_exists
 *
 * Returns B_TRUE if the share exists. Otherwise returns B_FALSE
 */
boolean_t
smb_shr_exists(char *sharename)
{
	boolean_t exists = B_FALSE;

	if (sharename == NULL || *sharename == '\0')
		return (B_FALSE);

	if (smb_shr_cache_lock(SMB_SHR_CACHE_RDLOCK) == NERR_Success) {
		exists = (smb_shr_cache_findent(sharename) != NULL);
		smb_shr_cache_unlock();
	}

	return (exists);
}

/*
 * If the shared directory does not begin with a /, one will be
 * inserted as a prefix. If ipaddr is not zero, then also return
 * information about access based on the host level access lists, if
 * present. Also return access check if there is an IP address and
 * shr_accflags.
 *
 * The value of smb_chk_hostaccess is checked for an access match.
 * -1 is wildcard match
 * 0 is no match
 * 1 is match
 *
 * Precedence is none is checked first followed by ro then rw if
 * needed.  If x is wildcard (< 0) then check to see if the other
 * values are a match. If a match, that wins.
 *
 * ipv6 is wide open for now, see smb_chk_hostaccess
 */
void
smb_shr_hostaccess(smb_share_t *si, smb_inaddr_t *ipaddr)
{
	int acc = SMB_SHRF_ACC_OPEN;

	/*
	 * Check to see if there area any share level access
	 * restrictions.
	 */
	if ((!smb_inet_iszero(ipaddr)) &&
	    (si->shr_flags & SMB_SHRF_ACC_ALL) != 0) {
		int none = SMB_SHRF_ACC_OPEN;
		int rw = SMB_SHRF_ACC_OPEN;
		int ro = SMB_SHRF_ACC_OPEN;

		if (si->shr_flags & SMB_SHRF_ACC_NONE)
			none = smb_chk_hostaccess(ipaddr, si->shr_access_none);
		if (si->shr_flags & SMB_SHRF_ACC_RW)
			rw = smb_chk_hostaccess(ipaddr, si->shr_access_rw);
		if (si->shr_flags & SMB_SHRF_ACC_RO)
			ro = smb_chk_hostaccess(ipaddr, si->shr_access_ro);
		/* make first pass to get basic value */
		if (none != 0)
			acc = SMB_SHRF_ACC_NONE;
		else if (ro != 0)
			acc = SMB_SHRF_ACC_RO;
		else if (rw != 0)
			acc = SMB_SHRF_ACC_RW;

		/* make second pass to handle '*' case */
		if (none < 0) {
			acc = SMB_SHRF_ACC_NONE;
			if (ro > 0)
				acc = SMB_SHRF_ACC_RO;
			else if (rw > 0)
				acc = SMB_SHRF_ACC_RW;
		} else if (ro < 0) {
			acc = SMB_SHRF_ACC_RO;
			if (none > 0)
				acc = SMB_SHRF_ACC_NONE;
			else if (rw > 0)
				acc = SMB_SHRF_ACC_RW;
		} else if (rw < 0) {
			acc = SMB_SHRF_ACC_RW;
			if (none > 0)
				acc = SMB_SHRF_ACC_NONE;
			else if (ro > 0)
				acc = SMB_SHRF_ACC_RO;
		}
	}
	si->shr_access_value = acc;	/* return access here */
}

/*
 * smb_shr_is_special
 *
 * Special share reserved for interprocess communication (IPC$) or
 * remote administration of the server (ADMIN$). Can also refer to
 * administrative shares such as C$, D$, E$, and so forth.
 */
int
smb_shr_is_special(char *sharename)
{
	int len;

	if (sharename == NULL)
		return (0);

	if ((len = strlen(sharename)) == 0)
		return (0);

	if (sharename[len - 1] == '$')
		return (STYPE_SPECIAL);

	return (0);
}

/*
 * smb_shr_is_restricted
 *
 * Check whether or not there is a restriction on a share. Restricted
 * shares are generally STYPE_SPECIAL, for example, IPC$. All the
 * administration share names are restricted: C$, D$ etc. Returns B_TRUE
 * if the share is restricted. Otherwise B_FALSE is returned to indicate
 * that there are no restrictions.
 */
boolean_t
smb_shr_is_restricted(char *sharename)
{
	static char *restricted[] = {
		"IPC$"
	};

	int i;

	if (sharename == NULL)
		return (B_FALSE);

	for (i = 0; i < sizeof (restricted)/sizeof (restricted[0]); i++) {
		if (smb_strcasecmp(restricted[i], sharename, 0) == 0)
			return (B_TRUE);
	}

	return (smb_shr_is_admin(sharename));
}

/*
 * smb_shr_is_admin
 *
 * Check whether or not access to the share should be restricted to
 * administrators. This is a bit of a hack because what we're doing
 * is checking for the default admin shares: C$, D$ etc.. There are
 * other shares that have restrictions: see smb_shr_is_restricted().
 *
 * Returns B_TRUE if the shares is an admin share. Otherwise B_FALSE
 * is returned to indicate that there are no restrictions.
 */
boolean_t
smb_shr_is_admin(char *sharename)
{
	if (sharename == NULL)
		return (B_FALSE);

	if (strlen(sharename) == 2 &&
	    smb_isalpha(sharename[0]) && sharename[1] == '$') {
		return (B_TRUE);
	}

	return (B_FALSE);
}

/*
 * smb_shr_chkname
 *
 * Check for invalid characters in a share name.  The list of invalid
 * characters includes control characters and the following:
 *
 * " / \ [ ] : | < > + ; , ? * =
 */
boolean_t
smb_shr_chkname(char *sharename)
{
	char *invalid = "\"/\\[]:|<>+;,?*=";
	char *cp;

	if (sharename == NULL)
		return (B_FALSE);

	if (strpbrk(sharename, invalid))
		return (B_FALSE);

	for (cp = sharename; *cp != '\0'; cp++) {
		if (iscntrl(*cp))
			return (B_FALSE);
	}

	return (B_TRUE);
}

/*
 * smb_shr_get_realpath
 *
 * Derive the real path for a share from the path provided by a client.
 * For instance, the real path of C:\ may be /cvol or the real path of
 * F:\home may be /vol1/home.
 *
 * clntpath - path provided by the Windows client is in the
 *            format of <drive letter>:\<dir>
 * realpath - path that will be stored as the directory field of
 *            the smb_share_t structure of the share.
 * maxlen   - maximum length of the realpath buffer
 *
 * Return LAN Manager network error code.
 */
uint32_t
smb_shr_get_realpath(const char *clntpath, char *realpath, int maxlen)
{
	const char *p;
	int len;

	if ((p = strchr(clntpath, ':')) != NULL)
		++p;
	else
		p = clntpath;

	(void) strlcpy(realpath, p, maxlen);
	(void) strcanon(realpath, "/\\");
	(void) strsubst(realpath, '\\', '/');

	len = strlen(realpath);
	if ((len > 1) && (realpath[len - 1] == '/'))
		realpath[len - 1] = '\0';

	return (NERR_Success);
}

void
smb_shr_list(int offset, smb_shrlist_t *list)
{
	smb_shriter_t iterator;
	smb_share_t *si;
	int n = 0;

	bzero(list, sizeof (smb_shrlist_t));
	smb_shr_iterinit(&iterator);

	while ((si = smb_shr_iterate(&iterator)) != NULL) {
		if (--offset > 0)
			continue;

		if ((si->shr_flags & SMB_SHRF_TRANS) &&
		    ((si->shr_type & STYPE_IPC) == 0)) {
			bcopy(si, &list->sl_shares[n], sizeof (smb_share_t));
			if (++n == LMSHARES_PER_REQUEST)
				break;
		}
	}

	list->sl_cnt = n;
}

/*
 * Executes the map/unmap command associated with a share.
 *
 * Returns 0 on success.  Otherwise non-zero for errors.
 */
int
smb_shr_exec(char *share, smb_execsub_info_t *subs, int exec_type)
{
	char cmd[MAXPATHLEN], **cmd_tokens, *path, *ptr;
	pid_t child_pid;
	int child_status;
	struct sigaction pact, cact;
	smb_share_t si;

	if (smb_shr_get(share, &si) != 0)
		return (-1);

	*cmd = '\0';

	(void) mutex_lock(&smb_shr_exec_mtx);

	switch (exec_type) {
	case SMB_SHR_MAP:
		(void) strlcpy(cmd, smb_shr_exec_map, sizeof (cmd));
		break;
	case SMB_SHR_UNMAP:
		(void) strlcpy(cmd, smb_shr_exec_unmap, sizeof (cmd));
		break;
	default:
		(void) mutex_unlock(&smb_shr_exec_mtx);
		return (-1);
	}

	(void) mutex_unlock(&smb_shr_exec_mtx);

	if (*cmd == '\0')
		return (0);

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

	pact.sa_handler = smb_shr_sig_child;
	pact.sa_flags = 0;
	(void) sigemptyset(&pact.sa_mask);
	sigaction(SIGCHLD, &pact, NULL);

	(void) priv_set(PRIV_ON, PRIV_EFFECTIVE, PRIV_PROC_FORK, NULL);

	if ((child_pid = fork()) == -1) {
		(void) priv_set(PRIV_OFF, PRIV_EFFECTIVE, PRIV_PROC_FORK, NULL);
		smb_proc_givesem();
		return (-1);
	}

	if (child_pid == 0) {

		/* child process */

		cact.sa_handler = smb_shr_sig_abnormal_term;
		cact.sa_flags = 0;
		(void) sigemptyset(&cact.sa_mask);
		sigaction(SIGTERM, &cact, NULL);
		sigaction(SIGABRT, &cact, NULL);
		sigaction(SIGSEGV, &cact, NULL);

		if (priv_set(PRIV_ON, PRIV_EFFECTIVE, PRIV_PROC_EXEC,
		    PRIV_FILE_DAC_EXECUTE, NULL))
			_exit(-1);

		if (smb_shr_enable_all_privs())
			_exit(-1);

		smb_proc_initsem();

		(void) trim_whitespace(cmd);
		(void) strcanon(cmd, " ");

		if ((cmd_tokens = smb_shr_tokenize_cmd(cmd)) != NULL) {

			if (smb_shr_expand_subs(cmd_tokens, &si, subs) != 0) {
				free(cmd_tokens[0]);
				free(cmd_tokens);
				_exit(-1);
			}

			ptr = cmd;
			path = strsep(&ptr, " ");

			(void) execv(path, cmd_tokens);
		}

		_exit(-1);
	}

	(void) priv_set(PRIV_OFF, PRIV_EFFECTIVE, PRIV_PROC_FORK, NULL);
	smb_proc_givesem();

	/* parent process */

	while (waitpid(child_pid, &child_status, 0) < 0) {
		if (errno != EINTR)
			break;

		/* continue if waitpid got interrupted by a signal */
		errno = 0;
		continue;
	}

	if (WIFEXITED(child_status))
		return (WEXITSTATUS(child_status));

	return (child_status);
}

/*
 * Locking for process-wide settings (i.e. privileges)
 */
void
smb_proc_initsem(void)
{
	(void) sema_init(&smb_proc_sem, 1, USYNC_THREAD, NULL);
}

int
smb_proc_takesem(void)
{
	return (sema_wait(&smb_proc_sem));
}

void
smb_proc_givesem(void)
{
	(void) sema_post(&smb_proc_sem);
}

/*
 * ============================================
 * Private helper/utility functions
 * ============================================
 */

/*
 * Looks up the given share in the cache and return
 * the info in 'si'
 */
static uint32_t
smb_shr_lookup(char *sharename, smb_share_t *si)
{
	smb_share_t *cached_si;
	uint32_t status = NERR_NetNameNotFound;

	if (sharename == NULL || *sharename == '\0')
		return (NERR_NetNameNotFound);
	if (smb_shr_cache_lock(SMB_SHR_CACHE_RDLOCK) == NERR_Success) {
		cached_si = smb_shr_cache_findent(sharename);
		if (cached_si != NULL) {
			bcopy(cached_si, si, sizeof (smb_share_t));
			smb_shr_set_exec_flags(si);
			status = NERR_Success;
		}

		smb_shr_cache_unlock();
	}
	return (status);
}

/*
 * Add IPC$ to the cache upon startup.
 */
static uint32_t
smb_shr_addipc(void)
{
	smb_share_t ipc;
	uint32_t status = NERR_InternalError;

	bzero(&ipc, sizeof (smb_share_t));
	(void) strcpy(ipc.shr_name, "IPC$");
	(void) strcpy(ipc.shr_cmnt, "Remote IPC");
	ipc.shr_flags = SMB_SHRF_TRANS;
	ipc.shr_type = STYPE_IPC;

	if (smb_shr_cache_lock(SMB_SHR_CACHE_WRLOCK) == NERR_Success) {
		status = smb_shr_cache_addent(&ipc);
		smb_shr_cache_unlock();
	}

	return (status);
}

/*
 * smb_shr_set_oemname
 *
 * Generate the OEM name for the specified share.  If the name is
 * shorter than 13 bytes the oemname will be saved in si->shr_oemname.
 * Otherwise si->shr_oemname will be empty and SMB_SHRF_LONGNAME will
 * be set in si->shr_flags.
 */
static void
smb_shr_set_oemname(smb_share_t *si)
{
	smb_wchar_t *unibuf;
	char *oem_name;
	int length;

	length = strlen(si->shr_name) + 1;

	oem_name = malloc(length);
	unibuf = malloc(length * sizeof (smb_wchar_t));
	if ((oem_name == NULL) || (unibuf == NULL)) {
		free(oem_name);
		free(unibuf);
		return;
	}

	(void) smb_mbstowcs(unibuf, si->shr_name, length);

	if (ucstooem(oem_name, unibuf, length, OEM_CPG_850) == 0)
		(void) strcpy(oem_name, si->shr_name);

	free(unibuf);

	if (strlen(oem_name) + 1 > SMB_SHARE_OEMNAME_MAX) {
		si->shr_flags |= SMB_SHRF_LONGNAME;
		*si->shr_oemname = '\0';
	} else {
		si->shr_flags &= ~SMB_SHRF_LONGNAME;
		(void) strlcpy(si->shr_oemname, oem_name,
		    SMB_SHARE_OEMNAME_MAX);
	}

	free(oem_name);
}

/*
 * ============================================
 * Cache management functions
 *
 * All cache functions are private
 * ============================================
 */

/*
 * Create the share cache (hash table).
 */
static uint32_t
smb_shr_cache_create(void)
{
	uint32_t status = NERR_Success;

	(void) mutex_lock(&smb_shr_cache.sc_mtx);
	switch (smb_shr_cache.sc_state) {
	case SMB_SHR_CACHE_STATE_NONE:
		smb_shr_cache.sc_cache = ht_create_table(SMB_SHR_HTAB_SZ,
		    MAXNAMELEN, 0);
		if (smb_shr_cache.sc_cache == NULL) {
			status = NERR_InternalError;
			break;
		}

		(void) ht_register_callback(smb_shr_cache.sc_cache,
		    smb_shr_cache_freent);
		smb_shr_cache.sc_nops = 0;
		smb_shr_cache.sc_state = SMB_SHR_CACHE_STATE_CREATED;
		break;

	default:
		assert(0);
		status = NERR_InternalError;
		break;
	}
	(void) mutex_unlock(&smb_shr_cache.sc_mtx);

	return (status);
}

/*
 * Destroy the share cache (hash table).
 * Wait for inflight/pending operations to finish or abort before
 * destroying the cache.
 */
static void
smb_shr_cache_destroy(void)
{
	(void) mutex_lock(&smb_shr_cache.sc_mtx);
	if (smb_shr_cache.sc_state == SMB_SHR_CACHE_STATE_CREATED) {
		smb_shr_cache.sc_state = SMB_SHR_CACHE_STATE_DESTROYING;
		while (smb_shr_cache.sc_nops > 0)
			(void) cond_wait(&smb_shr_cache.sc_cv,
			    &smb_shr_cache.sc_mtx);

		smb_shr_cache.sc_cache = NULL;
		smb_shr_cache.sc_state = SMB_SHR_CACHE_STATE_NONE;
	}
	(void) mutex_unlock(&smb_shr_cache.sc_mtx);
}

/*
 * If the cache is in "created" state, lock the cache for read
 * or read/write based on the specified mode.
 *
 * Whenever a lock is granted, the number of inflight cache
 * operations is incremented.
 */
static uint32_t
smb_shr_cache_lock(int mode)
{
	(void) mutex_lock(&smb_shr_cache.sc_mtx);
	if (smb_shr_cache.sc_state != SMB_SHR_CACHE_STATE_CREATED) {
		(void) mutex_unlock(&smb_shr_cache.sc_mtx);
		return (NERR_InternalError);
	}
	smb_shr_cache.sc_nops++;
	(void) mutex_unlock(&smb_shr_cache.sc_mtx);

	/*
	 * Lock has to be taken outside the mutex otherwise
	 * there could be a deadlock
	 */
	if (mode == SMB_SHR_CACHE_RDLOCK)
		(void) rw_rdlock(&smb_shr_cache.sc_cache_lck);
	else
		(void) rw_wrlock(&smb_shr_cache.sc_cache_lck);

	return (NERR_Success);
}

/*
 * Decrement the number of inflight operations and then unlock.
 */
static void
smb_shr_cache_unlock(void)
{
	(void) mutex_lock(&smb_shr_cache.sc_mtx);
	assert(smb_shr_cache.sc_nops > 0);
	smb_shr_cache.sc_nops--;
	(void) cond_broadcast(&smb_shr_cache.sc_cv);
	(void) mutex_unlock(&smb_shr_cache.sc_mtx);

	(void) rw_unlock(&smb_shr_cache.sc_cache_lck);
}

/*
 * Return the total number of shares
 */
static int
smb_shr_cache_count(void)
{
	return (ht_get_total_items(smb_shr_cache.sc_cache));
}

/*
 * looks up the given share name in the cache and if it
 * finds a match returns a pointer to the cached entry.
 * Note that since a pointer is returned this function
 * MUST be protected by smb_shr_cache_lock/unlock pair
 */
static smb_share_t *
smb_shr_cache_findent(char *sharename)
{
	HT_ITEM *item;

	(void) smb_strlwr(sharename);
	item = ht_find_item(smb_shr_cache.sc_cache, sharename);
	if (item && item->hi_data)
		return ((smb_share_t *)item->hi_data);

	return (NULL);
}

/*
 * Return a pointer to the first/next entry in
 * the cache based on the given iterator.
 *
 * Calls to this function MUST be protected by
 * smb_shr_cache_lock/unlock.
 */
static smb_share_t *
smb_shr_cache_iterate(smb_shriter_t *shi)
{
	HT_ITEM *item;

	if (shi->si_first) {
		item = ht_findfirst(smb_shr_cache.sc_cache, &shi->si_hashiter);
		shi->si_first = B_FALSE;
	} else {
		item = ht_findnext(&shi->si_hashiter);
	}

	if (item && item->hi_data)
		return ((smb_share_t *)item->hi_data);

	return (NULL);
}

/*
 * Add the specified share to the cache.  Memory needs to be allocated
 * for the cache entry and the passed information is copied to the
 * allocated space.
 */
static uint32_t
smb_shr_cache_addent(smb_share_t *si)
{
	smb_share_t *cache_ent;
	uint32_t status = NERR_Success;

	if ((cache_ent = malloc(sizeof (smb_share_t))) == NULL)
		return (ERROR_NOT_ENOUGH_MEMORY);

	bcopy(si, cache_ent, sizeof (smb_share_t));

	(void) smb_strlwr(cache_ent->shr_name);
	smb_shr_set_oemname(cache_ent);

	if ((si->shr_type & STYPE_IPC) == 0)
		cache_ent->shr_type = STYPE_DISKTREE;
	cache_ent->shr_type |= smb_shr_is_special(cache_ent->shr_name);

	if (smb_shr_is_admin(cache_ent->shr_name))
		cache_ent->shr_flags |= SMB_SHRF_ADMIN;

	if (si->shr_flags & SMB_SHRF_AUTOHOME)
		cache_ent->shr_refcnt = 1;

	if (ht_add_item(smb_shr_cache.sc_cache, cache_ent->shr_name, cache_ent)
	    == NULL) {
		syslog(LOG_DEBUG, "share: %s: cache update failed",
		    cache_ent->shr_name);
		free(cache_ent);
		status = NERR_InternalError;
	}

	return (status);
}

/*
 * Delete the specified share from the cache.
 */
static void
smb_shr_cache_delent(char *sharename)
{
	(void) smb_strlwr(sharename);
	(void) ht_remove_item(smb_shr_cache.sc_cache, sharename);
}

/*
 * Call back to free the given cache entry.
 */
static void
smb_shr_cache_freent(HT_ITEM *item)
{
	if (item && item->hi_data)
		free(item->hi_data);
}

/*
 * ============================================
 * Interfaces to sharemgr
 *
 * All functions in this section are private
 * ============================================
 */

/*
 * Load shares from sharemgr
 */
/*ARGSUSED*/
static void *
smb_shr_sa_loadall(void *args)
{
	sa_handle_t handle;
	sa_group_t group, subgroup;
	char *gstate;
	boolean_t gdisabled;

	if ((handle = smb_shr_sa_enter()) == NULL)
		return (NULL);

	for (group = sa_get_group(handle, NULL);
	    group != NULL; group = sa_get_next_group(group)) {
		gstate = sa_get_group_attr(group, "state");
		if (gstate == NULL)
			continue;

		gdisabled = (strcasecmp(gstate, "disabled") == 0);
		sa_free_attr_string(gstate);
		if (gdisabled)
			continue;

		smb_shr_sa_loadgrp(group);

		for (subgroup = sa_get_sub_group(group);
		    subgroup != NULL;
		    subgroup = sa_get_next_group(subgroup)) {
			smb_shr_sa_loadgrp(subgroup);
		}

	}

	smb_shr_sa_exit();
	return (NULL);
}

/*
 * Load the shares contained in the specified group.
 *
 * Don't process groups on which the smb protocol is disabled.
 * The top level ZFS group won't have the smb protocol enabled
 * but sub-groups will.
 *
 * We will tolerate a limited number of errors and then give
 * up on the current group.  A typical error might be that the
 * shared directory no longer exists.
 */
static void
smb_shr_sa_loadgrp(sa_group_t group)
{
	sa_share_t share;
	sa_resource_t resource;
	int error_count = 0;

	if (sa_get_optionset(group, SMB_PROTOCOL_NAME) == NULL)
		return;

	for (share = sa_get_share(group, NULL);
	    share != NULL;
	    share = sa_get_next_share(share)) {
		for (resource = sa_get_share_resource(share, NULL);
		    resource != NULL;
		    resource = sa_get_next_resource(resource)) {
			if (smb_shr_sa_load(share, resource))
				++error_count;

			if (error_count > SMB_SHR_ERROR_THRESHOLD)
				break;
		}

		if (error_count > SMB_SHR_ERROR_THRESHOLD)
			break;
	}
}

/*
 * Load a share definition from sharemgr and add it to the cache.
 * If the share is already in the cache then it doesn't do anything.
 *
 * This function does not report duplicate shares as error since
 * a share might have been added by smb_shr_get() while load is
 * in progress.
 */
static uint32_t
smb_shr_sa_load(sa_share_t share, sa_resource_t resource)
{
	smb_share_t si;
	char *sharename;
	uint32_t status;
	boolean_t loaded;

	if ((sharename = sa_get_resource_attr(resource, "name")) == NULL)
		return (NERR_InternalError);

	loaded = smb_shr_exists(sharename);
	sa_free_attr_string(sharename);

	if (loaded)
		return (NERR_Success);

	if ((status = smb_shr_sa_get(share, resource, &si)) != NERR_Success) {
		syslog(LOG_DEBUG, "share: failed to load %s (%d)",
		    si.shr_name, status);
		return (status);
	}

	status = smb_shr_add(&si);
	if ((status != NERR_Success) && (status != NERR_DuplicateShare)) {
		syslog(LOG_DEBUG, "share: failed to cache %s (%d)",
		    si.shr_name, status);
		return (status);
	}

	return (NERR_Success);
}

/*
 * Read the specified share information from sharemgr and return
 * it in the given smb_share_t structure.
 *
 * Shares read from sharemgr are marked as permanent/persistent.
 */
static uint32_t
smb_shr_sa_get(sa_share_t share, sa_resource_t resource, smb_share_t *si)
{
	sa_property_t prop;
	sa_optionset_t opts;
	char *val = NULL;
	char *path;
	char *rname;

	if ((path = sa_get_share_attr(share, "path")) == NULL)
		return (NERR_InternalError);

	if ((rname = sa_get_resource_attr(resource, "name")) == NULL) {
		sa_free_attr_string(path);
		return (NERR_InternalError);
	}

	bzero(si, sizeof (smb_share_t));
	si->shr_flags = SMB_SHRF_PERM;

	(void) strlcpy(si->shr_path, path, sizeof (si->shr_path));
	(void) strlcpy(si->shr_name, rname, sizeof (si->shr_name));
	sa_free_attr_string(path);
	sa_free_attr_string(rname);

	val = sa_get_resource_description(resource);
	if (val == NULL)
		val = sa_get_share_description(share);

	if (val != NULL) {
		(void) strlcpy(si->shr_cmnt, val, sizeof (si->shr_cmnt));
		sa_free_share_description(val);
	}

	opts = sa_get_derived_optionset(resource, SMB_PROTOCOL_NAME, 1);
	if (opts == NULL)
		return (NERR_Success);

	prop = (sa_property_t)sa_get_property(opts, SHOPT_AD_CONTAINER);
	if (prop != NULL) {
		if ((val = sa_get_property_attr(prop, "value")) != NULL) {
			(void) strlcpy(si->shr_container, val,
			    sizeof (si->shr_container));
			free(val);
		}
	}

	prop = (sa_property_t)sa_get_property(opts, SHOPT_CATIA);
	if (prop != NULL) {
		if ((val = sa_get_property_attr(prop, "value")) != NULL) {
			smb_shr_sa_catia_option(val, si);
			free(val);
		}
	}

	prop = (sa_property_t)sa_get_property(opts, SHOPT_ABE);
	if (prop != NULL) {
		if ((val = sa_get_property_attr(prop, "value")) != NULL) {
			smb_shr_sa_abe_option(val, si);
			free(val);
		}
	}

	prop = (sa_property_t)sa_get_property(opts, SHOPT_CSC);
	if (prop != NULL) {
		if ((val = sa_get_property_attr(prop, "value")) != NULL) {
			smb_shr_sa_csc_option(val, si);
			free(val);
		}
	}

	prop = (sa_property_t)sa_get_property(opts, SHOPT_GUEST);
	if (prop != NULL) {
		if ((val = sa_get_property_attr(prop, "value")) != NULL) {
			smb_shr_sa_guest_option(val, si);
			free(val);
		}
	}

	prop = (sa_property_t)sa_get_property(opts, SHOPT_NONE);
	if (prop != NULL) {
		if ((val = sa_get_property_attr(prop, "value")) != NULL) {
			(void) strlcpy(si->shr_access_none, val,
			    sizeof (si->shr_access_none));
			free(val);
			si->shr_flags |= SMB_SHRF_ACC_NONE;
		}
	}

	prop = (sa_property_t)sa_get_property(opts, SHOPT_RO);
	if (prop != NULL) {
		if ((val = sa_get_property_attr(prop, "value")) != NULL) {
			(void) strlcpy(si->shr_access_ro, val,
			    sizeof (si->shr_access_ro));
			free(val);
			si->shr_flags |= SMB_SHRF_ACC_RO;
		}
	}

	prop = (sa_property_t)sa_get_property(opts, SHOPT_RW);
	if (prop != NULL) {
		if ((val = sa_get_property_attr(prop, "value")) != NULL) {
			(void) strlcpy(si->shr_access_rw, val,
			    sizeof (si->shr_access_rw));
			free(val);
			si->shr_flags |= SMB_SHRF_ACC_RW;
		}
	}

	sa_free_derived_optionset(opts);
	return (NERR_Success);
}

/*
 * Map a client-side caching (CSC) option to the appropriate share
 * flag.  Only one option is allowed; an error will be logged if
 * multiple options have been specified.  We don't need to do anything
 * about multiple values here because the SRVSVC will not recognize
 * a value containing multiple flags and will return the default value.
 *
 * If the option value is not recognized, it will be ignored: invalid
 * values will typically be caught and rejected by sharemgr.
 */
void
smb_shr_sa_csc_option(const char *value, smb_share_t *si)
{
	int i;

	for (i = 0; i < (sizeof (cscopt) / sizeof (cscopt[0])); ++i) {
		if (strcasecmp(value, cscopt[i].value) == 0) {
			si->shr_flags |= cscopt[i].flag;
			break;
		}
	}

	switch (si->shr_flags & SMB_SHRF_CSC_MASK) {
	case 0:
	case SMB_SHRF_CSC_DISABLED:
	case SMB_SHRF_CSC_MANUAL:
	case SMB_SHRF_CSC_AUTO:
	case SMB_SHRF_CSC_VDO:
		break;

	default:
		syslog(LOG_INFO, "csc option conflict: 0x%08x",
		    si->shr_flags & SMB_SHRF_CSC_MASK);
		break;
	}
}

/*
 * Return the option name for the first CSC flag (there should be only
 * one) encountered in the share flags.
 */
char *
smb_shr_sa_csc_name(const smb_share_t *si)
{
	int i;

	for (i = 0; i < (sizeof (cscopt) / sizeof (cscopt[0])); ++i) {
		if (si->shr_flags & cscopt[i].flag)
			return (cscopt[i].value);
	}

	return (NULL);
}

/*
 * set SMB_SHRF_CATIA in accordance with catia property value
 */
void
smb_shr_sa_catia_option(const char *value, smb_share_t *si)
{
	if ((strcasecmp(value, "true") == 0) || (strcmp(value, "1") == 0)) {
		si->shr_flags |= SMB_SHRF_CATIA;
	} else {
		si->shr_flags &= ~SMB_SHRF_CATIA;
	}
}

/*
 * set SMB_SHRF_ABE in accordance with abe property value
 */
void
smb_shr_sa_abe_option(const char *value, smb_share_t *si)
{
	if ((strcasecmp(value, "true") == 0) || (strcmp(value, "1") == 0)) {
		si->shr_flags |= SMB_SHRF_ABE;
	} else {
		si->shr_flags &= ~SMB_SHRF_ABE;
	}
}

/*
 * set SMB_SHRF_GUEST_OK in accordance with guestok property value
 */
static void
smb_shr_sa_guest_option(const char *value, smb_share_t *si)
{
	if ((strcasecmp(value, "true") == 0) || (strcmp(value, "1") == 0)) {
		si->shr_flags |= SMB_SHRF_GUEST_OK;
	} else {
		si->shr_flags &= ~SMB_SHRF_GUEST_OK;
	}
}

/*
 * looks up sharemgr for the given share (resource) and loads
 * the definition into cache if lookup is successful
 */
static uint32_t
smb_shr_sa_loadbyname(char *sharename)
{
	sa_handle_t handle;
	sa_share_t share;
	sa_resource_t resource;
	uint32_t status;

	if ((handle = smb_shr_sa_enter()) == NULL)
		return (NERR_InternalError);

	resource = sa_find_resource(handle, sharename);
	if (resource == NULL) {
		smb_shr_sa_exit();
		return (NERR_NetNameNotFound);
	}

	share = sa_get_resource_parent(resource);
	if (share == NULL) {
		smb_shr_sa_exit();
		return (NERR_InternalError);
	}

	status = smb_shr_sa_load(share, resource);

	smb_shr_sa_exit();
	return (status);
}

/*
 * ============================================
 * Share publishing functions
 *
 * All the functions are private
 * ============================================
 */

static void
smb_shr_publish(const char *sharename, const char *container)
{
	smb_shr_publisher_queue(sharename, container, SMB_SHR_PUBLISH);
}

static void
smb_shr_unpublish(const char *sharename, const char *container)
{
	smb_shr_publisher_queue(sharename, container, SMB_SHR_UNPUBLISH);
}

/*
 * In domain mode, put a share on the publisher queue.
 * This is a no-op if the smb service is in Workgroup mode.
 */
static void
smb_shr_publisher_queue(const char *sharename, const char *container, char op)
{
	smb_shr_pitem_t *item = NULL;

	if (container == NULL || *container == '\0')
		return;

	if (smb_config_get_secmode() != SMB_SECMODE_DOMAIN)
		return;

	(void) mutex_lock(&ad_queue.spq_mtx);
	switch (ad_queue.spq_state) {
	case SMB_SHR_PQS_READY:
	case SMB_SHR_PQS_PUBLISHING:
		break;
	default:
		(void) mutex_unlock(&ad_queue.spq_mtx);
		return;
	}
	(void) mutex_unlock(&ad_queue.spq_mtx);

	if ((item = malloc(sizeof (smb_shr_pitem_t))) == NULL)
		return;

	item->spi_op = op;
	(void) strlcpy(item->spi_name, sharename, sizeof (item->spi_name));
	(void) strlcpy(item->spi_container, container,
	    sizeof (item->spi_container));

	(void) mutex_lock(&ad_queue.spq_mtx);
	list_insert_tail(&ad_queue.spq_list, item);
	(void) cond_signal(&ad_queue.spq_cv);
	(void) mutex_unlock(&ad_queue.spq_mtx);
}

/*
 * Publishing won't be activated if the smb service is running in
 * Workgroup mode.
 */
static int
smb_shr_publisher_start(void)
{
	pthread_t publish_thr;
	pthread_attr_t tattr;
	int rc;

	if (smb_config_get_secmode() != SMB_SECMODE_DOMAIN)
		return (0);

	(void) mutex_lock(&ad_queue.spq_mtx);
	if (ad_queue.spq_state != SMB_SHR_PQS_NOQUEUE) {
		(void) mutex_unlock(&ad_queue.spq_mtx);
		errno = EINVAL;
		return (-1);
	}

	list_create(&ad_queue.spq_list, sizeof (smb_shr_pitem_t),
	    offsetof(smb_shr_pitem_t, spi_lnd));
	ad_queue.spq_state = SMB_SHR_PQS_READY;
	(void) mutex_unlock(&ad_queue.spq_mtx);

	(void) pthread_attr_init(&tattr);
	(void) pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
	rc = pthread_create(&publish_thr, &tattr, smb_shr_publisher, 0);
	(void) pthread_attr_destroy(&tattr);

	return (rc);
}

static void
smb_shr_publisher_stop(void)
{
	if (smb_config_get_secmode() != SMB_SECMODE_DOMAIN)
		return;

	(void) mutex_lock(&ad_queue.spq_mtx);
	switch (ad_queue.spq_state) {
	case SMB_SHR_PQS_READY:
	case SMB_SHR_PQS_PUBLISHING:
		ad_queue.spq_state = SMB_SHR_PQS_STOPPING;
		(void) cond_signal(&ad_queue.spq_cv);
		break;
	default:
		break;
	}
	(void) mutex_unlock(&ad_queue.spq_mtx);
}

/*
 * This is the publisher daemon thread.  While running, the thread waits
 * on a conditional variable until notified that a share needs to be
 * [un]published or that the thread should be terminated.
 *
 * Entries may remain in the outgoing queue if the Active Directory
 * service is inaccessible, in which case the thread wakes up every 60
 * seconds to retry.
 */
/*ARGSUSED*/
static void *
smb_shr_publisher(void *arg)
{
	smb_ads_handle_t *ah;
	smb_shr_pitem_t *shr;
	list_t publist;
	timestruc_t pubretry;
	char hostname[MAXHOSTNAMELEN];

	(void) mutex_lock(&ad_queue.spq_mtx);
	if (ad_queue.spq_state != SMB_SHR_PQS_READY) {
		(void) mutex_unlock(&ad_queue.spq_mtx);
		return (NULL);
	}
	ad_queue.spq_state = SMB_SHR_PQS_PUBLISHING;
	(void) mutex_unlock(&ad_queue.spq_mtx);

	(void) smb_gethostname(hostname, MAXHOSTNAMELEN, 0);

	list_create(&publist, sizeof (smb_shr_pitem_t),
	    offsetof(smb_shr_pitem_t, spi_lnd));

	for (;;) {
		(void) mutex_lock(&ad_queue.spq_mtx);

		while (list_is_empty(&ad_queue.spq_list) &&
		    (ad_queue.spq_state == SMB_SHR_PQS_PUBLISHING)) {
			if (list_is_empty(&publist)) {
				(void) cond_wait(&ad_queue.spq_cv,
				    &ad_queue.spq_mtx);
			} else {
				pubretry.tv_sec = 60;
				pubretry.tv_nsec = 0;
				(void) cond_reltimedwait(&ad_queue.spq_cv,
				    &ad_queue.spq_mtx, &pubretry);
				break;
			}
		}

		if (ad_queue.spq_state != SMB_SHR_PQS_PUBLISHING) {
			(void) mutex_unlock(&ad_queue.spq_mtx);
			break;
		}

		/*
		 * Transfer queued items to the local list so that
		 * the mutex can be released.
		 */
		while ((shr = list_head(&ad_queue.spq_list)) != NULL) {
			list_remove(&ad_queue.spq_list, shr);
			list_insert_tail(&publist, shr);
		}

		(void) mutex_unlock(&ad_queue.spq_mtx);

		if ((ah = smb_ads_open()) != NULL) {
			smb_shr_publisher_send(ah, &publist, hostname);
			smb_ads_close(ah);
		}
	}

	(void) mutex_lock(&ad_queue.spq_mtx);
	smb_shr_publisher_flush(&ad_queue.spq_list);
	list_destroy(&ad_queue.spq_list);
	ad_queue.spq_state = SMB_SHR_PQS_NOQUEUE;
	(void) mutex_unlock(&ad_queue.spq_mtx);

	smb_shr_publisher_flush(&publist);
	list_destroy(&publist);
	return (NULL);
}

/*
 * Remove items from the specified queue and [un]publish them.
 */
static void
smb_shr_publisher_send(smb_ads_handle_t *ah, list_t *publist, const char *host)
{
	smb_shr_pitem_t *shr;

	while ((shr = list_head(publist)) != NULL) {
		(void) mutex_lock(&ad_queue.spq_mtx);
		if (ad_queue.spq_state != SMB_SHR_PQS_PUBLISHING) {
			(void) mutex_unlock(&ad_queue.spq_mtx);
			return;
		}
		(void) mutex_unlock(&ad_queue.spq_mtx);

		list_remove(publist, shr);

		if (shr->spi_op == SMB_SHR_PUBLISH)
			(void) smb_ads_publish_share(ah, shr->spi_name,
			    NULL, shr->spi_container, host);
		else
			(void) smb_ads_remove_share(ah, shr->spi_name,
			    NULL, shr->spi_container, host);

		free(shr);
	}
}

/*
 * Flush all remaining items from the specified list/queue.
 */
static void
smb_shr_publisher_flush(list_t *lst)
{
	smb_shr_pitem_t *shr;

	while ((shr = list_head(lst)) != NULL) {
		list_remove(lst, shr);
		free(shr);
	}
}

/*
 * If the share path refers to a ZFS file system, add the
 * .zfs/shares/<share> object.
 */

static void
smb_shr_zfs_add(smb_share_t *si)
{
	libzfs_handle_t *libhd;
	zfs_handle_t *zfshd;
	int ret;
	char dataset[MAXPATHLEN];

	if (smb_getdataset(si->shr_path, dataset, MAXPATHLEN) != 0)
		return;

	if ((libhd = libzfs_init()) == NULL)
		return;

	if ((zfshd = zfs_open(libhd, dataset, ZFS_TYPE_FILESYSTEM)) == NULL) {
		libzfs_fini(libhd);
		return;
	}

	errno = 0;
	ret = zfs_smb_acl_add(libhd, dataset, si->shr_path, si->shr_name);
	if (ret != 0 && errno != EAGAIN && errno != EEXIST)
		syslog(LOG_INFO, "share: failed to add ACL object: %s: %s\n",
		    si->shr_name, strerror(errno));

	zfs_close(zfshd);
	libzfs_fini(libhd);
}

/*
 * If the share path refers to a ZFS file system, remove the
 * .zfs/shares/<share> object.
 */

static void
smb_shr_zfs_remove(smb_share_t *si)
{
	libzfs_handle_t *libhd;
	zfs_handle_t *zfshd;
	int ret;
	char dataset[MAXPATHLEN];

	if (smb_getdataset(si->shr_path, dataset, MAXPATHLEN) != 0)
		return;

	if ((libhd = libzfs_init()) == NULL)
		return;

	if ((zfshd = zfs_open(libhd, dataset, ZFS_TYPE_FILESYSTEM)) == NULL) {
		libzfs_fini(libhd);
		return;
	}

	errno = 0;
	ret = zfs_smb_acl_remove(libhd, dataset, si->shr_path, si->shr_name);
	if (ret != 0 && errno != EAGAIN)
		syslog(LOG_INFO, "share: failed to remove ACL object: %s: %s\n",
		    si->shr_name, strerror(errno));

	zfs_close(zfshd);
	libzfs_fini(libhd);
}

/*
 * If the share path refers to a ZFS file system, rename the
 * .zfs/shares/<share> object.
 */

static void
smb_shr_zfs_rename(smb_share_t *from, smb_share_t *to)
{
	libzfs_handle_t *libhd;
	zfs_handle_t *zfshd;
	int ret;
	char dataset[MAXPATHLEN];

	if (smb_getdataset(from->shr_path, dataset, MAXPATHLEN) != 0)
		return;

	if ((libhd = libzfs_init()) == NULL)
		return;

	if ((zfshd = zfs_open(libhd, dataset, ZFS_TYPE_FILESYSTEM)) == NULL) {
		libzfs_fini(libhd);
		return;
	}

	errno = 0;
	ret = zfs_smb_acl_rename(libhd, dataset, from->shr_path,
	    from->shr_name, to->shr_name);
	if (ret != 0 && errno != EAGAIN)
		syslog(LOG_INFO, "share: failed to rename ACL object: %s: %s\n",
		    from->shr_name, strerror(errno));

	zfs_close(zfshd);
	libzfs_fini(libhd);
}

/*
 * Enable all privileges in the inheritable set to execute command.
 */
static int
smb_shr_enable_all_privs(void)
{
	priv_set_t *pset;

	pset = priv_allocset();
	if (pset == NULL)
		return (-1);

	if (getppriv(PRIV_LIMIT, pset)) {
		priv_freeset(pset);
		return (-1);
	}

	if (setppriv(PRIV_ON, PRIV_INHERITABLE, pset)) {
		priv_freeset(pset);
		return (-1);
	}

	priv_freeset(pset);
	return (0);
}

/*
 * Tokenizes the command string and returns the list of tokens in an array.
 *
 * Returns NULL if there are no tokens.
 */
static char **
smb_shr_tokenize_cmd(char *cmdstr)
{
	char *cmd, *buf, *bp, *value;
	char **argv, **ap;
	int argc, i;

	if (cmdstr == NULL || *cmdstr == '\0')
		return (NULL);

	if ((buf = malloc(MAXPATHLEN)) == NULL)
		return (NULL);

	(void) strlcpy(buf, cmdstr, MAXPATHLEN);

	for (argc = 2, bp = cmdstr; *bp != '\0'; ++bp)
		if (*bp == ' ')
			++argc;

	if ((argv = calloc(argc, sizeof (char *))) == NULL) {
		free(buf);
		return (NULL);
	}

	ap = argv;
	for (bp = buf, i = 0; i < argc; ++i) {
		do {
			if ((value = strsep(&bp, " ")) == NULL)
				break;
		} while (*value == '\0');

		if (value == NULL)
			break;

		*ap++ = value;
	}

	/* get the filename of the command from the path */
	if ((cmd = strrchr(argv[0], '/')) != NULL)
		(void) strlcpy(argv[0], ++cmd, strlen(argv[0]));

	return (argv);
}

/*
 * Expands the command string for the following substitution tokens:
 *
 * %U - Windows username
 * %D - Name of the domain or workgroup of %U
 * %h - The server hostname
 * %M - The client hostname
 * %L - The server NetBIOS name
 * %m - The client NetBIOS name. This option is only valid for NetBIOS
 *      connections (port 139).
 * %I - The IP address of the client machine
 * %i - The local IP address to which the client is connected
 * %S - The name of the share
 * %P - The root directory of the share
 * %u - The UID of the Unix user
 *
 * Returns 0 on success.  Otherwise -1.
 */
static int
smb_shr_expand_subs(char **cmd_toks, smb_share_t *si, smb_execsub_info_t *subs)
{
	char *fmt, *sub_chr, *ptr;
	boolean_t unknown;
	char hostname[MAXHOSTNAMELEN];
	char ip_str[INET6_ADDRSTRLEN];
	char name[SMB_PI_MAX_HOST];
	smb_wchar_t wbuf[SMB_PI_MAX_HOST];
	int i;

	if (cmd_toks == NULL || *cmd_toks == NULL)
		return (-1);

	for (i = 1; cmd_toks[i]; i++) {
		fmt = cmd_toks[i];
		if (*fmt == '%') {
			sub_chr = fmt + 1;
			unknown = B_FALSE;

			switch (*sub_chr) {
			case 'U':
				ptr = strdup(subs->e_winname);
				break;
			case 'D':
				ptr = strdup(subs->e_userdom);
				break;
			case 'h':
				if (gethostname(hostname, MAXHOSTNAMELEN) != 0)
					unknown = B_TRUE;
				else
					ptr = strdup(hostname);
				break;
			case 'M':
				if (smb_getnameinfo(&subs->e_cli_ipaddr,
				    hostname, sizeof (hostname), 0) != 0)
					unknown = B_TRUE;
				else
					ptr = strdup(hostname);
				break;
			case 'L':
				if (smb_getnetbiosname(hostname,
				    NETBIOS_NAME_SZ) != 0)
					unknown = B_TRUE;
				else
					ptr = strdup(hostname);
				break;
			case 'm':
				if (*subs->e_cli_netbiosname == '\0')
					unknown = B_TRUE;
				else {
					(void) smb_mbstowcs(wbuf,
					    subs->e_cli_netbiosname,
					    SMB_PI_MAX_HOST - 1);

					if (ucstooem(name, wbuf,
					    SMB_PI_MAX_HOST, OEM_CPG_850) == 0)
						(void) strlcpy(name,
						    subs->e_cli_netbiosname,
						    SMB_PI_MAX_HOST);

					ptr = strdup(name);
				}
				break;
			case 'I':
				if (smb_inet_ntop(&subs->e_cli_ipaddr, ip_str,
				    SMB_IPSTRLEN(subs->e_cli_ipaddr.a_family))
				    != NULL)
					ptr = strdup(ip_str);
				else
					unknown = B_TRUE;
				break;
			case 'i':
				if (smb_inet_ntop(&subs->e_srv_ipaddr, ip_str,
				    SMB_IPSTRLEN(subs->e_srv_ipaddr.a_family))
				    != NULL)
					ptr = strdup(ip_str);
				else
					unknown = B_TRUE;
				break;
			case 'S':
				ptr = strdup(si->shr_name);
				break;
			case 'P':
				ptr = strdup(si->shr_path);
				break;
			case 'u':
				(void) snprintf(name, sizeof (name), "%u",
				    subs->e_uid);
				ptr = strdup(name);
				break;
			default:
				/* unknown sub char */
				unknown = B_TRUE;
				break;
			}

			if (unknown)
				ptr = strdup("");

		} else  /* first char of cmd's arg is not '%' char */
			ptr = strdup("");

		cmd_toks[i] = ptr;

		if (ptr == NULL) {
			for (i = 1; cmd_toks[i]; i++)
				free(cmd_toks[i]);

			return (-1);
		}
	}

	return (0);
}

/*ARGSUSED*/
static void
smb_shr_sig_abnormal_term(int sig_val)
{
	/*
	 * Calling _exit() prevents parent process from getting SIGTERM/SIGINT
	 * signal.
	 */
	_exit(-1);
}

/*ARGSUSED*/
static void
smb_shr_sig_child(int sig_val)
{
	/*
	 * Catch the signal and allow the exit status of the child process
	 * to be available for reaping.
	 */
}

/*
 *  Gets the exec bit flags for each share.
 */
static void
smb_shr_get_exec_info(void)
{
	char buf[MAXPATHLEN];

	(void) mutex_lock(&smb_shr_exec_mtx);

	smb_shr_exec_flags = 0;

	*smb_shr_exec_map = '\0';
	(void) smb_config_getstr(SMB_CI_MAP, smb_shr_exec_map,
	    sizeof (smb_shr_exec_map));
	if (*smb_shr_exec_map != '\0')
		smb_shr_exec_flags |= SMB_SHRF_MAP;

	*smb_shr_exec_unmap = '\0';
	(void) smb_config_getstr(SMB_CI_UNMAP, smb_shr_exec_unmap,
	    sizeof (smb_shr_exec_unmap));
	if (*smb_shr_exec_unmap != '\0')
		smb_shr_exec_flags |= SMB_SHRF_UNMAP;

	*buf = '\0';
	(void) smb_config_getstr(SMB_CI_DISPOSITION, buf, sizeof (buf));
	if (*buf != '\0')
		if (strcasecmp(buf, SMB_SHR_DISP_TERM_STR) == 0)
			smb_shr_exec_flags |= SMB_SHRF_DISP_TERM;

	(void) mutex_unlock(&smb_shr_exec_mtx);
}

/*
 *  Sets the exec bit flags for each share.
 */
static void
smb_shr_set_exec_flags(smb_share_t *si)
{
	(void) mutex_lock(&smb_shr_exec_mtx);
	si->shr_flags &= ~SMB_SHRF_EXEC_MASK;
	si->shr_flags |= smb_shr_exec_flags;
	(void) mutex_unlock(&smb_shr_exec_mtx);
}