summaryrefslogtreecommitdiff
path: root/usr/src/lib/smbsrv/libmlsvc/common/dfs.c
blob: 7668d433b617b35a68271149238a8acc7709475f (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
/*
 * 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) 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2014 Nexenta Systems, Inc.  All rights reserved.
 */

#include <strings.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <dlfcn.h>
#include <pthread.h>
#include <syslog.h>
#include <sys/fs_reparse.h>
#include <uuid/uuid.h>

#include <smbsrv/libsmb.h>
#include <smbsrv/libmlsvc.h>
#include <smbsrv/smb_dfs.h>
#include <smbsrv/smb_share.h>
#include <dfs.h>

/*
 * default timeout (TTL) values (in second) for root and link
 */
#define	DFS_ROOT_TIMEOUT		300
#define	DFS_LINK_TIMEOUT		1800

/*
 * DFS link data format in reparse point
 *
 * ver:state:prop:timeout:guid:ntarget:cmntlen:comment
 *    [[:tserver:tshare:tstate:pclass:prank]...]
 */
#define	DFS_LINK_V1			1
#define	DFS_LINK_HDR_NFIELDS		7	/* # fields in header section */
#define	DFS_LINK_TRGT_NFIELDS		5	/* # fields for each target */

#define	DFS_ROOT_XATTR			"SUNWdfs.rootinfo"

#define	DFS_INFO_ALL			0

static void *dfs_intr_hdl = NULL;

static struct {
	int (*dfsops_remote_count)(uint32_t *);
} dfs_intr_ops;

/*
 * Namespace cache
 *
 * Caches links' UNC and filesystem path where the key is the UNC path.
 */
static smb_cache_t dfs_nscache;
static char dfs_nbname[NETBIOS_NAME_SZ];

/*
 * The name of cached namespace. This will be the only
 * exported namespace until hosting multiple namespaces
 * is supported
 */
static char dfs_cached_ns[MAXNAMELEN];
static mutex_t dfs_nsmtx;

/*
 * Lock for accessing root information (extended attribute)
 */
static rwlock_t dfs_root_rwl;

extern uint32_t srvsvc_shr_setdfsroot(smb_share_t *, boolean_t);

/*
 * Namespace functions
 */
static boolean_t dfs_namespace_findlink(const char *, char *, char *, size_t);
static void *dfs_namespace_cache(void *);
static boolean_t dfs_namespace_iscached(const char *);

/*
 * Root functions
 */
static int dfs_root_add(const char *, dfs_info_t *);
static uint32_t dfs_root_remove(const char *);
static uint32_t dfs_root_encode(dfs_info_t *, char **, size_t *);
static uint32_t dfs_root_decode(dfs_info_t *, char *, size_t, uint32_t);
static uint32_t dfs_root_isvalidstate(uint32_t);

static int dfs_root_xopen(const char *, int);
static void dfs_root_xclose(int);
static uint32_t dfs_root_xwrite(int, dfs_info_t *);
static uint32_t dfs_root_xread(int, dfs_info_t *, uint32_t);

/*
 * Link functions
 */
static uint32_t dfs_link_encode(dfs_info_t *, char *, size_t);
static uint32_t dfs_link_decode(dfs_info_t *, char *, uint32_t);
static uint32_t dfs_link_commit(const char *, dfs_info_t *);
static boolean_t dfs_link_isvalidstate(uint32_t);

/*
 * Target functions
 */
static void dfs_target_init(dfs_target_t *, const char *, const char *,
    uint32_t);
static int dfs_target_find(dfs_target_t *, uint32_t, const char *,
    const char *);
static boolean_t dfs_target_isvalidstate(uint32_t);

/*
 * Cache functions
 */
static uint32_t dfs_cache_add_byunc(const char *, const char *, uint32_t);
static void dfs_cache_populate(const char *, const char *);
static int dfs_cache_cmp(const void *, const void *);
static void dfs_cache_flush(const char *);
static uint32_t dfs_cache_nscount(void);

/*
 * Utility functions
 */
static boolean_t dfs_path_isdir(const char *);
static uint32_t dfs_modinfo(uint32_t, dfs_info_t *, dfs_info_t *, uint32_t);

/*
 * DFS module initializationr:
 *
 * - creates the namespace cache
 * - gets system's NetBIOS name
 */
void
dfs_init(void)
{
	smb_cache_create(&dfs_nscache, 0, dfs_cache_cmp, free, bcopy,
	    sizeof (dfs_nscnode_t));

	if (smb_getnetbiosname(dfs_nbname, sizeof (dfs_nbname)) != 0) {
		syslog(LOG_ERR, "dfs: can't get machine name");
		return;
	}

	bzero((void *)&dfs_intr_ops, sizeof (dfs_intr_ops));

	if ((dfs_intr_hdl = smb_dlopen()) == NULL)
		return;

	if ((dfs_intr_ops.dfsops_remote_count =
	    (int (*)())dlsym(dfs_intr_hdl, "smb_dfs_remote_count")) == NULL) {
		smb_dlclose(dfs_intr_hdl);
		dfs_intr_hdl = NULL;
		bzero((void *)&dfs_intr_ops, sizeof (dfs_intr_ops));
	}
}

/*
 * DFS module cleanup:
 *
 * - destroys the namespace cache
 */
void
dfs_fini(void)
{
	smb_dlclose(dfs_intr_hdl);
	smb_cache_destroy(&dfs_nscache);
}

/*
 * To successfully handle some of link/root requests, some
 * file system operations need to be performed. These operations
 * should take place on behalf of the connected user (typically
 * Administrator) and to do so we need to have an infrastructure
 * in place so that smbd can act as a client and sends request to
 * the kernel. Right now, we lack this infrastructure, so we make
 * a compromise by temporarily enabling some privileges for smbd
 * to be able to fulfill various link/root requests.
 */
void
dfs_setpriv(priv_op_t op)
{
	(void) priv_set(op, PRIV_EFFECTIVE,
	    PRIV_FILE_DAC_READ,
	    PRIV_FILE_DAC_WRITE,
	    PRIV_FILE_DAC_EXECUTE,
	    PRIV_FILE_DAC_SEARCH, NULL);
}

/*
 * ========================
 * Namespace API (public)
 * ========================
 */

/*
 * Launches a thread to cache the specified namespace
 */
void
dfs_namespace_load(const char *name)
{
	pthread_t thr;
	pthread_attr_t tattr;
	char *rootshr;
	int rc;

	if ((rootshr = strdup(name)) == NULL) {
		syslog(LOG_ERR, "dfs: failed to load %s namespace (no memory)",
		    name);
		return;
	}

	(void) pthread_attr_init(&tattr);
	(void) pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
	rc = pthread_create(&thr, &tattr, dfs_namespace_cache, rootshr);
	(void) pthread_attr_destroy(&tattr);

	if (rc != 0)
		syslog(LOG_ERR, "dfs: fail to loading %s namespace (%d)",
		    name, rc);
}

/*
 * Flushes the cache when a DFS root share is removed
 */
void /*ARGSUSED*/
dfs_namespace_unload(const char *name)
{
	dfs_cache_flush(name);
}

/*
 * Returns the file system path for the given share if it
 * is a DFS root share.
 * If 'path' is NULL, this function only indicates whether
 * or not the given share represents a DFS namespace
 */
uint32_t
dfs_namespace_path(const char *name, char *path, size_t pathsz)
{
	smb_share_t si;

	if (smb_shr_get((char *)name, &si) != NERR_Success)
		return (ERROR_NOT_FOUND);

	if ((si.shr_flags & SMB_SHRF_DFSROOT) == 0)
		return (ERROR_NOT_FOUND);

	if (!dfs_namespace_iscached(name))
		return (ERROR_NOT_FOUND);

	if (path != NULL)
		(void) strlcpy(path, si.shr_path, pathsz);

	return (ERROR_SUCCESS);
}

/*
 * Returns the number of DFS root shares i.e. the number
 * of standalone namespaces.
 */
uint32_t
dfs_namespace_count(void)
{
	uint32_t nroot = 0;
	int rc;

	if (dfs_intr_ops.dfsops_remote_count != NULL &&
	    (rc = dfs_intr_ops.dfsops_remote_count(&nroot)) != 0) {
		/*
		 * If this call fails, let's assume there's at least one root
		 * namespace already configured.  The interposer library cannot
		 * confirm or deny the presence of a namespace, so let's take
		 * the safe approach and assume one exists.
		 */
		nroot = 1;
		syslog(LOG_WARNING, "dfs: dfsops_remote_count() failed: %d, "
		    "assuming one namespace exists", rc);
	}

	nroot += dfs_cache_nscount();

	return (nroot);
}

/*
 * Creates a DFS root with the given name and comment.
 *
 * This function does not create the root share, it
 * should already exist.
 */
uint32_t
dfs_namespace_add(const char *rootshr, const char *cmnt)
{
	dfs_info_t info;
	dfs_target_t t;
	smb_share_t si;
	uuid_t uuid;
	uint32_t status;

	if (*rootshr == '\\') {
		/* Windows has a special case here! */
		return (ERROR_BAD_PATHNAME);
	}

	if (smb_shr_get((char *)rootshr, &si) != NERR_Success)
		return (NERR_NetNameNotFound);

	(void) mutex_lock(&dfs_nsmtx);
	if (smb_strcasecmp(dfs_cached_ns, rootshr, 0) == 0) {
		/* This DFS root is already exported */
		(void) mutex_unlock(&dfs_nsmtx);
		return (ERROR_FILE_EXISTS);
	}

	if (*dfs_cached_ns != '\0') {
		syslog(LOG_WARNING, "dfs: trying to add %s namespace."
		    " Only one standalone namespace is supported."
		    " A namespace is already exported for %s",
		    rootshr, dfs_cached_ns);
		(void) mutex_unlock(&dfs_nsmtx);
		return (ERROR_NOT_SUPPORTED);
	}

	bzero(&info, sizeof (info));
	if (cmnt)
		(void) strlcpy(info.i_comment, cmnt, sizeof (info.i_comment));
	info.i_state = DFS_VOLUME_STATE_OK | DFS_VOLUME_FLAVOR_STANDALONE;
	info.i_timeout = DFS_ROOT_TIMEOUT;
	info.i_propflags = 0;

	uuid_generate_random(uuid);
	uuid_unparse(uuid, info.i_guid);

	dfs_target_init(&t, dfs_nbname, rootshr, DFS_STORAGE_STATE_ONLINE);

	info.i_ntargets = 1;
	info.i_targets = &t;

	if ((status = dfs_root_add(si.shr_path, &info)) != ERROR_SUCCESS) {
		(void) mutex_unlock(&dfs_nsmtx);
		return (status);
	}

	status = srvsvc_shr_setdfsroot(&si, B_TRUE);
	if (status == ERROR_SUCCESS) {
		(void) dfs_cache_add_byname(rootshr, NULL, DFS_OBJECT_ROOT);
		(void) strlcpy(dfs_cached_ns, rootshr, sizeof (dfs_cached_ns));
		(void) smb_config_setnum(SMB_CI_DFS_STDROOT_NUM, 1);
	}
	(void) mutex_unlock(&dfs_nsmtx);

	return (status);
}

/*
 * Removes the namespace and all the links in it.
 */
uint32_t
dfs_namespace_remove(const char *name)
{
	smb_cache_cursor_t cursor;
	dfs_nscnode_t nscnode;
	smb_share_t si;
	uint32_t status;

	if (smb_shr_get((char *)name, &si) != NERR_Success)
		return (ERROR_NOT_FOUND);

	if ((si.shr_flags & SMB_SHRF_DFSROOT) == 0)
		return (ERROR_NOT_FOUND);

	if ((status = dfs_root_remove(si.shr_path)) != ERROR_SUCCESS)
		return (status);

	status = srvsvc_shr_setdfsroot(&si, B_FALSE);
	if (status != ERROR_SUCCESS)
		syslog(LOG_WARNING, "dfs: failed to disable root share %s (%d)",
		    name, status);

	if (!dfs_namespace_iscached(name))
		return (ERROR_SUCCESS);

	smb_cache_iterinit(&dfs_nscache, &cursor);

	while (smb_cache_iterate(&dfs_nscache, &cursor, &nscnode)) {
		if (nscnode.nsc_type == DFS_OBJECT_ROOT)
			continue;
		status = dfs_link_remove(nscnode.nsc_fspath, NULL, NULL);
		if (status != ERROR_SUCCESS)
			syslog(LOG_WARNING, "dfs: failed to remove %s (%d)",
			    nscnode.nsc_fspath, status);
	}

	dfs_cache_flush(name);

	/* TODO: remove empty dirs */
	return (ERROR_SUCCESS);
}

/*
 * Determines the DFS namespace flavor.
 */
uint32_t
dfs_namespace_getflavor(const char *name)
{
	char rootdir[DFS_PATH_MAX];
	dfs_info_t info;

	if (dfs_namespace_path(name, rootdir, DFS_PATH_MAX) != ERROR_SUCCESS)
		return (0);

	/* get flavor info from state info (info level 2) */
	if (dfs_root_getinfo(rootdir, &info, 2) != ERROR_SUCCESS)
		return (0);

	return (info.i_state & DFS_VOLUME_FLAVORS);
}

/*
 * ==================
 * Root API (public)
 * ==================
 */

/*
 * Retrieves the information of the root specified by its path.
 *
 * Info level (1) only needs the UNC path which is not stored,
 * it is constructed so the function will return without
 * accessing the backend storage.
 */
uint32_t
dfs_root_getinfo(const char *rootdir, dfs_info_t *info, uint32_t infolvl)
{
	uint32_t status = ERROR_INTERNAL_ERROR;
	int xfd;

	bzero(info, sizeof (dfs_info_t));
	info->i_type = DFS_OBJECT_ROOT;

	if (infolvl == 1)
		return (ERROR_SUCCESS);

	(void) rw_rdlock(&dfs_root_rwl);
	if ((xfd = dfs_root_xopen(rootdir, O_RDONLY)) > 0) {
		status = dfs_root_xread(xfd, info, infolvl);
		dfs_root_xclose(xfd);
	}
	(void) rw_unlock(&dfs_root_rwl);

	return (status);
}

/*
 * Sets the provided information for the specified root or root target.
 * Root is specified by 'rootdir' and the target is specified by
 * (t_server, t_share) pair. Only information items needed for given
 * information level (infolvl) is valid in the passed DFS info structure
 * 'info'.
 */
uint32_t
dfs_root_setinfo(const char *rootdir, dfs_info_t *info, uint32_t infolvl)
{
	dfs_info_t curinfo;
	uint32_t status = ERROR_SUCCESS;
	int xfd;

	(void) rw_wrlock(&dfs_root_rwl);
	if ((xfd = dfs_root_xopen(rootdir, O_RDWR)) < 0) {
		(void) rw_unlock(&dfs_root_rwl);
		return (ERROR_INTERNAL_ERROR);
	}

	status = dfs_root_xread(xfd, &curinfo, DFS_INFO_ALL);
	if (status != ERROR_SUCCESS) {
		dfs_root_xclose(xfd);
		(void) rw_unlock(&dfs_root_rwl);
		return (status);
	}

	status = dfs_modinfo(DFS_OBJECT_ROOT, &curinfo, info, infolvl);
	if (status == ERROR_SUCCESS)
		status = dfs_root_xwrite(xfd, &curinfo);

	dfs_root_xclose(xfd);
	(void) rw_unlock(&dfs_root_rwl);

	dfs_info_free(&curinfo);
	return (status);
}

/*
 * ==================
 * Link API (public)
 * ==================
 */

/*
 * Gets the status of the given path as a link
 */
uint32_t
dfs_link_stat(const char *path, uint32_t *stat)
{
	if (smb_reparse_stat(path, stat) != 0)
		return (ERROR_INTERNAL_ERROR);

	switch (*stat) {
	case SMB_REPARSE_NOTFOUND:
		*stat = DFS_STAT_NOTFOUND;
		break;
	case SMB_REPARSE_NOTREPARSE:
		*stat = DFS_STAT_NOTLINK;
		break;
	case SMB_REPARSE_ISREPARSE:
		*stat = DFS_STAT_ISREPARSE;
		if (smb_reparse_svcget(path, DFS_REPARSE_SVCTYPE, NULL) == 0)
			*stat = DFS_STAT_ISDFS;
		break;
	default:
		*stat = DFS_STAT_UNKNOWN;
		break;
	}

	return (ERROR_SUCCESS);
}

/*
 * Creates a new DFS link or adds a new target to an existing link
 */
uint32_t
dfs_link_add(const char *path, const char *server, const char *share,
    const char *cmnt, uint32_t flags, boolean_t *newlink)
{
	dfs_info_t info;
	dfs_target_t *t;
	int ntargets;
	uint32_t status;
	uint32_t stat;

	*newlink = B_FALSE;

	if ((status = dfs_link_stat(path, &stat)) != ERROR_SUCCESS)
		return (status);

	switch (stat) {
	case DFS_STAT_NOTFOUND:
	case DFS_STAT_ISREPARSE:
		/* Create a new DFS link */

		status = dfs_link_getinfo(NULL, &info, DFS_INFO_ALL);
		if (status != ERROR_SUCCESS)
			return (status);

		(void) strlcpy(info.i_comment, (cmnt) ? cmnt : "",
		    sizeof (info.i_comment));
		*newlink = B_TRUE;
		break;

	case DFS_STAT_ISDFS:
		/* Add a target to an existing link */

		if (flags & DFS_ADD_VOLUME)
			return (ERROR_FILE_EXISTS);

		status = dfs_link_getinfo(path, &info, DFS_INFO_ALL);
		if (status != ERROR_SUCCESS)
			return (status);

		break;

	case DFS_STAT_NOTLINK:
		/* specified path points to a non-reparse object */
		return (ERROR_FILE_EXISTS);

	default:
		return (ERROR_INTERNAL_ERROR);
	}

	/* checks to see if the target already exists */
	ntargets = info.i_ntargets;
	if (dfs_target_find(info.i_targets, ntargets, server, share) != -1) {
		dfs_info_free(&info);
		return (ERROR_FILE_EXISTS);
	}

	/* add the new target */
	t = realloc(info.i_targets, (ntargets + 1) * sizeof (dfs_target_t));
	if (t == NULL) {
		dfs_info_free(&info);
		return (ERROR_NOT_ENOUGH_MEMORY);
	}

	info.i_targets = t;
	dfs_target_init(&info.i_targets[ntargets], server, share,
	    DFS_STORAGE_STATE_ONLINE);
	info.i_ntargets++;

	status = dfs_link_commit(path, &info);

	dfs_info_free(&info);
	return (status);
}

/*
 * Removes a link or a link target from a DFS namespace. A link can be
 * removed regardless of the number of targets associated with it.
 *
 * 'server' and 'share' parameters specify a target, so if they are NULL
 * it means the link should be removed, otherwise the specified target
 * is removed if found.
 */
uint32_t
dfs_link_remove(const char *path, const char *server, const char *share)
{
	dfs_info_t info;
	uint32_t status, stat;
	int rc, idx;

	if ((status = dfs_link_stat(path, &stat)) != ERROR_SUCCESS)
		return (status);

	if (stat != DFS_STAT_ISDFS)
		return (ERROR_NOT_FOUND);

	if (server == NULL && share == NULL) {
		/* remove the link */
		if (smb_reparse_svcdel(path, DFS_REPARSE_SVCTYPE) != 0)
			return (ERROR_INTERNAL_ERROR);

		return (ERROR_SUCCESS);
	}

	/* remove the specified target in the link */

	status = dfs_link_getinfo(path, &info, DFS_INFO_ALL);
	if (status != ERROR_SUCCESS)
		return (status);

	/* checks to see if the target exists */
	idx = dfs_target_find(info.i_targets, info.i_ntargets, server, share);
	if (idx != -1) {
		bcopy(&info.i_targets[idx + 1], &info.i_targets[idx],
		    (info.i_ntargets - idx - 1) * sizeof (dfs_target_t));
		info.i_ntargets--;
	} else {
		dfs_info_free(&info);
		return (ERROR_FILE_NOT_FOUND);
	}

	if (info.i_ntargets == 0) {
		/* if last target, then remove the link */
		rc = smb_reparse_svcdel(path, DFS_REPARSE_SVCTYPE);
		status = (rc == 0) ? ERROR_SUCCESS : ERROR_INTERNAL_ERROR;
	} else {
		status = dfs_link_commit(path, &info);
	}

	dfs_info_free(&info);
	return (status);
}

/*
 * Sets the provided information for the specified link or link target.
 * Link is specified by 'path' and the target is specified by
 * (t_server, t_share) pair. Only information items needed for given
 * information level (infolvl) is valid in the passed DFS info structure
 * 'info'.
 */
uint32_t
dfs_link_setinfo(const char *path, dfs_info_t *info, uint32_t infolvl)
{
	dfs_info_t curinfo;
	uint32_t status;

	status = dfs_link_getinfo(path, &curinfo, DFS_INFO_ALL);
	if (status != ERROR_SUCCESS)
		return (status);

	status = dfs_modinfo(DFS_OBJECT_LINK, &curinfo, info, infolvl);
	if (status == ERROR_SUCCESS)
		status = dfs_link_commit(path, &curinfo);

	dfs_info_free(&curinfo);
	return (status);
}

/*
 * Gets the DFS link info.
 *
 * If path is NULL, it just does some initialization.
 *
 * Info level (1) only needs the UNC path which is not
 * stored, it is constructed so the function will return
 * without accessing the backend storage.
 */
uint32_t
dfs_link_getinfo(const char *path, dfs_info_t *info, uint32_t infolvl)
{
	char *link_data;
	uint32_t status;
	uuid_t uuid;
	int rc;

	bzero(info, sizeof (dfs_info_t));
	info->i_type = DFS_OBJECT_LINK;

	if (path == NULL) {
		info->i_state = DFS_VOLUME_STATE_OK;
		info->i_timeout = DFS_LINK_TIMEOUT;
		info->i_propflags = 0;
		uuid_generate_random(uuid);
		uuid_unparse(uuid, info->i_guid);
		return (ERROR_SUCCESS);
	}

	if (infolvl == 1)
		return (ERROR_SUCCESS);

	rc = smb_reparse_svcget(path, DFS_REPARSE_SVCTYPE, &link_data);
	if (rc != 0)
		return (ERROR_INTERNAL_ERROR);

	status = dfs_link_decode(info, link_data, infolvl);
	free(link_data);

	return (status);
}

/*
 * ===================
 * Cache API (public)
 * ===================
 */

/*
 * Adds an entry with given DFS name (root sharename) and relative path
 * to the share (relpath) and the specified entry type (i.e. root/link)
 * to the namespace cache.
 */
uint32_t
dfs_cache_add_byname(const char *name, const char *relpath, uint32_t type)
{
	char uncpath[DFS_PATH_MAX];
	char fspath[DFS_PATH_MAX];
	smb_share_t si;

	if (smb_shr_get((char *)name, &si) != NERR_Success)
		return (ERROR_NOT_FOUND);

	if (type == DFS_OBJECT_ROOT) {
		(void) snprintf(uncpath, DFS_PATH_MAX, "\\\\%s\\%s",
		    dfs_nbname, name);
		return (dfs_cache_add_byunc(uncpath, si.shr_path, type));
	}

	/* add link entry */
	(void) snprintf(fspath, DFS_PATH_MAX, "%s/%s", si.shr_path, relpath);
	(void) snprintf(uncpath, DFS_PATH_MAX, "\\\\%s\\%s\\%s", dfs_nbname,
	    name, relpath);

	/* relpath may contain '/' */
	(void) strsubst(uncpath, '/', '\\');

	return (dfs_cache_add_byunc(uncpath, fspath, type));
}

/*
 * Removes the namespace cache entry for the given link
 * in the namespace ('name') with 'relpath'
 */
void
dfs_cache_remove(const char *name, const char *relpath)
{
	dfs_nscnode_t dn;

	(void) snprintf(dn.nsc_uncpath, sizeof (dn.nsc_uncpath),
	    "\\\\%s\\%s\\%s", dfs_nbname, name, relpath);

	/* relpath may contain '/' */
	(void) strsubst(dn.nsc_uncpath, '/', '\\');

	smb_cache_remove(&dfs_nscache, &dn);
}

/*
 * Get the DFS data for the specified cache entry
 */
uint32_t
dfs_cache_getinfo(dfs_nscnode_t *dn, dfs_info_t *info, uint32_t infolvl)
{
	uint32_t status;

	if (dn->nsc_type == DFS_OBJECT_LINK)
		status = dfs_link_getinfo(dn->nsc_fspath, info, infolvl);
	else
		status = dfs_root_getinfo(dn->nsc_fspath, info, infolvl);

	(void) strlcpy(info->i_uncpath, dn->nsc_uncpath,
	    sizeof (info->i_uncpath));

	if (status == ERROR_SUCCESS)
		dfs_info_trace("dfs_cache_getinfo", info);

	return (status);
}

/*
 * Returns the number of cache entries i.e. the number of
 * root(s) and link(s)
 */
uint32_t
dfs_cache_num(void)
{
	return (smb_cache_num(&dfs_nscache));
}

void
dfs_cache_iterinit(smb_cache_cursor_t *cursor)
{
	smb_cache_iterinit(&dfs_nscache, cursor);
}

boolean_t
dfs_cache_iterate(smb_cache_cursor_t *cursor, dfs_nscnode_t *dn)
{
	return (smb_cache_iterate(&dfs_nscache, cursor, dn));
}

/*
 * ==================
 * Misc API (public)
 * ==================
 */

/*
 * This is the function that is called by smbd door server to
 * fullfil a GetReferrals request from smbsrv kernel module
 *
 * 'reftype' specifies the requested referral type. If it is
 * DFS_REFERRAL_ROOT then dfs_path should point to a namespace
 * root. If it is DFS_REFERRAL_LINK then dfs_path should CONTAIN
 * a link, in which case this function will find the link and
 * returns its target information.
 */
uint32_t
dfs_get_referrals(const char *dfs_path, dfs_reftype_t reftype,
    dfs_info_t *referrals)
{
	dfs_path_t path;
	smb_unc_t *unc;
	char linkpath[DFS_PATH_MAX];
	uint32_t status;

	status = dfs_path_parse(&path, dfs_path, DFS_OBJECT_ANY);
	if (status != ERROR_SUCCESS)
		return (status);

	dfs_setpriv(PRIV_ON);

	referrals->i_type = path.p_type;

	switch (reftype) {
	case DFS_REFERRAL_ROOT:
		if (path.p_type != DFS_OBJECT_ROOT) {
			status = ERROR_INVALID_PARAMETER;
			break;
		}

		status = dfs_root_getinfo((const char *)path.p_fspath,
		    referrals, DFS_INFO_ALL);
		(void) strlcpy(referrals->i_uncpath, dfs_path, DFS_PATH_MAX);
		break;

	case DFS_REFERRAL_LINK:
		if (path.p_type != DFS_OBJECT_LINK) {
			status = ERROR_INVALID_PARAMETER;
			break;
		}

		unc = &path.p_unc;
		if (!dfs_namespace_findlink(unc->unc_share, unc->unc_path,
		    linkpath, DFS_PATH_MAX)) {
			status = ERROR_NOT_FOUND;
			break;
		}

		status = dfs_link_getinfo(linkpath, referrals, DFS_INFO_ALL);
		(void) snprintf(referrals->i_uncpath, DFS_PATH_MAX, "/%s/%s/%s",
		    unc->unc_server, unc->unc_share, unc->unc_path);
		break;

	default:
		status = ERROR_INVALID_PARAMETER;
		break;
	}

	dfs_setpriv(PRIV_OFF);
	dfs_path_free(&path);
	return (status);
}

/*
 * Takes a DFS path in UNC format (dfs_path) and parse it into a dfs_path_t
 * structure.
 *
 * dfs_path_free() MUST be called to free the allocated memory in this
 * function.
 *
 * Returns:
 *
 * ERROR_INVALID_PARAMETER	path is not a valid UNC or not valid for the
 * 				specified object type
 * ERROR_NOT_ENOUGH_MEMORY	not enough memory to peform the parse
 * ERROR_NOT_FOUND		namespace specified does not exist
 */
uint32_t
dfs_path_parse(dfs_path_t *path, const char *dfs_path, uint32_t path_type)
{
	char rootdir[DFS_PATH_MAX];
	smb_unc_t *unc;
	uint32_t status = ERROR_SUCCESS;
	int rc;

	bzero(path, sizeof (dfs_path_t));
	unc = &path->p_unc;

	rc = smb_unc_init(dfs_path, unc);
	switch (rc) {
	case EINVAL:
		return (ERROR_INVALID_PARAMETER);
	case ENOMEM:
		return (ERROR_NOT_ENOUGH_MEMORY);
	default:
		break;
	}

	if (dfs_namespace_path(unc->unc_share, rootdir, DFS_PATH_MAX)
	    != ERROR_SUCCESS) {
		smb_unc_free(unc);
		return (ERROR_NOT_FOUND);
	}

	if (path_type == DFS_OBJECT_ANY)
		path->p_type = (unc->unc_path != NULL)
		    ? DFS_OBJECT_LINK : DFS_OBJECT_ROOT;
	else
		path->p_type = path_type;

	switch (path->p_type) {
	case DFS_OBJECT_LINK:
		if ((unc->unc_path == NULL) || (*unc->unc_path == '\0'))
			status = ERROR_NOT_FOUND;
		else
			(void) snprintf(path->p_fspath, sizeof (path->p_fspath),
			    "%s/%s", rootdir, unc->unc_path);
		break;

	case DFS_OBJECT_ROOT:
		if (unc->unc_path == NULL)
			(void) strlcpy(path->p_fspath, rootdir,
			    sizeof (path->p_fspath));
		else
			status = ERROR_INVALID_PARAMETER;
		break;

	default:
		status = ERROR_INVALID_PARAMETER;
	}

	if (status != ERROR_SUCCESS)
		smb_unc_free(unc);

	return (status);
}

/*
 * Frees the allocated memory for p_unc field of the passed path
 */
void
dfs_path_free(dfs_path_t *path)
{
	if (path != NULL)
		smb_unc_free(&path->p_unc);
}

/*
 * Free the allocated memory for targets in the given info
 * structure
 */
void
dfs_info_free(dfs_info_t *info)
{
	if (info)
		free(info->i_targets);
}

/*
 * Trace the given DFS info structure
 */
void
dfs_info_trace(const char *msg, dfs_info_t *info)
{
	dfs_target_t *t;
	int i;

	smb_tracef("%s", msg);
	if (info == NULL)
		return;

	smb_tracef("UNC\t%s", info->i_uncpath);
	smb_tracef("comment\t%s", info->i_comment);
	smb_tracef("GUID\t%s", info->i_guid);
	smb_tracef("state\t%X", info->i_state);
	smb_tracef("timeout\t%d", info->i_timeout);
	smb_tracef("props\t%X", info->i_propflags);
	smb_tracef("# targets\t%X", info->i_ntargets);

	if (info->i_targets == NULL)
		return;

	for (i = 0, t = info->i_targets; i < info->i_ntargets; i++, t++) {
		smb_tracef("[%d] \\\\%s\\%s", i, t->t_server, t->t_share);
		smb_tracef("[%d] state\t%X", i, t->t_state);
		smb_tracef("[%d] priority\t%d:%d", i, t->t_priority.p_class,
		    t->t_priority.p_rank);
	}
}

/*
 * Search the path specified by 'relpath' to see if it contains
 * a DFS link starting from the last component. If a link is found
 * the full path is returned in 'linkpath'
 */
static boolean_t
dfs_namespace_findlink(const char *name, char *relpath,
    char *linkpath, size_t bufsz)
{
	char rootdir[DFS_PATH_MAX];
	uint32_t stat;
	char *p;

	if (dfs_namespace_path(name, rootdir, DFS_PATH_MAX) != ERROR_SUCCESS)
		return (B_FALSE);

	(void) snprintf(linkpath, bufsz, "%s/%s", rootdir, relpath);

	for (;;) {
		if (dfs_link_stat(linkpath, &stat) != ERROR_SUCCESS)
			return (B_FALSE);

		if (stat == DFS_STAT_ISDFS)
			return (B_TRUE);

		if ((p = strrchr(relpath, '/')) == NULL)
			return (B_FALSE);
		*p = '\0';

		(void) snprintf(linkpath, bufsz, "%s/%s", rootdir, relpath);
	}

	/*NOTREACHED*/
	return (B_FALSE);
}

/*
 * Caches the specified namespace
 */
static void *
dfs_namespace_cache(void *arg)
{
	char *share = arg;
	char uncpath[DFS_PATH_MAX];
	smb_share_t si;

	if (smb_shr_get(share, &si) != NERR_Success) {
		free(share);
		return (NULL);
	}

	/*
	 * This check should be removed when multiple standalone
	 * namespaces are supported.
	 */
	(void) mutex_lock(&dfs_nsmtx);
	if (*dfs_cached_ns != '\0') {
		syslog(LOG_WARNING, "dfs: trying to load %s namespace."
		    " Only one standalone namespace is supported."
		    " A namespace is already exported for %s",
		    share, dfs_cached_ns);
		(void) mutex_unlock(&dfs_nsmtx);
		free(share);
		return (NULL);
	}
	(void) strlcpy(dfs_cached_ns, share, sizeof (dfs_cached_ns));
	(void) smb_config_setnum(SMB_CI_DFS_STDROOT_NUM, 1);
	(void) mutex_unlock(&dfs_nsmtx);

	(void) snprintf(uncpath, DFS_PATH_MAX, "\\\\%s\\%s", dfs_nbname, share);
	(void) dfs_cache_add_byunc(uncpath, si.shr_path, DFS_OBJECT_ROOT);

	dfs_cache_populate(uncpath, si.shr_path);

	free(share);
	return (NULL);
}

/*
 * Checks whether the given name matches the name of
 * the cached namespace.
 */
static boolean_t
dfs_namespace_iscached(const char *name)
{
	boolean_t iscached;

	(void) mutex_lock(&dfs_nsmtx);
	iscached = (smb_strcasecmp(name, dfs_cached_ns, 0) == 0);
	(void) mutex_unlock(&dfs_nsmtx);

	return (iscached);
}

static int
dfs_root_add(const char *rootdir, dfs_info_t *info)
{
	uint32_t status = ERROR_INTERNAL_ERROR;
	int xfd;

	(void) rw_wrlock(&dfs_root_rwl);
	if ((xfd = dfs_root_xopen(rootdir, O_CREAT | O_TRUNC | O_RDWR)) > 0) {
		status = dfs_root_xwrite(xfd, info);
		dfs_root_xclose(xfd);
	}
	(void) rw_unlock(&dfs_root_rwl);

	return (status);
}

/*
 * Deletes the specified root information
 */
static uint32_t
dfs_root_remove(const char *rootdir)
{
	int attrdirfd;
	int err = 0;

	(void) rw_wrlock(&dfs_root_rwl);

	if ((attrdirfd = attropen(rootdir, ".", O_RDONLY)) > 0) {
		if (unlinkat(attrdirfd, DFS_ROOT_XATTR, 0) == -1) {
			if (errno != ENOENT)
				err = errno;
		}
		(void) close(attrdirfd);
	} else {
		err = errno;
	}

	(void) rw_unlock(&dfs_root_rwl);

	if (err != 0) {
		syslog(LOG_DEBUG, "dfs: failed to remove root info %s (%d)",
		    rootdir, err);
		return (ERROR_INTERNAL_ERROR);
	}

	return (ERROR_SUCCESS);
}

/*
 * Opens DFS root directory's extended attribute with the given mode.
 */
static int
dfs_root_xopen(const char *rootdir, int oflag)
{
	int dfd;
	int xfd = -1;
	int err = 0;

	if ((dfd = open(rootdir, O_RDONLY)) > 0) {
		xfd = openat(dfd, DFS_ROOT_XATTR, oflag | O_XATTR, 0600);
		if (xfd == -1)
			err = errno;
		(void) close(dfd);
	} else {
		err = errno;
	}

	if (err != 0) {
		syslog(LOG_DEBUG, "dfs: failed to open root directory %s (%d)",
		    rootdir, err);
	}

	return (xfd);
}

/*
 * Closes given extended attribute file descriptor
 */
static void
dfs_root_xclose(int xfd)
{
	(void) close(xfd);
}

/*
 * Writes the given DFS data in the DFS root directory's
 * extended attribute specified with xfd file descriptor.
 */
static uint32_t
dfs_root_xwrite(int xfd, dfs_info_t *info)
{
	size_t nbytes;
	char *buf = NULL;
	size_t buflen;
	uint32_t status;

	if ((status = dfs_root_encode(info, &buf, &buflen)) != ERROR_SUCCESS)
		return (status);

	(void) lseek(xfd, 0, SEEK_SET);
	nbytes = write(xfd, buf, buflen);
	free(buf);

	return ((nbytes == buflen) ? ERROR_SUCCESS : ERROR_INTERNAL_ERROR);
}

/*
 * Reads DFS root information from its directory extended attribute
 * and parse it into given dfs_info_t structure
 */
static uint32_t
dfs_root_xread(int xfd, dfs_info_t *info, uint32_t infolvl)
{
	struct stat statbuf;
	uint32_t status;
	char *buf;

	if (fstat(xfd, &statbuf) != 0)
		return (ERROR_INTERNAL_ERROR);

	if ((buf = malloc(statbuf.st_size)) == NULL)
		return (ERROR_NOT_ENOUGH_MEMORY);

	if (read(xfd, buf, statbuf.st_size) == statbuf.st_size)
		status = dfs_root_decode(info, buf, statbuf.st_size, infolvl);
	else
		status = ERROR_INTERNAL_ERROR;

	free(buf);
	return (status);
}

/*
 * Encodes (packs) DFS information in 'info' into a flat
 * buffer in a name-value format. This function allocates a
 * buffer with appropriate size to contain all the information
 * so the caller MUST free the allocated memory by calling free().
 */
static uint32_t
dfs_root_encode(dfs_info_t *info, char **buf, size_t *bufsz)
{
	dfs_target_t *t;
	nvlist_t *nvl;
	int rc;

	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
		return (ERROR_NOT_ENOUGH_MEMORY);

	rc = nvlist_add_string(nvl, "comment", info->i_comment);
	rc |= nvlist_add_string(nvl, "guid", info->i_guid);
	rc |= nvlist_add_uint32(nvl, "state", info->i_state);
	rc |= nvlist_add_uint32(nvl, "timeout", info->i_timeout);
	rc |= nvlist_add_uint32(nvl, "propflags", info->i_propflags);
	t = info->i_targets;
	rc |= nvlist_add_string(nvl, "t_server", t->t_server);
	rc |= nvlist_add_string(nvl, "t_share", t->t_share);
	rc |= nvlist_add_uint32(nvl, "t_state", t->t_state);
	rc |= nvlist_add_uint32(nvl, "t_priority_class",
	    t->t_priority.p_class);
	rc |= nvlist_add_uint16(nvl, "t_priority_rank",
	    t->t_priority.p_rank);

	if (rc == 0)
		rc = nvlist_pack(nvl, buf, bufsz, NV_ENCODE_NATIVE, 0);

	nvlist_free(nvl);

	return ((rc == 0) ? ERROR_SUCCESS : ERROR_INTERNAL_ERROR);
}

/*
 * Decodes (unpack) provided buffer which contains a list of name-value
 * pairs into given dfs_info_t structure
 */
static uint32_t
dfs_root_decode(dfs_info_t *info, char *buf, size_t bufsz, uint32_t infolvl)
{
	nvlist_t *nvl;
	char *cmnt, *guid;
	char *t_server, *t_share;
	uint32_t t_state;
	uint32_t t_priority_class;
	uint16_t t_priority_rank;
	boolean_t decode_priority = B_FALSE;
	int rc;

	if (nvlist_unpack(buf, bufsz, &nvl, 0) != 0)
		return (ERROR_INTERNAL_ERROR);

	rc = nvlist_lookup_string(nvl, "comment", &cmnt);
	rc |= nvlist_lookup_string(nvl, "guid", &guid);
	rc |= nvlist_lookup_uint32(nvl, "state", &info->i_state);
	rc |= nvlist_lookup_uint32(nvl, "timeout", &info->i_timeout);
	rc |= nvlist_lookup_uint32(nvl, "propflags", &info->i_propflags);

	if (rc != 0) {
		nvlist_free(nvl);
		return (ERROR_INTERNAL_ERROR);
	}

	(void) strlcpy(info->i_comment, (cmnt) ? cmnt : "",
	    sizeof (info->i_comment));
	(void) strlcpy(info->i_guid, (guid) ? guid : "", sizeof (info->i_guid));

	info->i_targets = NULL;
	info->i_ntargets = 1;

	switch (infolvl) {
	case DFS_INFO_ALL:
	case 3:
	case 4:
		/* need target information */
		break;
	case 6:
	case 9:
		/* need target and priority information */
		decode_priority = B_TRUE;
		break;
	default:
		nvlist_free(nvl);
		return (ERROR_SUCCESS);
	}

	info->i_targets = malloc(sizeof (dfs_target_t));
	if (info->i_targets == NULL) {
		nvlist_free(nvl);
		return (ERROR_NOT_ENOUGH_MEMORY);
	}

	rc = nvlist_lookup_string(nvl, "t_server", &t_server);
	rc |= nvlist_lookup_string(nvl, "t_share", &t_share);
	rc |= nvlist_lookup_uint32(nvl, "t_state", &t_state);
	if (rc != 0) {
		nvlist_free(nvl);
		free(info->i_targets);
		return (ERROR_INTERNAL_ERROR);
	}
	dfs_target_init(info->i_targets, t_server, t_share, t_state);

	if (decode_priority) {
		rc = nvlist_lookup_uint32(nvl, "t_priority_class",
		    &t_priority_class);
		if (rc == 0)
			rc = nvlist_lookup_uint16(nvl, "t_priority_rank",
			    &t_priority_rank);

		if (rc != 0 && rc != ENOENT) {
			nvlist_free(nvl);
			free(info->i_targets);
			return (ERROR_INTERNAL_ERROR);
		} else if (rc == 0) {
			info->i_targets->t_priority.p_class = t_priority_class;
			info->i_targets->t_priority.p_rank = t_priority_rank;
		}
	}

	nvlist_free(nvl);
	return (ERROR_SUCCESS);
}

/*
 * Determines if the passed state is valid for a DFS root
 *
 * This is based on test results against Win2003 and in some cases
 * does not match [MS-DFSNM] spec.
 */
static uint32_t
dfs_root_isvalidstate(uint32_t state)
{
	switch (state) {
	case DFS_VOLUME_STATE_OK:
	case DFS_VOLUME_STATE_RESYNCHRONIZE:
		return (ERROR_SUCCESS);

	case DFS_VOLUME_STATE_INCONSISTENT:
	case DFS_VOLUME_STATE_FORCE_SYNC:
		return (ERROR_INVALID_PARAMETER);

	case DFS_VOLUME_STATE_OFFLINE:
	case DFS_VOLUME_STATE_ONLINE:
	case DFS_VOLUME_STATE_STANDBY:
		return (ERROR_NOT_SUPPORTED);
	default:
		break;
	}

	return (ERROR_INVALID_PARAMETER);
}

/*
 * Decodes the link info from given string buffer (buf) into
 * dfs_info_t structure.
 */
static uint32_t
dfs_link_decode(dfs_info_t *info, char *buf, uint32_t infolvl)
{
	char *lfield[DFS_LINK_HDR_NFIELDS];
	dfs_target_t *t;
	uint32_t linkver;
	uint32_t cmntlen;
	uint32_t cpylen;
	int i, j;

	/*
	 * Header format
	 * ver:state:prop:timeout:guid:ntarget:cmntlen:comment:
	 */
	for (i = 0; i < DFS_LINK_HDR_NFIELDS; i++) {
		if ((lfield[i] = strsep((char **)&buf, ":")) == NULL)
			return (ERROR_INVALID_DATA);
	}

	i = 0;
	linkver = strtoul(lfield[i++], NULL, 10);
	if (linkver != DFS_LINK_V1)
		return (ERROR_INVALID_DATA);

	info->i_state = strtoul(lfield[i++], NULL, 10);
	info->i_propflags = strtoul(lfield[i++], NULL, 10);
	info->i_timeout = strtoul(lfield[i++], NULL, 10);
	(void) strlcpy(info->i_guid, lfield[i++], sizeof (info->i_guid));
	info->i_ntargets = strtoul(lfield[i++], NULL, 10);
	info->i_targets = NULL;

	cpylen = cmntlen = strtoul(lfield[i++], NULL, 10);

	if (cmntlen > sizeof (info->i_comment))
		cpylen = sizeof (info->i_comment);
	else if (cmntlen != 0)
		cpylen = cmntlen + 1;

	(void) strlcpy(info->i_comment, buf, cpylen);
	buf += (cmntlen + 1);

	switch (infolvl) {
	case DFS_INFO_ALL:
	case 3:
	case 4:
	case 6:
	case 9:
		/* need target information */
		break;
	default:
		return (ERROR_SUCCESS);
	}

	info->i_targets = calloc(info->i_ntargets, sizeof (dfs_target_t));
	if (info->i_targets == NULL)
		return (ERROR_NOT_ENOUGH_MEMORY);

	/*
	 * Format for each target
	 * server:share:state:class:rank
	 */
	for (i = 0, t = info->i_targets; i < info->i_ntargets; i++, t++) {
		for (j = 0; j < DFS_LINK_TRGT_NFIELDS; j++) {
			if ((lfield[j] = strsep((char **)&buf, ":")) == NULL) {
				dfs_info_free(info);
				return (ERROR_INVALID_DATA);
			}
		}

		(void) strlcpy(t->t_server, lfield[0], sizeof (t->t_server));
		(void) strlcpy(t->t_share, lfield[1], sizeof (t->t_share));
		t->t_state = strtoul(lfield[2], NULL, 10);
		t->t_priority.p_class = strtoul(lfield[3], NULL, 10);
		t->t_priority.p_rank = strtoul(lfield[4], NULL, 10);
	}

	return (ERROR_SUCCESS);
}

/*
 * Encodes given link information (info)
 */
static uint32_t
dfs_link_encode(dfs_info_t *info, char *buf, size_t bufsz)
{
	char linkdata[MAXREPARSELEN];
	dfs_target_t *t;
	int i, sz;

	/*
	 * Header format
	 * ver:state:prop:timeout:guid:ntarget:cmntlen:comment
	 */
	sz = snprintf(buf, bufsz, "%u:%u:%u:%u:%s:%u:%u:%s",
	    DFS_LINK_V1, info->i_state, info->i_propflags, info->i_timeout,
	    info->i_guid, info->i_ntargets,
	    strlen(info->i_comment), info->i_comment);

	if (sz > bufsz) {
		syslog(LOG_WARNING, "dfs: link data is too large");
		dfs_info_trace("DFS link encode", info);
		return (ERROR_INTERNAL_ERROR);
	}

	/*
	 * Format for each target
	 * :server:share:state:class:rank
	 */
	bufsz -= sz;
	for (i = 0, t = info->i_targets; i < info->i_ntargets; i++, t++) {
		if (strchr(t->t_server, ':') || strchr(t->t_share, ':'))
			return (ERROR_INVALID_NAME);

		sz = snprintf(linkdata, MAXREPARSELEN, ":%s:%s:%u:%u:%u",
		    t->t_server, t->t_share, t->t_state,
		    t->t_priority.p_class, t->t_priority.p_rank);
		if (sz > bufsz) {
			syslog(LOG_WARNING, "dfs: link data is too large");
			dfs_info_trace("DFS link encode", info);
			return (ERROR_INTERNAL_ERROR);
		}
		(void) strcat(buf, linkdata);
		bufsz -= sz;
	}

	return (ERROR_SUCCESS);
}

/*
 * Stores given information for the specified link
 */
static uint32_t
dfs_link_commit(const char *path, dfs_info_t *info)
{
	char linkdata[MAXREPARSELEN];
	uint32_t status;
	int rc;

	status = dfs_link_encode(info, linkdata, MAXREPARSELEN);
	if (status == ERROR_SUCCESS) {
		rc = smb_reparse_svcadd(path, DFS_REPARSE_SVCTYPE, linkdata);
		if (rc != 0)
			status = ERROR_INTERNAL_ERROR;
	}

	return (status);
}

/*
 * Determines if the passed state is valid for a link
 */
static boolean_t
dfs_link_isvalidstate(uint32_t state)
{
	return (state == DFS_VOLUME_STATE_OK ||
	    state == DFS_VOLUME_STATE_OFFLINE ||
	    state == DFS_VOLUME_STATE_ONLINE);
}

/*
 * Initializes the given target structure (t) with provided information.
 */
static void
dfs_target_init(dfs_target_t *t, const char *srv, const char *share,
    uint32_t state)
{
	(void) strlcpy(t->t_server, (srv) ? srv : "", sizeof (t->t_server));
	(void) strlcpy(t->t_share, (share) ? share : "", sizeof (t->t_share));
	t->t_state = state;
	t->t_priority.p_class = DfsSiteCostNormalPriorityClass;
	t->t_priority.p_rank = 0;
}

/*
 * Lookup the specified target (server, share) in the given
 * target list (targets). If there is a match its index is
 * returned, otherwise -1 will be returned.
 */
static int
dfs_target_find(dfs_target_t *targets, uint32_t ntargets,
    const char *server, const char *share)
{
	dfs_target_t *t;
	int i;

	for (i = 0, t = targets; i < ntargets; i++, t++) {
		if ((smb_strcasecmp(t->t_server, server, 0) == 0) &&
		    (smb_strcasecmp(t->t_share, share, 0) == 0))
			return (i);
	}

	return (-1);
}

/*
 * Determines if the passed state is valid for a link/root target
 */
static boolean_t
dfs_target_isvalidstate(uint32_t state)
{
	return (state == DFS_STORAGE_STATE_ONLINE ||
	    state == DFS_STORAGE_STATE_OFFLINE);
}

/*
 * Cache compare function, the key is UNC path
 */
static int
dfs_cache_cmp(const void *p1, const void *p2)
{
	smb_cache_node_t *cn1 = (smb_cache_node_t *)p1;
	smb_cache_node_t *cn2 = (smb_cache_node_t *)p2;
	dfs_nscnode_t *dn1 = cn1->cn_data;
	dfs_nscnode_t *dn2 = cn2->cn_data;
	int rc;

	rc = smb_strcasecmp(dn1->nsc_uncpath, dn2->nsc_uncpath, 0);

	if (rc < 0)
		return (-1);

	if (rc > 0)
		return (1);

	return (0);
}

/*
 * Adds an entry with given UNC and filesystem path and the specified
 * entry type (i.e. root/link) to the namespace cache.
 */
static uint32_t
dfs_cache_add_byunc(const char *uncpath, const char *fspath, uint32_t type)
{
	dfs_nscnode_t *dn;
	uint32_t status = ERROR_SUCCESS;

	if ((dn = malloc(sizeof (dfs_nscnode_t))) == NULL)
		return (ERROR_NOT_ENOUGH_MEMORY);

	(void) strlcpy(dn->nsc_uncpath, uncpath, sizeof (dn->nsc_uncpath));
	(void) strlcpy(dn->nsc_fspath, fspath, sizeof (dn->nsc_fspath));
	dn->nsc_type = type;
	if (smb_cache_add(&dfs_nscache, dn, SMB_CACHE_ADD) != 0) {
		free(dn);
		status = ERROR_INTERNAL_ERROR;
	}

	return (status);
}

/*
 * starting from DFS root directory, scans the tree for DFS links
 * and adds them to the cache.
 */
static void
dfs_cache_populate(const char *unc_prefix, const char *dir)
{
	char fspath[DFS_PATH_MAX];
	char uncpath[DFS_PATH_MAX];
	char *fname;
	int nentries, i;
	struct dirent **entry_list;
	uint32_t stat;

	nentries = scandir(dir, &entry_list, NULL, NULL);
	if (nentries == -1)
		return;

	for (i = 0; i < nentries; i++) {
		fname = entry_list[i]->d_name;

		if (strcmp(fname, ".") == 0 ||
		    strcmp(fname, "..") == 0) {
			free(entry_list[i]);
			continue;
		}

		(void) snprintf(fspath, DFS_PATH_MAX, "%s/%s", dir, fname);
		(void) snprintf(uncpath, DFS_PATH_MAX, "%s\\%s", unc_prefix,
		    fname);

		if (dfs_path_isdir(fspath)) {
			dfs_cache_populate(uncpath, fspath);
		} else if (dfs_link_stat(fspath, &stat) == ERROR_SUCCESS) {
			if (stat == DFS_STAT_ISDFS)
				(void) dfs_cache_add_byunc(uncpath, fspath,
				    DFS_OBJECT_LINK);
		}

		free(entry_list[i]);
	}

	for (; i < nentries; i++)
		free(entry_list[i]);

	free(entry_list);
}

/*
 * If this namespace hasn't been cached then return
 * without flushing the cache; otherwise clear the
 * name and flush the cache.
 */
static void
dfs_cache_flush(const char *name)
{
	(void) mutex_lock(&dfs_nsmtx);
	if (smb_strcasecmp(name, dfs_cached_ns, 0) != 0) {
		(void) mutex_unlock(&dfs_nsmtx);
		return;
	}
	*dfs_cached_ns = '\0';
	(void) smb_config_setnum(SMB_CI_DFS_STDROOT_NUM, 0);
	(void) mutex_unlock(&dfs_nsmtx);

	smb_cache_flush(&dfs_nscache);
}

/*
 * Returns the number of cached namespaces
 */
static uint32_t
dfs_cache_nscount(void)
{
	uint32_t nscount;

	(void) mutex_lock(&dfs_nsmtx);
	nscount = (*dfs_cached_ns == '\0') ? 0 : 1;
	(void) mutex_unlock(&dfs_nsmtx);

	return (nscount);
}

/*
 * Determines whether the given path is a directory.
 */
static boolean_t
dfs_path_isdir(const char *path)
{
	struct stat statbuf;

	if (lstat(path, &statbuf) != 0)
		return (B_FALSE);

	return ((statbuf.st_mode & S_IFMT) == S_IFDIR);
}

/*
 * Validates the given state based on the object type (root/link), info
 * level, and whether it is the object's state or its target's state
 */
static uint32_t
dfs_isvalidstate(uint32_t state, uint32_t type, boolean_t target,
    uint32_t infolvl)
{
	uint32_t status = ERROR_SUCCESS;

	switch (infolvl) {
	case 101:
		if (type == DFS_OBJECT_ROOT) {
			if (!target)
				return (dfs_root_isvalidstate(state));

			if (!dfs_target_isvalidstate(state))
				status = ERROR_INVALID_PARAMETER;
			else if (state == DFS_STORAGE_STATE_OFFLINE)
				status = ERROR_NOT_SUPPORTED;
		} else {
			if (!target) {
				if (!dfs_link_isvalidstate(state))
					status = ERROR_INVALID_PARAMETER;
			} else {
				if (!dfs_target_isvalidstate(state))
					status = ERROR_INVALID_PARAMETER;
			}
		}
		break;

	case 105:
		if (state == 0)
			return (ERROR_SUCCESS);

		if (type == DFS_OBJECT_ROOT) {
			switch (state) {
			case DFS_VOLUME_STATE_OK:
			case DFS_VOLUME_STATE_OFFLINE:
			case DFS_VOLUME_STATE_ONLINE:
			case DFS_VOLUME_STATE_RESYNCHRONIZE:
			case DFS_VOLUME_STATE_STANDBY:
				status = ERROR_NOT_SUPPORTED;
				break;

			default:
				status = ERROR_INVALID_PARAMETER;
			}
		} else {
			switch (state) {
			case DFS_VOLUME_STATE_OK:
			case DFS_VOLUME_STATE_OFFLINE:
			case DFS_VOLUME_STATE_ONLINE:
				break;

			case DFS_VOLUME_STATE_RESYNCHRONIZE:
			case DFS_VOLUME_STATE_STANDBY:
				status = ERROR_NOT_SUPPORTED;
				break;

			default:
				status = ERROR_INVALID_PARAMETER;
			}
		}
		break;

	default:
		status = ERROR_INVALID_LEVEL;
	}

	return (status);
}

/*
 * Validates the given property flag mask based on the object
 * type (root/link) and namespace flavor.
 */
static uint32_t
dfs_isvalidpropflagmask(uint32_t propflag_mask, uint32_t type,
    uint32_t flavor)
{
	uint32_t flgs_not_supported;

	flgs_not_supported = DFS_PROPERTY_FLAG_ROOT_SCALABILITY
	    | DFS_PROPERTY_FLAG_CLUSTER_ENABLED
	    | DFS_PROPERTY_FLAG_ABDE;

	if (flavor == DFS_VOLUME_FLAVOR_STANDALONE) {
		if (type == DFS_OBJECT_LINK)
			flgs_not_supported |= DFS_PROPERTY_FLAG_SITE_COSTING;
		if (propflag_mask & flgs_not_supported)
			return (ERROR_NOT_SUPPORTED);
	}

	return (ERROR_SUCCESS);
}

/*
 * Based on the specified information level (infolvl) copy parts of the
 * information provided through newinfo into the existing information
 * (info) for the given object.
 */
static uint32_t
dfs_modinfo(uint32_t type, dfs_info_t *info, dfs_info_t *newinfo,
    uint32_t infolvl)
{
	boolean_t target_op = B_FALSE;
	uint32_t status = ERROR_SUCCESS;
	uint32_t state;
	int target_idx;

	if (newinfo->i_targets != NULL) {
		target_idx = dfs_target_find(info->i_targets, info->i_ntargets,
		    newinfo->i_targets->t_server, newinfo->i_targets->t_share);
		if (target_idx == -1)
			return (ERROR_FILE_NOT_FOUND);
		target_op = B_TRUE;
	}

	switch (infolvl) {
	case 100:
		(void) strlcpy(info->i_comment, newinfo->i_comment,
		    sizeof (newinfo->i_comment));
		break;

	case 101:
		state = (target_op)
		    ? newinfo->i_targets->t_state : newinfo->i_state;
		status = dfs_isvalidstate(state, type, target_op, 101);
		if (status != ERROR_SUCCESS)
			return (status);

		if (!target_op) {
			/*
			 * states specified by this mask should not be stored
			 */
			if (state & DFS_VOLUME_STATES_SRV_OPS)
				return (ERROR_SUCCESS);

			info->i_state = state;
		} else {
			info->i_targets[target_idx].t_state = state;
		}
		break;

	case 102:
		info->i_timeout = newinfo->i_timeout;
		break;

	case 103:
		info->i_propflags = newinfo->i_propflags;
		break;

	case 104:
		info->i_targets[target_idx].t_priority =
		    newinfo->i_targets->t_priority;
		break;

	case 105:
		status = dfs_isvalidstate(newinfo->i_state, type, B_FALSE, 105);
		if (status != ERROR_SUCCESS)
			return (status);

		status = dfs_isvalidpropflagmask(newinfo->i_propflag_mask, type,
		    newinfo->i_flavor);
		if (status != ERROR_SUCCESS)
			return (status);

		(void) strlcpy(info->i_comment, newinfo->i_comment,
		    sizeof (newinfo->i_comment));
		if (newinfo->i_state != 0)
			info->i_state = newinfo->i_state;
		info->i_timeout = newinfo->i_timeout;
		info->i_propflags = newinfo->i_propflags;
		break;

	default:
		status = ERROR_INVALID_LEVEL;
	}

	return (status);
}