summaryrefslogtreecommitdiff
path: root/usr/src/lib/libzonecfg/common/libzonecfg.c
blob: c1500aa1847cedd4c4c00dc6f3bef52e1af339eb (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
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
/*
 * 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 2014 Gary Mills
 * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 2018, Joyent, Inc.
 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
 * Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
 */

#include <libsysevent.h>
#include <pthread.h>
#include <stdlib.h>
#include <errno.h>
#include <fnmatch.h>
#include <strings.h>
#include <unistd.h>
#include <assert.h>
#include <libgen.h>
#include <libintl.h>
#include <alloca.h>
#include <ctype.h>
#include <sys/acl.h>
#include <sys/stat.h>
#include <sys/brand.h>
#include <sys/mntio.h>
#include <sys/mnttab.h>
#include <sys/nvpair.h>
#include <sys/types.h>
#include <sys/sockio.h>
#include <sys/systeminfo.h>
#include <ftw.h>
#include <pool.h>
#include <libscf.h>
#include <libproc.h>
#include <sys/priocntl.h>
#include <libuutil.h>
#include <wait.h>
#include <bsm/adt.h>
#include <auth_attr.h>
#include <auth_list.h>
#include <secdb.h>
#include <user_attr.h>
#include <prof_attr.h>
#include <definit.h>

#include <arpa/inet.h>
#include <netdb.h>

#include <libxml/xmlmemory.h>
#include <libxml/parser.h>

#include <libdevinfo.h>
#include <uuid/uuid.h>
#include <dirent.h>
#include <libbrand.h>

#include <libzonecfg.h>
#include "zonecfg_impl.h"

#define	_PATH_TMPFILE	"/zonecfg.XXXXXX"
#define	ZONE_CB_RETRY_COUNT		10
#define	ZONE_EVENT_PING_SUBCLASS	"ping"
#define	ZONE_EVENT_PING_PUBLISHER	"solaris"

/* Hard-code the DTD element/attribute/entity names just once, here. */
#define	DTD_ELEM_ATTR		(const xmlChar *) "attr"
#define	DTD_ELEM_COMMENT	(const xmlChar *) "comment"
#define	DTD_ELEM_DEVICE		(const xmlChar *) "device"
#define	DTD_ELEM_FS		(const xmlChar *) "filesystem"
#define	DTD_ELEM_FSOPTION	(const xmlChar *) "fsoption"
#define	DTD_ELEM_NET		(const xmlChar *) "network"
#define	DTD_ELEM_RCTL		(const xmlChar *) "rctl"
#define	DTD_ELEM_RCTLVALUE	(const xmlChar *) "rctl-value"
#define	DTD_ELEM_ZONE		(const xmlChar *) "zone"
#define	DTD_ELEM_DATASET	(const xmlChar *) "dataset"
#define	DTD_ELEM_TMPPOOL	(const xmlChar *) "tmp_pool"
#define	DTD_ELEM_PSET		(const xmlChar *) "pset"
#define	DTD_ELEM_MCAP		(const xmlChar *) "mcap"
#define	DTD_ELEM_PACKAGE	(const xmlChar *) "package"
#define	DTD_ELEM_OBSOLETES	(const xmlChar *) "obsoletes"
#define	DTD_ELEM_DEV_PERM	(const xmlChar *) "dev-perm"
#define	DTD_ELEM_ADMIN		(const xmlChar *) "admin"
#define	DTD_ELEM_SECFLAGS	(const xmlChar *) "security-flags"

#define	DTD_ATTR_ACTION		(const xmlChar *) "action"
#define	DTD_ATTR_ADDRESS	(const xmlChar *) "address"
#define	DTD_ATTR_ALLOWED_ADDRESS	(const xmlChar *) "allowed-address"
#define	DTD_ATTR_AUTOBOOT	(const xmlChar *) "autoboot"
#define	DTD_ATTR_IPTYPE		(const xmlChar *) "ip-type"
#define	DTD_ATTR_DEFROUTER	(const xmlChar *) "defrouter"
#define	DTD_ATTR_DIR		(const xmlChar *) "directory"
#define	DTD_ATTR_LIMIT		(const xmlChar *) "limit"
#define	DTD_ATTR_LIMITPRIV	(const xmlChar *) "limitpriv"
#define	DTD_ATTR_BOOTARGS	(const xmlChar *) "bootargs"
#define	DTD_ATTR_SCHED		(const xmlChar *) "scheduling-class"
#define	DTD_ATTR_MATCH		(const xmlChar *) "match"
#define	DTD_ATTR_NAME		(const xmlChar *) "name"
#define	DTD_ATTR_PHYSICAL	(const xmlChar *) "physical"
#define	DTD_ATTR_POOL		(const xmlChar *) "pool"
#define	DTD_ATTR_PRIV		(const xmlChar *) "priv"
#define	DTD_ATTR_RAW		(const xmlChar *) "raw"
#define	DTD_ATTR_SPECIAL	(const xmlChar *) "special"
#define	DTD_ATTR_TYPE		(const xmlChar *) "type"
#define	DTD_ATTR_VALUE		(const xmlChar *) "value"
#define	DTD_ATTR_ZONEPATH	(const xmlChar *) "zonepath"
#define	DTD_ATTR_NCPU_MIN	(const xmlChar *) "ncpu_min"
#define	DTD_ATTR_NCPU_MAX	(const xmlChar *) "ncpu_max"
#define	DTD_ATTR_IMPORTANCE	(const xmlChar *) "importance"
#define	DTD_ATTR_PHYSCAP	(const xmlChar *) "physcap"
#define	DTD_ATTR_VERSION	(const xmlChar *) "version"
#define	DTD_ATTR_ID		(const xmlChar *) "id"
#define	DTD_ATTR_UID		(const xmlChar *) "uid"
#define	DTD_ATTR_GID		(const xmlChar *) "gid"
#define	DTD_ATTR_MODE		(const xmlChar *) "mode"
#define	DTD_ATTR_ACL		(const xmlChar *) "acl"
#define	DTD_ATTR_BRAND		(const xmlChar *) "brand"
#define	DTD_ATTR_HOSTID		(const xmlChar *) "hostid"
#define	DTD_ATTR_USER		(const xmlChar *) "user"
#define	DTD_ATTR_AUTHS		(const xmlChar *) "auths"
#define	DTD_ATTR_FS_ALLOWED	(const xmlChar *) "fs-allowed"
#define	DTD_ATTR_DEFAULT	(const xmlChar *) "default"
#define	DTD_ATTR_LOWER		(const xmlChar *) "lower"
#define	DTD_ATTR_UPPER		(const xmlChar *) "upper"


#define	DTD_ENTITY_BOOLEAN	"boolean"
#define	DTD_ENTITY_DEVPATH	"devpath"
#define	DTD_ENTITY_DRIVER	"driver"
#define	DTD_ENTITY_DRVMIN	"drv_min"
#define	DTD_ENTITY_FALSE	"false"
#define	DTD_ENTITY_INT		"int"
#define	DTD_ENTITY_STRING	"string"
#define	DTD_ENTITY_TRUE		"true"
#define	DTD_ENTITY_UINT		"uint"

#define	DTD_ENTITY_BOOL_LEN	6	/* "false" */

#define	ATTACH_FORCED	"SUNWattached.xml"

#define	TMP_POOL_NAME	"SUNWtmp_%s"
#define	MAX_TMP_POOL_NAME	(ZONENAME_MAX + 9)
#define	RCAP_SERVICE	"system/rcap:default"
#define	POOLD_SERVICE	"system/pools/dynamic:default"

/*
 * rctl alias definitions
 *
 * This holds the alias, the full rctl name, the default priv value, action
 * and lower limit.  The functions that handle rctl aliases step through
 * this table, matching on the alias, and using the full values for setting
 * the rctl entry as well the limit for validation.
 */
static struct alias {
	char *shortname;
	char *realname;
	char *priv;
	char *action;
	uint64_t low_limit;
} aliases[] = {
	{ALIAS_MAXLWPS, "zone.max-lwps", "privileged", "deny", 100},
	{ALIAS_MAXSHMMEM, "zone.max-shm-memory", "privileged", "deny", 0},
	{ALIAS_MAXSHMIDS, "zone.max-shm-ids", "privileged", "deny", 0},
	{ALIAS_MAXMSGIDS, "zone.max-msg-ids", "privileged", "deny", 0},
	{ALIAS_MAXSEMIDS, "zone.max-sem-ids", "privileged", "deny", 0},
	{ALIAS_MAXLOCKEDMEM, "zone.max-locked-memory", "privileged", "deny", 0},
	{ALIAS_MAXSWAP, "zone.max-swap", "privileged", "deny", 0},
	{ALIAS_SHARES, "zone.cpu-shares", "privileged", "none", 0},
	{ALIAS_CPUCAP, "zone.cpu-cap", "privileged", "deny", 0},
	{ALIAS_MAXPROCS, "zone.max-processes", "privileged", "deny", 100},
	{NULL, NULL, NULL, NULL, 0}
};

/*
 * Structure for applying rctls to a running zone.  It allows important
 * process values to be passed together easily.
 */
typedef struct pr_info_handle {
	struct ps_prochandle *pr;
	pid_t pid;
} pr_info_handle_t;

struct zone_dochandle {
	char		*zone_dh_rootdir;
	xmlDocPtr	zone_dh_doc;
	xmlNodePtr	zone_dh_cur;
	xmlNodePtr	zone_dh_top;
	boolean_t	zone_dh_newzone;
	boolean_t	zone_dh_snapshot;
	boolean_t	zone_dh_sw_inv;
	zone_userauths_t	*zone_dh_userauths;
	char		zone_dh_delete_name[ZONENAME_MAX];
};

struct znotify {
	void * zn_private;
	evchan_t *zn_eventchan;
	int (*zn_callback)(const  char *zonename, zoneid_t zid,
	    const char *newstate, const char *oldstate, hrtime_t when, void *p);
	pthread_mutex_t zn_mutex;
	pthread_cond_t zn_cond;
	pthread_mutex_t zn_bigmutex;
	volatile enum {ZN_UNLOCKED, ZN_LOCKED, ZN_PING_INFLIGHT,
	    ZN_PING_RECEIVED} zn_state;
	char zn_subscriber_id[MAX_SUBID_LEN];
	volatile boolean_t zn_failed;
	int zn_failure_count;
};

/* used to track nested zone-lock operations */
static int zone_lock_cnt = 0;

/* used to communicate lock status to children */
#define	LOCK_ENV_VAR	"_ZONEADM_LOCK_HELD"
static char zoneadm_lock_held[] = LOCK_ENV_VAR"=1";
static char zoneadm_lock_not_held[] = LOCK_ENV_VAR"=0";

char *zonecfg_root = "";

/*
 * For functions which return int, which is most of the functions herein,
 * the return values should be from the Z_foo set defined in <libzonecfg.h>.
 * In some instances, we take pains mapping some libc errno values to Z_foo
 * values from this set.
 */

/*
 * Set the root (/) path for all zonecfg configuration files.  This is a
 * private interface used by Live Upgrade extensions to access zone
 * configuration inside mounted alternate boot environments.
 * This interface is also used by zoneadm mount and unmount subcommands.
 */
void
zonecfg_set_root(const char *rootpath)
{
	if (*zonecfg_root != '\0')
		free(zonecfg_root);
	if (rootpath == NULL || rootpath[0] == '\0' || rootpath[1] == '\0' ||
	    (zonecfg_root = strdup(rootpath)) == NULL)
		zonecfg_root = "";
}

const char *
zonecfg_get_root(void)
{
	return (zonecfg_root);
}

boolean_t
zonecfg_in_alt_root(void)
{
	return (*zonecfg_root != '\0');
}

/*
 * Callers of the _file_path() functions are expected to have the second
 * parameter be a (char foo[MAXPATHLEN]).
 */

static boolean_t
config_file_path(const char *zonename, char *answer)
{
	return (snprintf(answer, MAXPATHLEN, "%s%s/%s.xml", zonecfg_root,
	    ZONE_CONFIG_ROOT, zonename) < MAXPATHLEN);
}

static boolean_t
snap_file_path(const char *zonename, char *answer)
{
	return (snprintf(answer, MAXPATHLEN, "%s%s/%s.snapshot.xml",
	    zonecfg_root, ZONE_SNAPSHOT_ROOT, zonename) < MAXPATHLEN);
}

/*ARGSUSED*/
static void
zonecfg_error_func(void *ctx, const char *msg, ...)
{
	/*
	 * This function does nothing by design.  Its purpose is to prevent
	 * libxml from dumping unwanted messages to stdout/stderr.
	 */
}

zone_dochandle_t
zonecfg_init_handle(void)
{
	zone_dochandle_t handle = calloc(1, sizeof (struct zone_dochandle));
	if (handle == NULL) {
		errno = Z_NOMEM;
		return (NULL);
	}

	/* generic libxml initialization */
	(void) xmlLineNumbersDefault(1);
	xmlLoadExtDtdDefaultValue |= XML_DETECT_IDS;
	xmlDoValidityCheckingDefaultValue = 1;
	(void) xmlKeepBlanksDefault(0);
	xmlGetWarningsDefaultValue = 0;
	xmlSetGenericErrorFunc(NULL, zonecfg_error_func);

	return (handle);
}

int
zonecfg_check_handle(zone_dochandle_t handle)
{
	if (handle == NULL || handle->zone_dh_doc == NULL)
		return (Z_BAD_HANDLE);
	return (Z_OK);
}

void
zonecfg_fini_handle(zone_dochandle_t handle)
{
	if (zonecfg_check_handle(handle) == Z_OK)
		xmlFreeDoc(handle->zone_dh_doc);
	if (handle != NULL)
		free(handle);
}

static int
zonecfg_destroy_impl(char *filename)
{
	if (unlink(filename) == -1) {
		if (errno == EACCES)
			return (Z_ACCES);
		if (errno == ENOENT)
			return (Z_NO_ZONE);
		return (Z_MISC_FS);
	}
	return (Z_OK);
}

int
zonecfg_destroy(const char *zonename, boolean_t force)
{
	char path[MAXPATHLEN];
	struct zoneent ze;
	int err, state_err;
	zone_state_t state;

	if (!config_file_path(zonename, path))
		return (Z_MISC_FS);

	state_err = zone_get_state((char *)zonename, &state);
	err = access(path, W_OK);

	/*
	 * If there is no file, and no index entry, reliably indicate that no
	 * such zone exists.
	 */
	if ((state_err == Z_NO_ZONE) && (err == -1) && (errno == ENOENT))
		return (Z_NO_ZONE);

	/*
	 * Handle any other filesystem related errors (except if the XML
	 * file is missing, which we treat silently), unless we're forcing,
	 * in which case we plow on.
	 */
	if (err == -1 && errno != ENOENT) {
		if (errno == EACCES)
			return (Z_ACCES);
		else if (!force)
			return (Z_MISC_FS);
	}

	if (state > ZONE_STATE_INSTALLED)
		return (Z_BAD_ZONE_STATE);

	if (!force && state > ZONE_STATE_CONFIGURED)
		return (Z_BAD_ZONE_STATE);

	/*
	 * Index deletion succeeds even if the entry doesn't exist.  So this
	 * will fail only if we've had some more severe problem.
	 */
	bzero(&ze, sizeof (ze));
	(void) strlcpy(ze.zone_name, zonename, sizeof (ze.zone_name));
	if ((err = putzoneent(&ze, PZE_REMOVE)) != Z_OK)
		if (!force)
			return (err);

	err = zonecfg_destroy_impl(path);

	/*
	 * Treat failure to find the XML file silently, since, well, it's
	 * gone, and with the index file cleaned up, we're done.
	 */
	if (err == Z_OK || err == Z_NO_ZONE)
		return (Z_OK);
	return (err);
}

int
zonecfg_destroy_snapshot(const char *zonename)
{
	char path[MAXPATHLEN];

	if (!snap_file_path(zonename, path))
		return (Z_MISC_FS);
	return (zonecfg_destroy_impl(path));
}

static int
getroot(zone_dochandle_t handle, xmlNodePtr *root)
{
	if (zonecfg_check_handle(handle) == Z_BAD_HANDLE)
		return (Z_BAD_HANDLE);

	*root = xmlDocGetRootElement(handle->zone_dh_doc);

	if (*root == NULL)
		return (Z_EMPTY_DOCUMENT);

	if (xmlStrcmp((*root)->name, DTD_ELEM_ZONE))
		return (Z_WRONG_DOC_TYPE);

	return (Z_OK);
}

static int
operation_prep(zone_dochandle_t handle)
{
	xmlNodePtr root;
	int err;

	if ((err = getroot(handle, &root)) != 0)
		return (err);

	handle->zone_dh_cur = root;
	handle->zone_dh_top = root;
	return (Z_OK);
}

static int
fetchprop(xmlNodePtr cur, const xmlChar *propname, char *dst, size_t dstsize)
{
	xmlChar *property;
	size_t srcsize;

	if ((property = xmlGetProp(cur, propname)) == NULL)
		return (Z_BAD_PROPERTY);
	srcsize = strlcpy(dst, (char *)property, dstsize);
	xmlFree(property);
	if (srcsize >= dstsize)
		return (Z_TOO_BIG);
	return (Z_OK);
}

static int
fetch_alloc_prop(xmlNodePtr cur, const xmlChar *propname, char **dst)
{
	xmlChar *property;

	if ((property = xmlGetProp(cur, propname)) == NULL)
		return (Z_BAD_PROPERTY);
	if ((*dst = strdup((char *)property)) == NULL) {
		xmlFree(property);
		return (Z_NOMEM);
	}
	xmlFree(property);
	return (Z_OK);
}

static int
getrootattr(zone_dochandle_t handle, const xmlChar *propname,
    char *propval, size_t propsize)
{
	xmlNodePtr root;
	int err;

	if ((err = getroot(handle, &root)) != 0)
		return (err);

	return (fetchprop(root, propname, propval, propsize));
}

static int
get_alloc_rootattr(zone_dochandle_t handle, const xmlChar *propname,
    char **propval)
{
	xmlNodePtr root;
	int err;

	if ((err = getroot(handle, &root)) != 0)
		return (err);

	return (fetch_alloc_prop(root, propname, propval));
}

static int
setrootattr(zone_dochandle_t handle, const xmlChar *propname,
    const char *propval)
{
	int err;
	xmlNodePtr root;

	if ((err = getroot(handle, &root)) != Z_OK)
		return (err);

	/*
	 * If we get a null propval remove the property (ignore return since it
	 * may not be set to begin with).
	 */
	if (propval == NULL) {
		(void) xmlUnsetProp(root, propname);
	} else {
		if (xmlSetProp(root, propname, (const xmlChar *) propval)
		    == NULL)
			return (Z_INVAL);
	}
	return (Z_OK);
}

static void
addcomment(zone_dochandle_t handle, const char *comment)
{
	xmlNodePtr node;
	node = xmlNewComment((xmlChar *) comment);

	if (node != NULL)
		(void) xmlAddPrevSibling(handle->zone_dh_top, node);
}

static void
stripcomments(zone_dochandle_t handle)
{
	xmlDocPtr top;
	xmlNodePtr child, next;

	top = handle->zone_dh_doc;
	for (child = top->xmlChildrenNode; child != NULL; child = next) {
		next = child->next;
		if (child->name == NULL)
			continue;
		if (xmlStrcmp(child->name, DTD_ELEM_COMMENT) == 0) {
			next = child->next;
			xmlUnlinkNode(child);
			xmlFreeNode(child);
		}
	}
}

static void
strip_sw_inv(zone_dochandle_t handle)
{
	xmlNodePtr root, child, next;

	root = xmlDocGetRootElement(handle->zone_dh_doc);
	for (child = root->xmlChildrenNode; child != NULL; child = next) {
		next = child->next;
		if (child->name == NULL)
			continue;
		if (xmlStrcmp(child->name, DTD_ELEM_PACKAGE) == 0) {
			next = child->next;
			xmlUnlinkNode(child);
			xmlFreeNode(child);
		}
	}
}

static int
zonecfg_get_handle_impl(const char *zonename, const char *filename,
    zone_dochandle_t handle)
{
	xmlValidCtxtPtr cvp;
	struct stat statbuf;
	int valid;

	if (zonename == NULL)
		return (Z_NO_ZONE);

	if ((handle->zone_dh_doc = xmlParseFile(filename)) == NULL) {
		/* distinguish file not found vs. found but not parsed */
		if (stat(filename, &statbuf) == 0)
			return (Z_INVALID_DOCUMENT);
		return (Z_NO_ZONE);
	}
	if ((cvp = xmlNewValidCtxt()) == NULL)
		return (Z_NOMEM);
	cvp->error = zonecfg_error_func;
	cvp->warning = zonecfg_error_func;
	valid = xmlValidateDocument(cvp, handle->zone_dh_doc);
	xmlFreeValidCtxt(cvp);
	if (valid == 0)
		return (Z_INVALID_DOCUMENT);

	/* delete any comments such as inherited Sun copyright / ident str */
	stripcomments(handle);
	return (Z_OK);
}

int
zonecfg_get_handle(const char *zonename, zone_dochandle_t handle)
{
	char path[MAXPATHLEN];

	if (!config_file_path(zonename, path))
		return (Z_MISC_FS);
	handle->zone_dh_newzone = B_FALSE;

	return (zonecfg_get_handle_impl(zonename, path, handle));
}

int
zonecfg_get_attach_handle(const char *path, const char *fname,
    const char *zonename, boolean_t preserve_sw, zone_dochandle_t handle)
{
	char		migpath[MAXPATHLEN];
	int		err;
	struct stat	buf;

	if (snprintf(migpath, sizeof (migpath), "%s/root", path) >=
	    sizeof (migpath))
		return (Z_NOMEM);

	if (stat(migpath, &buf) == -1 || !S_ISDIR(buf.st_mode))
		return (Z_NO_ZONE);

	if (snprintf(migpath, sizeof (migpath), "%s/%s", path, fname) >=
	    sizeof (migpath))
		return (Z_NOMEM);

	if ((err = zonecfg_get_handle_impl(zonename, migpath, handle)) != Z_OK)
		return (err);

	if (!preserve_sw)
		strip_sw_inv(handle);

	handle->zone_dh_newzone = B_TRUE;
	if ((err = setrootattr(handle, DTD_ATTR_ZONEPATH, path)) != Z_OK)
		return (err);

	return (setrootattr(handle, DTD_ATTR_NAME, zonename));
}

int
zonecfg_get_snapshot_handle(const char *zonename, zone_dochandle_t handle)
{
	char path[MAXPATHLEN];

	if (!snap_file_path(zonename, path))
		return (Z_MISC_FS);
	handle->zone_dh_newzone = B_FALSE;
	return (zonecfg_get_handle_impl(zonename, path, handle));
}

int
zonecfg_get_template_handle(const char *template, const char *zonename,
    zone_dochandle_t handle)
{
	char path[MAXPATHLEN];
	int err;

	if (!config_file_path(template, path))
		return (Z_MISC_FS);

	if ((err = zonecfg_get_handle_impl(template, path, handle)) != Z_OK)
		return (err);
	handle->zone_dh_newzone = B_TRUE;
	return (setrootattr(handle, DTD_ATTR_NAME, zonename));
}

int
zonecfg_get_xml_handle(const char *path, zone_dochandle_t handle)
{
	struct stat buf;
	int err;

	if (stat(path, &buf) == -1)
		return (Z_MISC_FS);

	if ((err = zonecfg_get_handle_impl("xml", path, handle)) != Z_OK)
		return (err);
	handle->zone_dh_newzone = B_TRUE;
	return (Z_OK);
}

/*
 * Initialize two handles from the manifest read on fd.  The rem_handle
 * is initialized from the input file, including the sw inventory.  The
 * local_handle is initialized with the same zone configuration but with
 * no sw inventory.
 */
int
zonecfg_attach_manifest(int fd, zone_dochandle_t local_handle,
    zone_dochandle_t rem_handle)
{
	xmlValidCtxtPtr cvp;
	int valid;

	/* load the manifest into the handle for the remote system */
	if ((rem_handle->zone_dh_doc = xmlReadFd(fd, NULL, NULL, 0)) == NULL) {
		return (Z_INVALID_DOCUMENT);
	}
	if ((cvp = xmlNewValidCtxt()) == NULL)
		return (Z_NOMEM);
	cvp->error = zonecfg_error_func;
	cvp->warning = zonecfg_error_func;
	valid = xmlValidateDocument(cvp, rem_handle->zone_dh_doc);
	xmlFreeValidCtxt(cvp);
	if (valid == 0)
		return (Z_INVALID_DOCUMENT);

	/* delete any comments such as inherited Sun copyright / ident str */
	stripcomments(rem_handle);

	rem_handle->zone_dh_newzone = B_TRUE;
	rem_handle->zone_dh_sw_inv = B_TRUE;

	/*
	 * Now use the remote system handle to generate a local system handle
	 * with an identical zones configuration but no sw inventory.
	 */
	if ((local_handle->zone_dh_doc = xmlCopyDoc(rem_handle->zone_dh_doc,
	    1)) == NULL) {
		return (Z_INVALID_DOCUMENT);
	}

	/*
	 * We need to re-run xmlValidateDocument on local_handle to properly
	 * update the in-core representation of the configuration.
	 */
	if ((cvp = xmlNewValidCtxt()) == NULL)
		return (Z_NOMEM);
	cvp->error = zonecfg_error_func;
	cvp->warning = zonecfg_error_func;
	valid = xmlValidateDocument(cvp, local_handle->zone_dh_doc);
	xmlFreeValidCtxt(cvp);
	if (valid == 0)
		return (Z_INVALID_DOCUMENT);

	strip_sw_inv(local_handle);

	local_handle->zone_dh_newzone = B_TRUE;
	local_handle->zone_dh_sw_inv = B_FALSE;

	return (Z_OK);
}

static boolean_t
is_renaming(zone_dochandle_t handle)
{
	if (handle->zone_dh_newzone)
		return (B_FALSE);
	if (strlen(handle->zone_dh_delete_name) > 0)
		return (B_TRUE);
	return (B_FALSE);
}

static boolean_t
is_new(zone_dochandle_t handle)
{
	return (handle->zone_dh_newzone || handle->zone_dh_snapshot);
}

static boolean_t
is_snapshot(zone_dochandle_t handle)
{
	return (handle->zone_dh_snapshot);
}

/*
 * It would be great to be able to use libc's ctype(3c) macros, but we
 * can't, as they are locale sensitive, and it would break our limited thread
 * safety if this routine had to change the app locale on the fly.
 */
int
zonecfg_validate_zonename(const char *zone)
{
	int i;

	if (strcmp(zone, GLOBAL_ZONENAME) == 0)
		return (Z_BOGUS_ZONE_NAME);

	if (strlen(zone) >= ZONENAME_MAX)
		return (Z_BOGUS_ZONE_NAME);

	if (!((zone[0] >= 'a' && zone[0] <= 'z') ||
	    (zone[0] >= 'A' && zone[0] <= 'Z') ||
	    (zone[0] >= '0' && zone[0] <= '9')))
		return (Z_BOGUS_ZONE_NAME);

	for (i = 1; zone[i] != '\0'; i++) {
		if (!((zone[i] >= 'a' && zone[i] <= 'z') ||
		    (zone[i] >= 'A' && zone[i] <= 'Z') ||
		    (zone[i] >= '0' && zone[i] <= '9') ||
		    (zone[i] == '-') || (zone[i] == '_') || (zone[i] == '.')))
			return (Z_BOGUS_ZONE_NAME);
	}

	return (Z_OK);
}

/*
 * Changing the zone name requires us to track both the old and new
 * name of the zone until commit time.
 */
int
zonecfg_get_name(zone_dochandle_t handle, char *name, size_t namesize)
{
	return (getrootattr(handle, DTD_ATTR_NAME, name, namesize));
}

static int
insert_admins(zone_dochandle_t handle, char *zonename)
{
	int err;
	struct zone_admintab admintab;

	if ((err = zonecfg_setadminent(handle)) != Z_OK) {
		return (err);
	}
	while (zonecfg_getadminent(handle, &admintab) == Z_OK) {
		err = zonecfg_insert_userauths(handle,
		    admintab.zone_admin_user, zonename);
		if (err != Z_OK) {
			(void) zonecfg_endadminent(handle);
			return (err);
		}
	}
	(void) zonecfg_endadminent(handle);
	return (Z_OK);
}

int
zonecfg_set_name(zone_dochandle_t handle, char *name)
{
	zone_state_t state;
	char curname[ZONENAME_MAX], old_delname[ZONENAME_MAX];
	int err;

	if ((err = getrootattr(handle, DTD_ATTR_NAME, curname,
	    sizeof (curname))) != Z_OK)
		return (err);

	if (strcmp(name, curname) == 0)
		return (Z_OK);

	/*
	 * Switching zone names to one beginning with SUNW is not permitted.
	 */
	if (strncmp(name, "SUNW", 4) == 0)
		return (Z_BOGUS_ZONE_NAME);

	if ((err = zonecfg_validate_zonename(name)) != Z_OK)
		return (err);

	/*
	 * Setting the name back to the original name (effectively a revert of
	 * the name) is fine.  But if we carry on, we'll falsely identify the
	 * name as "in use," so special case here.
	 */
	if (strcmp(name, handle->zone_dh_delete_name) == 0) {
		err = setrootattr(handle, DTD_ATTR_NAME, name);
		handle->zone_dh_delete_name[0] = '\0';
		return (err);
	}

	/* Check to see if new name chosen is already in use */
	if (zone_get_state(name, &state) != Z_NO_ZONE)
		return (Z_NAME_IN_USE);

	/*
	 * If this isn't already "new" or in a renaming transition, then
	 * we're initiating a rename here; so stash the "delete name"
	 * (i.e. the name of the zone we'll be removing) for the rename.
	 */
	(void) strlcpy(old_delname, handle->zone_dh_delete_name,
	    sizeof (old_delname));
	if (!is_new(handle) && !is_renaming(handle)) {
		/*
		 * Name change is allowed only when the zone we're altering
		 * is not ready or running.
		 */
		err = zone_get_state(curname, &state);
		if (err == Z_OK) {
			if (state > ZONE_STATE_INSTALLED)
				return (Z_BAD_ZONE_STATE);
		} else if (err != Z_NO_ZONE) {
			return (err);
		}

		(void) strlcpy(handle->zone_dh_delete_name, curname,
		    sizeof (handle->zone_dh_delete_name));
		assert(is_renaming(handle));
	} else if (is_renaming(handle)) {
		err = zone_get_state(handle->zone_dh_delete_name, &state);
		if (err == Z_OK) {
			if (state > ZONE_STATE_INSTALLED)
				return (Z_BAD_ZONE_STATE);
		} else if (err != Z_NO_ZONE) {
			return (err);
		}
	}

	if ((err = setrootattr(handle, DTD_ATTR_NAME, name)) != Z_OK) {
		/*
		 * Restore the deletename to whatever it was at the
		 * top of the routine, since we've had a failure.
		 */
		(void) strlcpy(handle->zone_dh_delete_name, old_delname,
		    sizeof (handle->zone_dh_delete_name));
		return (err);
	}

	/*
	 * Record the old admins from the old zonename
	 * so that they can be deleted when the operation is committed.
	 */
	if ((err = insert_admins(handle, curname)) != Z_OK)
		return (err);
	else
		return (Z_OK);
}

int
zonecfg_get_zonepath(zone_dochandle_t handle, char *path, size_t pathsize)
{
	size_t len;

	if ((len = strlcpy(path, zonecfg_root, pathsize)) >= pathsize)
		return (Z_TOO_BIG);
	return (getrootattr(handle, DTD_ATTR_ZONEPATH, path + len,
	    pathsize - len));
}

int
zonecfg_set_zonepath(zone_dochandle_t handle, char *zonepath)
{
	size_t len;
	char *modpath, *copy_mp, *curr_mp;	/* modified path ptrs */
	char last_copied;
	int ret;

	/*
	 * Collapse multiple contiguous slashes and remove trailing slash.
	 */
	modpath = strdup(zonepath);
	if (modpath == NULL)
		return (Z_NOMEM);
	last_copied = '\0';
	for (copy_mp = curr_mp = modpath; *curr_mp != '\0'; curr_mp++) {
		if (*curr_mp != '/' || last_copied != '/') {
			last_copied = *copy_mp = *curr_mp;
			copy_mp++;
		}
	}
	if (last_copied == '/')
		copy_mp--;
	*copy_mp = '\0';

	/*
	 * The user deals in absolute paths in the running global zone, but the
	 * internal configuration files deal with boot environment relative
	 * paths.  Strip out the alternate root when specified.
	 */
	len = strlen(zonecfg_root);
	if (strncmp(modpath, zonecfg_root, len) != 0 || modpath[len] != '/') {
		free(modpath);
		return (Z_BAD_PROPERTY);
	}
	curr_mp = modpath + len;
	ret = setrootattr(handle, DTD_ATTR_ZONEPATH, curr_mp);
	free(modpath);
	return (ret);
}

static int
i_zonecfg_get_brand(zone_dochandle_t handle, char *brand, size_t brandsize,
    boolean_t default_query)
{
	int ret, sz;

	ret = getrootattr(handle, DTD_ATTR_BRAND, brand, brandsize);

	/*
	 * If the lookup failed, or succeeded in finding a non-null brand
	 * string then return.
	 */
	if (ret != Z_OK || brand[0] != '\0')
		return (ret);

	if (!default_query) {
		/* If the zone has no brand, it is the default brand. */
		return (zonecfg_default_brand(brand, brandsize));
	}

	/* if SUNWdefault didn't specify a brand, fallback to "native" */
	sz = strlcpy(brand, NATIVE_BRAND_NAME, brandsize);
	if (sz >= brandsize)
		return (Z_TOO_BIG);
	return (Z_OK);
}

int
zonecfg_get_brand(zone_dochandle_t handle, char *brand, size_t brandsize)
{
	return (i_zonecfg_get_brand(handle, brand, brandsize, B_FALSE));
}

int
zonecfg_set_brand(zone_dochandle_t handle, char *brand)
{
	return (setrootattr(handle, DTD_ATTR_BRAND, brand));
}

int
zonecfg_get_autoboot(zone_dochandle_t handle, boolean_t *autoboot)
{
	char autobootstr[DTD_ENTITY_BOOL_LEN];
	int ret;

	if ((ret = getrootattr(handle, DTD_ATTR_AUTOBOOT, autobootstr,
	    sizeof (autobootstr))) != Z_OK)
		return (ret);

	if (strcmp(autobootstr, DTD_ENTITY_TRUE) == 0)
		*autoboot = B_TRUE;
	else if (strcmp(autobootstr, DTD_ENTITY_FALSE) == 0)
		*autoboot = B_FALSE;
	else
		ret = Z_BAD_PROPERTY;
	return (ret);
}

int
zonecfg_set_autoboot(zone_dochandle_t handle, boolean_t autoboot)
{
	return (setrootattr(handle, DTD_ATTR_AUTOBOOT,
	    autoboot ? DTD_ENTITY_TRUE : DTD_ENTITY_FALSE));
}

int
zonecfg_get_pool(zone_dochandle_t handle, char *pool, size_t poolsize)
{
	return (getrootattr(handle, DTD_ATTR_POOL, pool, poolsize));
}

int
zonecfg_set_pool(zone_dochandle_t handle, char *pool)
{
	return (setrootattr(handle, DTD_ATTR_POOL, pool));
}

int
zonecfg_get_limitpriv(zone_dochandle_t handle, char **limitpriv)
{
	return (get_alloc_rootattr(handle, DTD_ATTR_LIMITPRIV, limitpriv));
}

int
zonecfg_set_limitpriv(zone_dochandle_t handle, char *limitpriv)
{
	return (setrootattr(handle, DTD_ATTR_LIMITPRIV, limitpriv));
}

int
zonecfg_get_bootargs(zone_dochandle_t handle, char *bargs, size_t bargssize)
{
	return (getrootattr(handle, DTD_ATTR_BOOTARGS, bargs, bargssize));
}

int
zonecfg_set_bootargs(zone_dochandle_t handle, char *bargs)
{
	return (setrootattr(handle, DTD_ATTR_BOOTARGS, bargs));
}

int
zonecfg_get_sched_class(zone_dochandle_t handle, char *sched, size_t schedsize)
{
	return (getrootattr(handle, DTD_ATTR_SCHED, sched, schedsize));
}

int
zonecfg_set_sched(zone_dochandle_t handle, char *sched)
{
	return (setrootattr(handle, DTD_ATTR_SCHED, sched));
}

/*
 * /etc/zones/index caches a vital piece of information which is also
 * in the <zonename>.xml file: the path to the zone.  This is for performance,
 * since we need to walk all zonepath's in order to be able to detect conflicts
 * (see crosscheck_zonepaths() in the zoneadm command).
 *
 * An additional complexity is that when doing a rename, we'd like the entire
 * index update operation (rename, and potential state changes) to be atomic.
 * In general, the operation of this function should succeed or fail as
 * a unit.
 */
int
zonecfg_refresh_index_file(zone_dochandle_t handle)
{
	char name[ZONENAME_MAX], zonepath[MAXPATHLEN];
	struct zoneent ze;
	int err;
	int opcode;
	char *zn;

	bzero(&ze, sizeof (ze));
	ze.zone_state = -1;	/* Preserve existing state in index */

	if ((err = zonecfg_get_name(handle, name, sizeof (name))) != Z_OK)
		return (err);
	(void) strlcpy(ze.zone_name, name, sizeof (ze.zone_name));

	if ((err = zonecfg_get_zonepath(handle, zonepath,
	    sizeof (zonepath))) != Z_OK)
		return (err);
	(void) strlcpy(ze.zone_path, zonepath + strlen(zonecfg_root),
	    sizeof (ze.zone_path));

	if (is_renaming(handle)) {
		opcode = PZE_MODIFY;
		(void) strlcpy(ze.zone_name, handle->zone_dh_delete_name,
		    sizeof (ze.zone_name));
		(void) strlcpy(ze.zone_newname, name, sizeof (ze.zone_newname));
	} else if (is_new(handle)) {
		FILE *cookie;
		/*
		 * Be tolerant of the zone already existing in the index file,
		 * since we might be forcibly overwriting an existing
		 * configuration with a new one (for example 'create -F'
		 * in zonecfg).
		 */
		opcode = PZE_ADD;
		cookie = setzoneent();
		while ((zn = getzoneent(cookie)) != NULL) {
			if (strcmp(zn, name) == 0) {
				opcode = PZE_MODIFY;
				free(zn);
				break;
			}
			free(zn);
		}
		endzoneent(cookie);
		ze.zone_state = ZONE_STATE_CONFIGURED;
	} else {
		opcode = PZE_MODIFY;
	}

	if ((err = putzoneent(&ze, opcode)) != Z_OK)
		return (err);

	return (Z_OK);
}

/*
 * The goal of this routine is to cause the index file update and the
 * document save to happen as an atomic operation.  We do the document
 * first, saving a backup copy using a hard link; if that succeeds, we go
 * on to the index.  If that fails, we roll the document back into place.
 *
 * Strategy:
 *
 * New zone 'foo' configuration:
 *	Create tmpfile (zonecfg.xxxxxx)
 *	Write XML to tmpfile
 *	Rename tmpfile to xmlfile (zonecfg.xxxxxx -> foo.xml)
 *	Add entry to index file
 *	If it fails, delete foo.xml, leaving nothing behind.
 *
 * Save existing zone 'foo':
 *	Make backup of foo.xml -> .backup
 *	Create tmpfile (zonecfg.xxxxxx)
 *	Write XML to tmpfile
 *	Rename tmpfile to xmlfile (zonecfg.xxxxxx -> foo.xml)
 *	Modify index file as needed
 *	If it fails, recover from .backup -> foo.xml
 *
 * Rename 'foo' to 'bar':
 *	Create tmpfile (zonecfg.xxxxxx)
 *	Write XML to tmpfile
 *	Rename tmpfile to xmlfile (zonecfg.xxxxxx -> bar.xml)
 *	Add entry for 'bar' to index file, Remove entry for 'foo' (refresh)
 *	If it fails, delete bar.xml; foo.xml is left behind.
 */
static int
zonecfg_save_impl(zone_dochandle_t handle, char *filename)
{
	char tmpfile[MAXPATHLEN];
	char bakdir[MAXPATHLEN], bakbase[MAXPATHLEN], bakfile[MAXPATHLEN];
	int tmpfd, err, valid;
	xmlValidCtxt cvp = { NULL };
	boolean_t backup;

	(void) strlcpy(tmpfile, filename, sizeof (tmpfile));
	(void) dirname(tmpfile);
	(void) strlcat(tmpfile, _PATH_TMPFILE, sizeof (tmpfile));

	tmpfd = mkstemp(tmpfile);
	if (tmpfd == -1) {
		(void) unlink(tmpfile);
		return (Z_TEMP_FILE);
	}
	(void) close(tmpfd);

	cvp.error = zonecfg_error_func;
	cvp.warning = zonecfg_error_func;

	/*
	 * We do a final validation of the document.  Since the library has
	 * malfunctioned if it fails to validate, we follow-up with an
	 * assert() that the doc is valid.
	 */
	valid = xmlValidateDocument(&cvp, handle->zone_dh_doc);
	assert(valid != 0);

	if (xmlSaveFormatFile(tmpfile, handle->zone_dh_doc, 1) <= 0)
		goto err;

	(void) chmod(tmpfile, 0644);

	/*
	 * In the event we are doing a standard save, hard link a copy of the
	 * original file in .backup.<pid>.filename so we can restore it if
	 * something goes wrong.
	 */
	if (!is_new(handle) && !is_renaming(handle)) {
		backup = B_TRUE;

		(void) strlcpy(bakdir, filename, sizeof (bakdir));
		(void) strlcpy(bakbase, filename, sizeof (bakbase));
		(void) snprintf(bakfile, sizeof (bakfile), "%s/.backup.%d.%s",
		    dirname(bakdir), getpid(), basename(bakbase));

		if (link(filename, bakfile) == -1) {
			err = errno;
			(void) unlink(tmpfile);
			if (errno == EACCES)
				return (Z_ACCES);
			return (Z_MISC_FS);
		}
	}

	/*
	 * Move the new document over top of the old.
	 * i.e.:   zonecfg.XXXXXX  ->  myzone.xml
	 */
	if (rename(tmpfile, filename) == -1) {
		err = errno;
		(void) unlink(tmpfile);
		if (backup)
			(void) unlink(bakfile);
		if (err == EACCES)
			return (Z_ACCES);
		return (Z_MISC_FS);
	}

	/*
	 * If this is a snapshot, we're done-- don't add an index entry.
	 */
	if (is_snapshot(handle))
		return (Z_OK);

	/* now update the index file to reflect whatever we just did */
	if ((err = zonecfg_refresh_index_file(handle)) != Z_OK) {
		if (backup) {
			/*
			 * Try to restore from our backup.
			 */
			(void) unlink(filename);
			(void) rename(bakfile, filename);
		} else {
			/*
			 * Either the zone is new, in which case we can delete
			 * new.xml, or we're doing a rename, so ditto.
			 */
			assert(is_new(handle) || is_renaming(handle));
			(void) unlink(filename);
		}
		return (Z_UPDATING_INDEX);
	}

	if (backup)
		(void) unlink(bakfile);

	return (Z_OK);

err:
	(void) unlink(tmpfile);
	return (Z_SAVING_FILE);
}

int
zonecfg_save(zone_dochandle_t handle)
{
	char zname[ZONENAME_MAX], path[MAXPATHLEN];
	char delpath[MAXPATHLEN];
	int err = Z_SAVING_FILE;

	if (zonecfg_check_handle(handle) != Z_OK)
		return (Z_BAD_HANDLE);

	/*
	 * We don't support saving snapshots or a tree containing a sw
	 * inventory at this time.
	 */
	if (handle->zone_dh_snapshot || handle->zone_dh_sw_inv)
		return (Z_INVAL);

	if ((err = zonecfg_get_name(handle, zname, sizeof (zname))) != Z_OK)
		return (err);

	if (!config_file_path(zname, path))
		return (Z_MISC_FS);

	addcomment(handle, "\n    DO NOT EDIT THIS "
	    "FILE.  Use zonecfg(8) instead.\n");

	/*
	 * Update user_attr first so that it will be older
	 * than the config file.
	 */
	(void) zonecfg_authorize_users(handle, zname);
	err = zonecfg_save_impl(handle, path);

	stripcomments(handle);

	if (err != Z_OK)
		return (err);

	handle->zone_dh_newzone = B_FALSE;

	if (is_renaming(handle)) {
		if (config_file_path(handle->zone_dh_delete_name, delpath))
			(void) unlink(delpath);
		handle->zone_dh_delete_name[0] = '\0';
	}

	return (Z_OK);
}

int
zonecfg_verify_save(zone_dochandle_t handle, char *filename)
{
	int valid;

	xmlValidCtxt cvp = { NULL };

	if (zonecfg_check_handle(handle) != Z_OK)
		return (Z_BAD_HANDLE);

	cvp.error = zonecfg_error_func;
	cvp.warning = zonecfg_error_func;

	/*
	 * We do a final validation of the document.  Since the library has
	 * malfunctioned if it fails to validate, we follow-up with an
	 * assert() that the doc is valid.
	 */
	valid = xmlValidateDocument(&cvp, handle->zone_dh_doc);
	assert(valid != 0);

	if (xmlSaveFormatFile(filename, handle->zone_dh_doc, 1) <= 0)
		return (Z_SAVING_FILE);

	return (Z_OK);
}

int
zonecfg_detach_save(zone_dochandle_t handle, uint_t flags)
{
	char zname[ZONENAME_MAX];
	char path[MAXPATHLEN];
	char migpath[MAXPATHLEN];
	xmlValidCtxt cvp = { NULL };
	int err = Z_SAVING_FILE;
	int valid;

	if (zonecfg_check_handle(handle) != Z_OK)
		return (Z_BAD_HANDLE);

	if (flags & ZONE_DRY_RUN) {
		(void) strlcpy(migpath, "-", sizeof (migpath));
	} else {
		if ((err = zonecfg_get_name(handle, zname, sizeof (zname)))
		    != Z_OK)
			return (err);

		if ((err = zone_get_zonepath(zname, path, sizeof (path)))
		    != Z_OK)
			return (err);

		if (snprintf(migpath, sizeof (migpath), "%s/%s", path,
		    ZONE_DETACHED) >= sizeof (migpath))
			return (Z_NOMEM);
	}

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	addcomment(handle, "\n    DO NOT EDIT THIS FILE.  "
	    "Use zonecfg(8) and zoneadm(8) attach.\n");

	cvp.error = zonecfg_error_func;
	cvp.warning = zonecfg_error_func;

	/*
	 * We do a final validation of the document.  Since the library has
	 * malfunctioned if it fails to validate, we follow-up with an
	 * assert() that the doc is valid.
	 */
	valid = xmlValidateDocument(&cvp, handle->zone_dh_doc);
	assert(valid != 0);

	if (xmlSaveFormatFile(migpath, handle->zone_dh_doc, 1) <= 0)
		return (Z_SAVING_FILE);

	if (!(flags & ZONE_DRY_RUN))
		(void) chmod(migpath, 0644);

	stripcomments(handle);

	handle->zone_dh_newzone = B_FALSE;

	return (Z_OK);
}

boolean_t
zonecfg_detached(const char *path)
{
	char		migpath[MAXPATHLEN];
	struct stat	buf;

	if (snprintf(migpath, sizeof (migpath), "%s/%s", path, ZONE_DETACHED) >=
	    sizeof (migpath))
		return (B_FALSE);

	if (stat(migpath, &buf) != -1)
		return (B_TRUE);

	return (B_FALSE);
}

void
zonecfg_rm_detached(zone_dochandle_t handle, boolean_t forced)
{
	char zname[ZONENAME_MAX];
	char path[MAXPATHLEN];
	char detached[MAXPATHLEN];
	char attached[MAXPATHLEN];

	if (zonecfg_check_handle(handle) != Z_OK)
		return;

	if (zonecfg_get_name(handle, zname, sizeof (zname)) != Z_OK)
		return;

	if (zone_get_zonepath(zname, path, sizeof (path)) != Z_OK)
		return;

	(void) snprintf(detached, sizeof (detached), "%s/%s", path,
	    ZONE_DETACHED);
	(void) snprintf(attached, sizeof (attached), "%s/%s", path,
	    ATTACH_FORCED);

	if (forced) {
		(void) rename(detached, attached);
	} else {
		(void) unlink(attached);
		(void) unlink(detached);
	}
}

/*
 * Special case: if access(2) fails with ENOENT, then try again using
 * ZONE_CONFIG_ROOT instead of config_file_path(zonename).  This is how we
 * work around the case of a config file which has not been created yet:
 * the user will need access to the directory so use that as a heuristic.
 */

int
zonecfg_access(const char *zonename, int amode)
{
	char path[MAXPATHLEN];

	if (!config_file_path(zonename, path))
		return (Z_INVAL);
	if (access(path, amode) == 0)
		return (Z_OK);
	if (errno == ENOENT) {
		if (snprintf(path, sizeof (path), "%s%s", zonecfg_root,
		    ZONE_CONFIG_ROOT) >= sizeof (path))
			return (Z_INVAL);
		if (access(path, amode) == 0)
			return (Z_OK);
	}
	if (errno == EACCES)
		return (Z_ACCES);
	if (errno == EINVAL)
		return (Z_INVAL);
	return (Z_MISC_FS);
}

int
zonecfg_create_snapshot(const char *zonename)
{
	zone_dochandle_t handle;
	char path[MAXPATHLEN], zonepath[MAXPATHLEN], rpath[MAXPATHLEN];
	int error = Z_OK, res;

	if ((handle = zonecfg_init_handle()) == NULL) {
		return (Z_NOMEM);
	}

	handle->zone_dh_newzone = B_TRUE;
	handle->zone_dh_snapshot = B_TRUE;

	if ((error = zonecfg_get_handle(zonename, handle)) != Z_OK)
		goto out;
	if ((error = operation_prep(handle)) != Z_OK)
		goto out;
	error = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath));
	if (error != Z_OK)
		goto out;
	if ((res = resolvepath(zonepath, rpath, sizeof (rpath))) == -1) {
		error = Z_RESOLVED_PATH;
		goto out;
	}
	/*
	 * If the resolved path is not the same as the original path, then
	 * save the resolved path in the snapshot, thus preventing any
	 * potential problems down the line when zoneadmd goes to unmount
	 * file systems and depends on initial string matches with resolved
	 * paths.
	 */
	rpath[res] = '\0';
	if (strcmp(zonepath, rpath) != 0) {
		if ((error = zonecfg_set_zonepath(handle, rpath)) != Z_OK)
			goto out;
	}
	if (snprintf(path, sizeof (path), "%s%s", zonecfg_root,
	    ZONE_SNAPSHOT_ROOT) >= sizeof (path)) {
		error = Z_MISC_FS;
		goto out;
	}
	if ((mkdir(path, S_IRWXU) == -1) && (errno != EEXIST)) {
		error = Z_MISC_FS;
		goto out;
	}

	if (!snap_file_path(zonename, path)) {
		error = Z_MISC_FS;
		goto out;
	}

	addcomment(handle, "\n    DO NOT EDIT THIS FILE.  "
	    "It is a snapshot of running zone state.\n");

	error = zonecfg_save_impl(handle, path);

	stripcomments(handle);

out:
	zonecfg_fini_handle(handle);
	return (error);
}

int
zonecfg_get_iptype(zone_dochandle_t handle, zone_iptype_t *iptypep)
{
	char property[10]; /* 10 is big enough for "shared"/"exclusive" */
	int err;

	err = getrootattr(handle, DTD_ATTR_IPTYPE, property, sizeof (property));
	if (err == Z_BAD_PROPERTY) {
		/* Return default value */
		*iptypep = ZS_SHARED;
		return (Z_OK);
	} else if (err != Z_OK) {
		return (err);
	}

	if (strlen(property) == 0 ||
	    strcmp(property, "shared") == 0)
		*iptypep = ZS_SHARED;
	else if (strcmp(property, "exclusive") == 0)
		*iptypep = ZS_EXCLUSIVE;
	else
		return (Z_INVAL);

	return (Z_OK);
}

int
zonecfg_set_iptype(zone_dochandle_t handle, zone_iptype_t iptype)
{
	xmlNodePtr cur;

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

	cur = xmlDocGetRootElement(handle->zone_dh_doc);
	if (cur == NULL) {
		return (Z_EMPTY_DOCUMENT);
	}

	if (xmlStrcmp(cur->name, DTD_ELEM_ZONE) != 0) {
		return (Z_WRONG_DOC_TYPE);
	}
	switch (iptype) {
	case ZS_SHARED:
		/*
		 * Since "shared" is the default, we don't write it to the
		 * configuration file, so that it's easier to migrate those
		 * zones elsewhere, eg., to systems which are not IP-Instances
		 * aware.
		 * xmlUnsetProp only fails when the attribute doesn't exist,
		 * which we don't care.
		 */
		(void) xmlUnsetProp(cur, DTD_ATTR_IPTYPE);
		break;
	case ZS_EXCLUSIVE:
		if (xmlSetProp(cur, DTD_ATTR_IPTYPE,
		    (const xmlChar *) "exclusive") == NULL)
			return (Z_INVAL);
		break;
	}
	return (Z_OK);
}

static int
newprop(xmlNodePtr node, const xmlChar *attrname, char *src)
{
	xmlAttrPtr newattr;

	newattr = xmlNewProp(node, attrname, (xmlChar *)src);
	if (newattr == NULL) {
		xmlUnlinkNode(node);
		xmlFreeNode(node);
		return (Z_BAD_PROPERTY);
	}
	return (Z_OK);
}

static int
zonecfg_add_filesystem_core(zone_dochandle_t handle, struct zone_fstab *tabptr)
{
	xmlNodePtr newnode, cur = handle->zone_dh_cur, options_node;
	zone_fsopt_t *ptr;
	int err;

	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_FS, NULL);
	if ((err = newprop(newnode, DTD_ATTR_SPECIAL,
	    tabptr->zone_fs_special)) != Z_OK)
		return (err);
	if (tabptr->zone_fs_raw[0] != '\0' &&
	    (err = newprop(newnode, DTD_ATTR_RAW, tabptr->zone_fs_raw)) != Z_OK)
		return (err);
	if ((err = newprop(newnode, DTD_ATTR_DIR, tabptr->zone_fs_dir)) != Z_OK)
		return (err);
	if ((err = newprop(newnode, DTD_ATTR_TYPE,
	    tabptr->zone_fs_type)) != Z_OK)
		return (err);
	if (tabptr->zone_fs_options != NULL) {
		for (ptr = tabptr->zone_fs_options; ptr != NULL;
		    ptr = ptr->zone_fsopt_next) {
			options_node = xmlNewTextChild(newnode, NULL,
			    DTD_ELEM_FSOPTION, NULL);
			if ((err = newprop(options_node, DTD_ATTR_NAME,
			    ptr->zone_fsopt_opt)) != Z_OK)
				return (err);
		}
	}
	return (Z_OK);
}

int
zonecfg_add_filesystem(zone_dochandle_t handle, struct zone_fstab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_filesystem_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_add_fs_option(struct zone_fstab *tabptr, char *option)
{
	zone_fsopt_t *last, *old, *new;

	last = tabptr->zone_fs_options;
	for (old = last; old != NULL; old = old->zone_fsopt_next)
		last = old;	/* walk to the end of the list */
	new = (zone_fsopt_t *)malloc(sizeof (zone_fsopt_t));
	if (new == NULL)
		return (Z_NOMEM);
	(void) strlcpy(new->zone_fsopt_opt, option,
	    sizeof (new->zone_fsopt_opt));
	new->zone_fsopt_next = NULL;
	if (last == NULL)
		tabptr->zone_fs_options = new;
	else
		last->zone_fsopt_next = new;
	return (Z_OK);
}

int
zonecfg_remove_fs_option(struct zone_fstab *tabptr, char *option)
{
	zone_fsopt_t *last, *this, *next;

	last = tabptr->zone_fs_options;
	for (this = last; this != NULL; this = this->zone_fsopt_next) {
		if (strcmp(this->zone_fsopt_opt, option) == 0) {
			next = this->zone_fsopt_next;
			if (this == tabptr->zone_fs_options)
				tabptr->zone_fs_options = next;
			else
				last->zone_fsopt_next = next;
			free(this);
			return (Z_OK);
		} else
			last = this;
	}
	return (Z_NO_PROPERTY_ID);
}

void
zonecfg_free_fs_option_list(zone_fsopt_t *list)
{
	zone_fsopt_t *this, *next;

	for (this = list; this != NULL; this = next) {
		next = this->zone_fsopt_next;
		free(this);
	}
}

void
zonecfg_free_rctl_value_list(struct zone_rctlvaltab *valtab)
{
	if (valtab == NULL)
		return;
	zonecfg_free_rctl_value_list(valtab->zone_rctlval_next);
	free(valtab);
}

static boolean_t
match_prop(xmlNodePtr cur, const xmlChar *attr, char *user_prop)
{
	xmlChar *gotten_prop;
	int prop_result;

	gotten_prop = xmlGetProp(cur, attr);
	if (gotten_prop == NULL)	/* shouldn't happen */
		return (B_FALSE);
	prop_result = xmlStrcmp(gotten_prop, (const xmlChar *) user_prop);
	xmlFree(gotten_prop);
	return ((prop_result == 0));	/* empty strings will match */
}

static int
zonecfg_delete_filesystem_core(zone_dochandle_t handle,
    struct zone_fstab *tabptr)
{
	xmlNodePtr cur = handle->zone_dh_cur;
	boolean_t dir_match, spec_match, raw_match, type_match;

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_FS))
			continue;
		dir_match = match_prop(cur, DTD_ATTR_DIR, tabptr->zone_fs_dir);
		spec_match = match_prop(cur, DTD_ATTR_SPECIAL,
		    tabptr->zone_fs_special);
		raw_match = match_prop(cur, DTD_ATTR_RAW,
		    tabptr->zone_fs_raw);
		type_match = match_prop(cur, DTD_ATTR_TYPE,
		    tabptr->zone_fs_type);
		if (dir_match && spec_match && raw_match && type_match) {
			xmlUnlinkNode(cur);
			xmlFreeNode(cur);
			return (Z_OK);
		}
	}
	return (Z_NO_RESOURCE_ID);
}

int
zonecfg_delete_filesystem(zone_dochandle_t handle, struct zone_fstab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_filesystem_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_modify_filesystem(
	zone_dochandle_t handle,
	struct zone_fstab *oldtabptr,
	struct zone_fstab *newtabptr)
{
	int err;

	if (oldtabptr == NULL || newtabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_filesystem_core(handle, oldtabptr)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_filesystem_core(handle, newtabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_lookup_filesystem(
	zone_dochandle_t handle,
	struct zone_fstab *tabptr)
{
	xmlNodePtr cur, options, firstmatch;
	int err;
	char dirname[MAXPATHLEN], special[MAXPATHLEN], raw[MAXPATHLEN];
	char type[FSTYPSZ];
	char options_str[MAX_MNTOPT_STR];

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	/*
	 * Walk the list of children looking for matches on any properties
	 * specified in the fstab parameter.  If more than one resource
	 * matches, we return Z_INSUFFICIENT_SPEC; if none match, we return
	 * Z_NO_RESOURCE_ID.
	 */
	cur = handle->zone_dh_cur;
	firstmatch = NULL;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_FS))
			continue;
		if (strlen(tabptr->zone_fs_dir) > 0) {
			if ((fetchprop(cur, DTD_ATTR_DIR, dirname,
			    sizeof (dirname)) == Z_OK) &&
			    (strcmp(tabptr->zone_fs_dir, dirname) == 0)) {
				if (firstmatch == NULL)
					firstmatch = cur;
				else
					return (Z_INSUFFICIENT_SPEC);
			}
		}
		if (strlen(tabptr->zone_fs_special) > 0) {
			if ((fetchprop(cur, DTD_ATTR_SPECIAL, special,
			    sizeof (special)) == Z_OK)) {
				if (strcmp(tabptr->zone_fs_special,
				    special) == 0) {
					if (firstmatch == NULL)
						firstmatch = cur;
					else if (firstmatch != cur)
						return (Z_INSUFFICIENT_SPEC);
				} else {
					/*
					 * If another property matched but this
					 * one doesn't then reset firstmatch.
					 */
					if (firstmatch == cur)
						firstmatch = NULL;
				}
			}
		}
		if (strlen(tabptr->zone_fs_raw) > 0) {
			if ((fetchprop(cur, DTD_ATTR_RAW, raw,
			    sizeof (raw)) == Z_OK)) {
				if (strcmp(tabptr->zone_fs_raw, raw) == 0) {
					if (firstmatch == NULL)
						firstmatch = cur;
					else if (firstmatch != cur)
						return (Z_INSUFFICIENT_SPEC);
				} else {
					/*
					 * If another property matched but this
					 * one doesn't then reset firstmatch.
					 */
					if (firstmatch == cur)
						firstmatch = NULL;
				}
			}
		}
		if (strlen(tabptr->zone_fs_type) > 0) {
			if ((fetchprop(cur, DTD_ATTR_TYPE, type,
			    sizeof (type)) == Z_OK)) {
				if (strcmp(tabptr->zone_fs_type, type) == 0) {
					if (firstmatch == NULL)
						firstmatch = cur;
					else if (firstmatch != cur)
						return (Z_INSUFFICIENT_SPEC);
				} else {
					/*
					 * If another property matched but this
					 * one doesn't then reset firstmatch.
					 */
					if (firstmatch == cur)
						firstmatch = NULL;
				}
			}
		}
	}

	if (firstmatch == NULL)
		return (Z_NO_RESOURCE_ID);

	cur = firstmatch;

	if ((err = fetchprop(cur, DTD_ATTR_DIR, tabptr->zone_fs_dir,
	    sizeof (tabptr->zone_fs_dir))) != Z_OK)
		return (err);

	if ((err = fetchprop(cur, DTD_ATTR_SPECIAL, tabptr->zone_fs_special,
	    sizeof (tabptr->zone_fs_special))) != Z_OK)
		return (err);

	if ((err = fetchprop(cur, DTD_ATTR_RAW, tabptr->zone_fs_raw,
	    sizeof (tabptr->zone_fs_raw))) != Z_OK)
		return (err);

	if ((err = fetchprop(cur, DTD_ATTR_TYPE, tabptr->zone_fs_type,
	    sizeof (tabptr->zone_fs_type))) != Z_OK)
		return (err);

	/* options are optional */
	tabptr->zone_fs_options = NULL;
	for (options = cur->xmlChildrenNode; options != NULL;
	    options = options->next) {
		if ((fetchprop(options, DTD_ATTR_NAME, options_str,
		    sizeof (options_str)) != Z_OK))
			break;
		if (zonecfg_add_fs_option(tabptr, options_str) != Z_OK)
			break;
	}
	return (Z_OK);
}

/*
 * Compare two IP addresses in string form.  Allow for the possibility that
 * one might have "/<prefix-length>" at the end: allow a match on just the
 * IP address (or host name) part.
 */

boolean_t
zonecfg_same_net_address(char *a1, char *a2)
{
	char *slashp, *slashp1, *slashp2;
	int result;

	if (strcmp(a1, a2) == 0)
		return (B_TRUE);

	/*
	 * If neither has a slash or both do, they need to match to be
	 * considered the same, but they did not match above, so fail.
	 */
	slashp1 = strchr(a1, '/');
	slashp2 = strchr(a2, '/');
	if ((slashp1 == NULL && slashp2 == NULL) ||
	    (slashp1 != NULL && slashp2 != NULL))
		return (B_FALSE);

	/*
	 * Only one had a slash: pick that one, zero out the slash, compare
	 * the "address only" strings, restore the slash, and return the
	 * result of the comparison.
	 */
	slashp = (slashp1 == NULL) ? slashp2 : slashp1;
	*slashp = '\0';
	result = strcmp(a1, a2);
	*slashp = '/';
	return ((result == 0));
}

int
zonecfg_valid_net_address(char *address, struct lifreq *lifr)
{
	struct sockaddr_in *sin4;
	struct sockaddr_in6 *sin6;
	struct addrinfo hints, *result;
	char *slashp = strchr(address, '/');

	bzero(lifr, sizeof (struct lifreq));
	sin4 = (struct sockaddr_in *)&lifr->lifr_addr;
	sin6 = (struct sockaddr_in6 *)&lifr->lifr_addr;
	if (slashp != NULL)
		*slashp = '\0';
	if (inet_pton(AF_INET, address, &sin4->sin_addr) == 1) {
		sin4->sin_family = AF_INET;
	} else if (inet_pton(AF_INET6, address, &sin6->sin6_addr) == 1) {
		if (slashp == NULL)
			return (Z_IPV6_ADDR_PREFIX_LEN);
		sin6->sin6_family = AF_INET6;
	} else {
		/* "address" may be a host name */
		(void) memset(&hints, 0, sizeof (hints));
		hints.ai_family = PF_INET;
		if (getaddrinfo(address, NULL, &hints, &result) != 0)
			return (Z_BOGUS_ADDRESS);
		sin4->sin_family = result->ai_family;

		(void) memcpy(&sin4->sin_addr,
		    /* LINTED E_BAD_PTR_CAST_ALIGN */
		    &((struct sockaddr_in *)result->ai_addr)->sin_addr,
		    sizeof (struct in_addr));

		freeaddrinfo(result);
	}
	return (Z_OK);
}

boolean_t
zonecfg_ifname_exists(sa_family_t af, char *ifname)
{
	struct lifreq lifr;
	int so;
	int save_errno;

	(void) memset(&lifr, 0, sizeof (lifr));
	(void) strlcpy(lifr.lifr_name, ifname, sizeof (lifr.lifr_name));
	lifr.lifr_addr.ss_family = af;
	if ((so = socket(af, SOCK_DGRAM, 0)) < 0) {
		/* Odd - can't tell if the ifname exists */
		return (B_FALSE);
	}
	if (ioctl(so, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
		save_errno = errno;
		(void) close(so);
		errno = save_errno;
		return (B_FALSE);
	}
	(void) close(so);
	return (B_TRUE);
}

/*
 * Determines whether there is a net resource with the physical interface, IP
 * address, and default router specified by 'tabptr' in the zone configuration
 * to which 'handle' refers.  'tabptr' must have an interface, an address, a
 * default router, or a combination of the three.  This function returns Z_OK
 * iff there is exactly one net resource matching the query specified by
 * 'tabptr'.  The function returns Z_INSUFFICIENT_SPEC if there are multiple
 * matches or 'tabptr' does not specify a physical interface, address, or
 * default router.  The function returns Z_NO_RESOURCE_ID if are no matches.
 *
 * Errors might also be returned if the entry that exactly matches the
 * query lacks critical network resource information.
 *
 * If there is a single match, then the matching entry's physical interface, IP
 * address, and default router information are stored in 'tabptr'.
 */
int
zonecfg_lookup_nwif(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
{
	xmlNodePtr cur;
	xmlNodePtr firstmatch;
	int err;
	char address[INET6_ADDRSTRLEN];
	char physical[LIFNAMSIZ];
	size_t addrspec;		/* nonzero if tabptr has IP addr */
	size_t physspec;		/* nonzero if tabptr has interface */
	size_t defrouterspec;		/* nonzero if tabptr has def. router */
	size_t allowed_addrspec;
	zone_iptype_t iptype;

	if (tabptr == NULL)
		return (Z_INVAL);

	/*
	 * Determine the fields that will be searched.  There must be at least
	 * one.
	 *
	 * zone_nwif_address, zone_nwif_physical, and zone_nwif_defrouter are
	 * arrays, so no NULL checks are necessary.
	 */
	addrspec = strlen(tabptr->zone_nwif_address);
	physspec = strlen(tabptr->zone_nwif_physical);
	defrouterspec = strlen(tabptr->zone_nwif_defrouter);
	allowed_addrspec = strlen(tabptr->zone_nwif_allowed_address);
	if (addrspec != 0 && allowed_addrspec != 0)
		return (Z_INVAL); /* can't specify both */
	if (addrspec == 0 && physspec == 0 && defrouterspec == 0 &&
	    allowed_addrspec == 0)
		return (Z_INSUFFICIENT_SPEC);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_get_iptype(handle, &iptype)) != Z_OK)
		return (err);
	/*
	 * Iterate over the configuration's elements and look for net elements
	 * that match the query.
	 */
	firstmatch = NULL;
	cur = handle->zone_dh_cur;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		/* Skip non-net elements */
		if (xmlStrcmp(cur->name, DTD_ELEM_NET))
			continue;

		/*
		 * If any relevant fields don't match the query, then skip
		 * the current net element.
		 */
		if (physspec != 0 && (fetchprop(cur, DTD_ATTR_PHYSICAL,
		    physical, sizeof (physical)) != Z_OK ||
		    strcmp(tabptr->zone_nwif_physical, physical) != 0))
			continue;
		if (iptype == ZS_SHARED && addrspec != 0 &&
		    (fetchprop(cur, DTD_ATTR_ADDRESS, address,
		    sizeof (address)) != Z_OK ||
		    !zonecfg_same_net_address(tabptr->zone_nwif_address,
		    address)))
			continue;
		if (iptype == ZS_EXCLUSIVE && allowed_addrspec != 0 &&
		    (fetchprop(cur, DTD_ATTR_ALLOWED_ADDRESS, address,
		    sizeof (address)) != Z_OK ||
		    !zonecfg_same_net_address(tabptr->zone_nwif_allowed_address,
		    address)))
			continue;
		if (defrouterspec != 0 && (fetchprop(cur, DTD_ATTR_DEFROUTER,
		    address, sizeof (address)) != Z_OK ||
		    !zonecfg_same_net_address(tabptr->zone_nwif_defrouter,
		    address)))
			continue;

		/*
		 * The current net element matches the query.  Select it if
		 * it's the first match; otherwise, abort the search.
		 */
		if (firstmatch == NULL)
			firstmatch = cur;
		else
			return (Z_INSUFFICIENT_SPEC);
	}
	if (firstmatch == NULL)
		return (Z_NO_RESOURCE_ID);

	cur = firstmatch;

	if ((err = fetchprop(cur, DTD_ATTR_PHYSICAL, tabptr->zone_nwif_physical,
	    sizeof (tabptr->zone_nwif_physical))) != Z_OK)
		return (err);

	if (iptype == ZS_SHARED &&
	    (err = fetchprop(cur, DTD_ATTR_ADDRESS, tabptr->zone_nwif_address,
	    sizeof (tabptr->zone_nwif_address))) != Z_OK)
		return (err);

	if (iptype == ZS_EXCLUSIVE &&
	    (err = fetchprop(cur, DTD_ATTR_ALLOWED_ADDRESS,
	    tabptr->zone_nwif_allowed_address,
	    sizeof (tabptr->zone_nwif_allowed_address))) != Z_OK)
		return (err);

	if ((err = fetchprop(cur, DTD_ATTR_DEFROUTER,
	    tabptr->zone_nwif_defrouter,
	    sizeof (tabptr->zone_nwif_defrouter))) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_add_nwif_core(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
{
	xmlNodePtr newnode, cur = handle->zone_dh_cur;
	int err;

	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_NET, NULL);
	if (strlen(tabptr->zone_nwif_address) > 0 &&
	    (err = newprop(newnode, DTD_ATTR_ADDRESS,
	    tabptr->zone_nwif_address)) != Z_OK)
		return (err);
	if (strlen(tabptr->zone_nwif_allowed_address) > 0 &&
	    (err = newprop(newnode, DTD_ATTR_ALLOWED_ADDRESS,
	    tabptr->zone_nwif_allowed_address)) != Z_OK)
		return (err);
	if ((err = newprop(newnode, DTD_ATTR_PHYSICAL,
	    tabptr->zone_nwif_physical)) != Z_OK)
		return (err);
	/*
	 * Do not add this property when it is not set, for backwards
	 * compatibility and because it is optional.
	 */
	if ((strlen(tabptr->zone_nwif_defrouter) > 0) &&
	    ((err = newprop(newnode, DTD_ATTR_DEFROUTER,
	    tabptr->zone_nwif_defrouter)) != Z_OK))
		return (err);
	return (Z_OK);
}

int
zonecfg_add_nwif(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_nwif_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_delete_nwif_core(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
{
	xmlNodePtr cur = handle->zone_dh_cur;
	boolean_t addr_match, phys_match, allowed_addr_match;

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_NET))
			continue;

		addr_match = match_prop(cur, DTD_ATTR_ADDRESS,
		    tabptr->zone_nwif_address);
		allowed_addr_match = match_prop(cur, DTD_ATTR_ALLOWED_ADDRESS,
		    tabptr->zone_nwif_allowed_address);
		phys_match = match_prop(cur, DTD_ATTR_PHYSICAL,
		    tabptr->zone_nwif_physical);

		if (addr_match && allowed_addr_match && phys_match) {
			xmlUnlinkNode(cur);
			xmlFreeNode(cur);
			return (Z_OK);
		}
	}
	return (Z_NO_RESOURCE_ID);
}

int
zonecfg_delete_nwif(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_nwif_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_modify_nwif(
	zone_dochandle_t handle,
	struct zone_nwiftab *oldtabptr,
	struct zone_nwiftab *newtabptr)
{
	int err;

	if (oldtabptr == NULL || newtabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_nwif_core(handle, oldtabptr)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_nwif_core(handle, newtabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

/*
 * Must be a comma-separated list of alpha-numeric file system names.
 */
static int
zonecfg_valid_fs_allowed(const char *fsallowedp)
{
	char tmp[ZONE_FS_ALLOWED_MAX];
	char *cp = tmp;
	char *p;

	if (strlen(fsallowedp) > ZONE_FS_ALLOWED_MAX)
		return (Z_TOO_BIG);

	(void) strlcpy(tmp, fsallowedp, sizeof (tmp));

	while (*cp != '\0') {
		p = cp;
		while (*p != '\0' && *p != ',') {
			if (!isalnum(*p) && *p != '-')
				return (Z_INVALID_PROPERTY);
			p++;
		}

		if (*p == ',') {
			if (p == cp)
				return (Z_INVALID_PROPERTY);

			p++;

			if (*p == '\0')
				return (Z_INVALID_PROPERTY);
		}

		cp = p;
	}

	return (Z_OK);
}

int
zonecfg_get_fs_allowed(zone_dochandle_t handle, char *bufp, size_t buflen)
{
	int err;

	if ((err = getrootattr(handle, DTD_ATTR_FS_ALLOWED,
	    bufp, buflen)) != Z_OK)
		return (err);
	if (bufp[0] == '\0')
		return (Z_BAD_PROPERTY);
	return (zonecfg_valid_fs_allowed(bufp));
}

int
zonecfg_set_fs_allowed(zone_dochandle_t handle, const char *bufp)
{
	int err;

	if (bufp == NULL || (err = zonecfg_valid_fs_allowed(bufp)) == Z_OK)
		return (setrootattr(handle, DTD_ATTR_FS_ALLOWED, bufp));
	return (err);
}

/*
 * Determines if the specified string is a valid hostid string.  This function
 * returns Z_OK if the string is a valid hostid string.  It returns Z_INVAL if
 * 'hostidp' is NULL, Z_TOO_BIG if 'hostidp' refers to a string buffer
 * containing a hex string with more than 8 digits, and Z_INVALID_PROPERTY if
 * the string has an invalid format.
 */
static int
zonecfg_valid_hostid(const char *hostidp)
{
	char *currentp;
	u_longlong_t hostidval;
	size_t len;

	if (hostidp == NULL)
		return (Z_INVAL);

	/* Empty strings and strings with whitespace are invalid. */
	if (*hostidp == '\0')
		return (Z_INVALID_PROPERTY);
	for (currentp = (char *)hostidp; *currentp != '\0'; ++currentp) {
		if (isspace(*currentp))
			return (Z_INVALID_PROPERTY);
	}
	len = (size_t)(currentp - hostidp);

	/*
	 * The caller might pass a hostid that is larger than the maximum
	 * unsigned 32-bit integral value.  Check for this!  Also, make sure
	 * that the whole string is converted (this helps us find illegal
	 * characters) and that the whole string fits within a buffer of size
	 * HW_HOSTID_LEN.
	 */
	currentp = (char *)hostidp;
	if (strncmp(hostidp, "0x", 2) == 0 || strncmp(hostidp, "0X", 2) == 0)
		currentp += 2;
	hostidval = strtoull(currentp, &currentp, 16);
	if ((size_t)(currentp - hostidp) >= HW_HOSTID_LEN)
		return (Z_TOO_BIG);
	if (hostidval > UINT_MAX || hostidval == HW_INVALID_HOSTID ||
	    currentp != hostidp + len)
		return (Z_INVALID_PROPERTY);
	return (Z_OK);
}

/*
 * Gets the zone hostid string stored in the specified zone configuration
 * document.  This function returns Z_OK on success.  Z_BAD_PROPERTY is returned
 * if the config file doesn't specify a hostid or if the hostid is blank.
 *
 * Note that buflen should be at least HW_HOSTID_LEN.
 */
int
zonecfg_get_hostid(zone_dochandle_t handle, char *bufp, size_t buflen)
{
	int err;

	if ((err = getrootattr(handle, DTD_ATTR_HOSTID, bufp, buflen)) != Z_OK)
		return (err);
	if (bufp[0] == '\0')
		return (Z_BAD_PROPERTY);
	return (zonecfg_valid_hostid(bufp));
}

/*
 * Sets the hostid string in the specified zone config document to the given
 * string value.  If 'hostidp' is NULL, then the config document's hostid
 * attribute is cleared.  Non-NULL hostids are validated.  This function returns
 * Z_OK on success.  Any other return value indicates failure.
 */
int
zonecfg_set_hostid(zone_dochandle_t handle, const char *hostidp)
{
	int err;

	/*
	 * A NULL hostid string is interpreted as a request to clear the
	 * hostid.
	 */
	if (hostidp == NULL || (err = zonecfg_valid_hostid(hostidp)) == Z_OK)
		return (setrootattr(handle, DTD_ATTR_HOSTID, hostidp));
	return (err);
}

int
zonecfg_lookup_dev(zone_dochandle_t handle, struct zone_devtab *tabptr)
{
	xmlNodePtr cur, firstmatch;
	int err;
	char match[MAXPATHLEN];

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	firstmatch = NULL;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_DEVICE))
			continue;
		if (strlen(tabptr->zone_dev_match) == 0)
			continue;

		if ((fetchprop(cur, DTD_ATTR_MATCH, match,
		    sizeof (match)) == Z_OK)) {
			if (strcmp(tabptr->zone_dev_match,
			    match) == 0) {
				if (firstmatch == NULL)
					firstmatch = cur;
				else if (firstmatch != cur)
					return (Z_INSUFFICIENT_SPEC);
			} else {
				/*
				 * If another property matched but this
				 * one doesn't then reset firstmatch.
				 */
				if (firstmatch == cur)
					firstmatch = NULL;
			}
		}
	}
	if (firstmatch == NULL)
		return (Z_NO_RESOURCE_ID);

	cur = firstmatch;

	if ((err = fetchprop(cur, DTD_ATTR_MATCH, tabptr->zone_dev_match,
	    sizeof (tabptr->zone_dev_match))) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_add_dev_core(zone_dochandle_t handle, struct zone_devtab *tabptr)
{
	xmlNodePtr newnode, cur = handle->zone_dh_cur;
	int err;

	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_DEVICE, NULL);

	if ((err = newprop(newnode, DTD_ATTR_MATCH,
	    tabptr->zone_dev_match)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_add_dev(zone_dochandle_t handle, struct zone_devtab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_dev_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_delete_dev_core(zone_dochandle_t handle, struct zone_devtab *tabptr)
{
	xmlNodePtr cur = handle->zone_dh_cur;
	int match_match;

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_DEVICE))
			continue;

		match_match = match_prop(cur, DTD_ATTR_MATCH,
		    tabptr->zone_dev_match);

		if (match_match) {
			xmlUnlinkNode(cur);
			xmlFreeNode(cur);
			return (Z_OK);
		}
	}
	return (Z_NO_RESOURCE_ID);
}

int
zonecfg_delete_dev(zone_dochandle_t handle, struct zone_devtab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_dev_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_modify_dev(
	zone_dochandle_t handle,
	struct zone_devtab *oldtabptr,
	struct zone_devtab *newtabptr)
{
	int err;

	if (oldtabptr == NULL || newtabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_dev_core(handle, oldtabptr)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_dev_core(handle, newtabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_add_auth_core(zone_dochandle_t handle, struct zone_admintab *tabptr,
    char *zonename)
{
	xmlNodePtr newnode, cur = handle->zone_dh_cur;
	int err;

	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_ADMIN, NULL);
	err = newprop(newnode, DTD_ATTR_USER, tabptr->zone_admin_user);
	if (err != Z_OK)
		return (err);
	err = newprop(newnode, DTD_ATTR_AUTHS, tabptr->zone_admin_auths);
	if (err != Z_OK)
		return (err);
	if ((err = zonecfg_remove_userauths(
	    handle, tabptr->zone_admin_user, zonename, B_FALSE)) != Z_OK)
		return (err);
	return (Z_OK);
}

int
zonecfg_add_admin(zone_dochandle_t handle, struct zone_admintab *tabptr,
    char *zonename)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_auth_core(handle, tabptr,
	    zonename)) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_delete_auth_core(zone_dochandle_t handle, struct zone_admintab *tabptr,
    char *zonename)
{
	xmlNodePtr cur = handle->zone_dh_cur;
	boolean_t auth_match;
	int err;

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
			continue;
		auth_match = match_prop(cur, DTD_ATTR_USER,
		    tabptr->zone_admin_user);
		if (auth_match) {
			if ((err = zonecfg_insert_userauths(
			    handle, tabptr->zone_admin_user,
			    zonename)) != Z_OK)
				return (err);
			xmlUnlinkNode(cur);
			xmlFreeNode(cur);
			return (Z_OK);
		}
	}
	return (Z_NO_RESOURCE_ID);
}

int
zonecfg_delete_admin(zone_dochandle_t handle, struct zone_admintab *tabptr,
    char *zonename)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_auth_core(handle, tabptr, zonename)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_modify_admin(zone_dochandle_t handle, struct zone_admintab *oldtabptr,
    struct zone_admintab *newtabptr, char *zonename)
{
	int err;

	if (oldtabptr == NULL || newtabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_auth_core(handle, oldtabptr, zonename))
	    != Z_OK)
		return (err);

	if ((err = zonecfg_add_auth_core(handle, newtabptr,
	    zonename)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_lookup_admin(zone_dochandle_t handle, struct zone_admintab *tabptr)
{
	xmlNodePtr cur, firstmatch;
	int err;
	char user[MAXUSERNAME];

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	firstmatch = NULL;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
			continue;
		if (strlen(tabptr->zone_admin_user) > 0) {
			if ((fetchprop(cur, DTD_ATTR_USER, user,
			    sizeof (user)) == Z_OK) &&
			    (strcmp(tabptr->zone_admin_user, user) == 0)) {
				if (firstmatch == NULL)
					firstmatch = cur;
				else
					return (Z_INSUFFICIENT_SPEC);
			}
		}
	}
	if (firstmatch == NULL)
		return (Z_NO_RESOURCE_ID);

	cur = firstmatch;

	if ((err = fetchprop(cur, DTD_ATTR_USER, tabptr->zone_admin_user,
	    sizeof (tabptr->zone_admin_user))) != Z_OK)
		return (err);

	if ((err = fetchprop(cur, DTD_ATTR_AUTHS, tabptr->zone_admin_auths,
	    sizeof (tabptr->zone_admin_auths))) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_add_secflags_core(zone_dochandle_t handle,
    struct zone_secflagstab *tabptr)
{
	xmlNodePtr newnode, cur = handle->zone_dh_cur;
	int err;

	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_SECFLAGS, NULL);
	err = newprop(newnode, DTD_ATTR_DEFAULT, tabptr->zone_secflags_default);
	if (err != Z_OK)
		return (err);
	err = newprop(newnode, DTD_ATTR_LOWER, tabptr->zone_secflags_lower);
	if (err != Z_OK)
		return (err);
	err = newprop(newnode, DTD_ATTR_UPPER, tabptr->zone_secflags_upper);
	if (err != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_add_secflags(zone_dochandle_t handle, struct zone_secflagstab *tabptr)
{
	int err;


	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_secflags_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_delete_secflags_core(zone_dochandle_t handle,
    struct zone_secflagstab *tabptr)
{
	xmlNodePtr cur = handle->zone_dh_cur;
	boolean_t def_match, low_match, up_match;

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_SECFLAGS) != 0)
			continue;

		def_match = match_prop(cur, DTD_ATTR_DEFAULT,
		    tabptr->zone_secflags_default);
		low_match = match_prop(cur, DTD_ATTR_LOWER,
		    tabptr->zone_secflags_lower);
		up_match = match_prop(cur, DTD_ATTR_UPPER,
		    tabptr->zone_secflags_upper);

		if (def_match && low_match && up_match) {
			xmlUnlinkNode(cur);
			xmlFreeNode(cur);
			return (Z_OK);
		}

	}
	return (Z_NO_RESOURCE_ID);
}

int
zonecfg_delete_secflags(zone_dochandle_t handle,
    struct zone_secflagstab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_secflags_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_modify_secflags(zone_dochandle_t handle,
    struct zone_secflagstab *oldtabptr,
    struct zone_secflagstab *newtabptr)
{
	int err;

	if (oldtabptr == NULL || newtabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_secflags_core(handle, oldtabptr))
	    != Z_OK)
		return (err);

	if ((err = zonecfg_add_secflags_core(handle, newtabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_lookup_secflags(zone_dochandle_t handle,
    struct zone_secflagstab *tabptr)
{
	xmlNodePtr cur;
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_SECFLAGS) != 0)
			continue;

		if ((err = fetchprop(cur, DTD_ATTR_DEFAULT,
		    tabptr->zone_secflags_default,
		    sizeof (tabptr->zone_secflags_default))) != Z_OK) {
			handle->zone_dh_cur = handle->zone_dh_top;
			return (err);
		}

		if ((err = fetchprop(cur, DTD_ATTR_LOWER,
		    tabptr->zone_secflags_lower,
		    sizeof (tabptr->zone_secflags_lower))) != Z_OK) {
			handle->zone_dh_cur = handle->zone_dh_top;
			return (err);
		}

		if ((err = fetchprop(cur, DTD_ATTR_UPPER,
		    tabptr->zone_secflags_upper,
		    sizeof (tabptr->zone_secflags_upper))) != Z_OK) {
			handle->zone_dh_cur = handle->zone_dh_top;
			return (err);
		}

		return (Z_OK);
	}

	return (Z_NO_ENTRY);
}

/* Lock to serialize all devwalks */
static pthread_mutex_t zonecfg_devwalk_lock = PTHREAD_MUTEX_INITIALIZER;
/*
 * Global variables used to pass data from zonecfg_dev_manifest to the nftw
 * call-back (zonecfg_devwalk_cb).  g_devwalk_data is really the void*
 * parameter and g_devwalk_cb is really the *cb parameter from
 * zonecfg_dev_manifest.
 */
typedef struct __g_devwalk_data *g_devwalk_data_t;
static g_devwalk_data_t g_devwalk_data;
static int (*g_devwalk_cb)(const char *, uid_t, gid_t, mode_t, const char *,
    void *);
static size_t g_devwalk_skip_prefix;

/*
 * zonecfg_dev_manifest call-back function used during detach to generate the
 * dev info in the manifest.
 */
static int
get_detach_dev_entry(const char *name, uid_t uid, gid_t gid, mode_t mode,
    const char *acl, void *hdl)
{
	zone_dochandle_t handle = (zone_dochandle_t)hdl;
	xmlNodePtr newnode;
	xmlNodePtr cur;
	int err;
	char buf[128];

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_DEV_PERM, NULL);
	if ((err = newprop(newnode, DTD_ATTR_NAME, (char *)name)) != Z_OK)
		return (err);
	(void) snprintf(buf, sizeof (buf), "%lu", uid);
	if ((err = newprop(newnode, DTD_ATTR_UID, buf)) != Z_OK)
		return (err);
	(void) snprintf(buf, sizeof (buf), "%lu", gid);
	if ((err = newprop(newnode, DTD_ATTR_GID, buf)) != Z_OK)
		return (err);
	(void) snprintf(buf, sizeof (buf), "%o", mode);
	if ((err = newprop(newnode, DTD_ATTR_MODE, buf)) != Z_OK)
		return (err);
	if ((err = newprop(newnode, DTD_ATTR_ACL, (char *)acl)) != Z_OK)
		return (err);
	return (Z_OK);
}

/*
 * This is the nftw call-back function used by zonecfg_dev_manifest.  It is
 * responsible for calling the actual call-back.
 */
/* ARGSUSED2 */
static int
zonecfg_devwalk_cb(const char *path, const struct stat *st, int f,
    struct FTW *ftw)
{
	acl_t *acl;
	char *acl_txt = NULL;

	/* skip all but character and block devices */
	if (!S_ISBLK(st->st_mode) && !S_ISCHR(st->st_mode))
		return (0);

	if ((acl_get(path, ACL_NO_TRIVIAL, &acl) == 0) &&
	    acl != NULL) {
		acl_txt = acl_totext(acl, ACL_NORESOLVE);
		acl_free(acl);
	}

	if (strlen(path) <= g_devwalk_skip_prefix)
		return (0);

	(void) g_devwalk_cb(path + g_devwalk_skip_prefix, st->st_uid,
	    st->st_gid, st->st_mode & S_IAMB, acl_txt != NULL ? acl_txt : "",
	    g_devwalk_data);
	free(acl_txt);
	return (0);
}

/*
 * Walk the dev tree for the zone specified by hdl and call the
 * get_detach_dev_entry call-back function for each entry in the tree.  The
 * call-back will be passed the name, uid, gid, mode, acl string and the
 * handle input parameter for each dev entry.
 *
 * Data is passed to get_detach_dev_entry through the global variables
 * g_devwalk_data, *g_devwalk_cb, and g_devwalk_skip_prefix.  The
 * zonecfg_devwalk_cb function will actually call get_detach_dev_entry.
 */
int
zonecfg_dev_manifest(zone_dochandle_t hdl)
{
	char path[MAXPATHLEN];
	int ret;

	if ((ret = zonecfg_get_zonepath(hdl, path, sizeof (path))) != Z_OK)
		return (ret);

	if (strlcat(path, "/dev", sizeof (path)) >= sizeof (path))
		return (Z_TOO_BIG);

	/*
	 * We have to serialize all devwalks in the same process
	 * (which should be fine), since nftw() is so badly designed.
	 */
	(void) pthread_mutex_lock(&zonecfg_devwalk_lock);

	g_devwalk_skip_prefix = strlen(path) + 1;
	g_devwalk_data = (g_devwalk_data_t)hdl;
	g_devwalk_cb = get_detach_dev_entry;
	(void) nftw(path, zonecfg_devwalk_cb, 0, FTW_PHYS);

	(void) pthread_mutex_unlock(&zonecfg_devwalk_lock);
	return (Z_OK);
}

/*
 * Update the owner, group, mode and acl on the specified dev (inpath) for
 * the zone (hdl).  This function can be used to fix up the dev tree after
 * attaching a migrated zone.
 */
int
zonecfg_devperms_apply(zone_dochandle_t hdl, const char *inpath, uid_t owner,
    gid_t group, mode_t mode, const char *acltxt)
{
	int ret;
	char path[MAXPATHLEN];
	struct stat st;
	acl_t *aclp;

	if ((ret = zonecfg_get_zonepath(hdl, path, sizeof (path))) != Z_OK)
		return (ret);

	if (strlcat(path, "/dev/", sizeof (path)) >= sizeof (path))
		return (Z_TOO_BIG);
	if (strlcat(path, inpath, sizeof (path)) >= sizeof (path))
		return (Z_TOO_BIG);

	if (stat(path, &st) == -1)
		return (Z_INVAL);

	/* make sure we're only touching device nodes */
	if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode))
		return (Z_INVAL);

	if (chown(path, owner, group) == -1)
		return (Z_SYSTEM);

	if (chmod(path, mode) == -1)
		return (Z_SYSTEM);

	if ((acltxt == NULL) || (strcmp(acltxt, "") == 0))
		return (Z_OK);

	if (acl_fromtext(acltxt, &aclp) != 0) {
		errno = EINVAL;
		return (Z_SYSTEM);
	}

	errno = 0;
	if (acl_set(path, aclp) == -1) {
		free(aclp);
		return (Z_SYSTEM);
	}

	free(aclp);
	return (Z_OK);
}

/*
 * This function finds everything mounted under a zone's rootpath.
 * This returns the number of mounts under rootpath, or -1 on error.
 * callback is called once per mount found with the first argument
 * pointing to a mnttab structure containing the mount's information.
 *
 * If the callback function returns non-zero zonecfg_find_mounts
 * aborts with an error.
 */
int
zonecfg_find_mounts(char *rootpath, int (*callback)(const struct mnttab *,
    void *), void *priv)
{
	FILE *mnttab;
	struct mnttab m;
	size_t l;
	int zfsl;
	int rv = 0;
	char zfs_path[MAXPATHLEN];

	assert(rootpath != NULL);

	if ((zfsl = snprintf(zfs_path, sizeof (zfs_path), "%s/.zfs/", rootpath))
	    >= sizeof (zfs_path))
		return (-1);

	l = strlen(rootpath);

	mnttab = fopen("/etc/mnttab", "r");

	if (mnttab == NULL)
		return (-1);

	if (ioctl(fileno(mnttab), MNTIOC_SHOWHIDDEN, NULL) < 0)  {
		rv = -1;
		goto out;
	}

	while (!getmntent(mnttab, &m)) {
		if ((strncmp(rootpath, m.mnt_mountp, l) == 0) &&
		    (m.mnt_mountp[l] == '/') &&
		    (strncmp(zfs_path, m.mnt_mountp, zfsl) != 0)) {
			rv++;
			if (callback == NULL)
				continue;
			if (callback(&m, priv)) {
				rv = -1;
				goto out;

			}
		}
	}

out:
	(void) fclose(mnttab);
	return (rv);
}

int
zonecfg_lookup_attr(zone_dochandle_t handle, struct zone_attrtab *tabptr)
{
	xmlNodePtr cur, firstmatch;
	int err;
	char name[MAXNAMELEN], type[MAXNAMELEN], value[MAXNAMELEN];

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	firstmatch = NULL;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_ATTR))
			continue;
		if (strlen(tabptr->zone_attr_name) > 0) {
			if ((fetchprop(cur, DTD_ATTR_NAME, name,
			    sizeof (name)) == Z_OK) &&
			    (strcmp(tabptr->zone_attr_name, name) == 0)) {
				if (firstmatch == NULL)
					firstmatch = cur;
				else
					return (Z_INSUFFICIENT_SPEC);
			}
		}
		if (strlen(tabptr->zone_attr_type) > 0) {
			if ((fetchprop(cur, DTD_ATTR_TYPE, type,
			    sizeof (type)) == Z_OK)) {
				if (strcmp(tabptr->zone_attr_type, type) == 0) {
					if (firstmatch == NULL)
						firstmatch = cur;
					else if (firstmatch != cur)
						return (Z_INSUFFICIENT_SPEC);
				} else {
					/*
					 * If another property matched but this
					 * one doesn't then reset firstmatch.
					 */
					if (firstmatch == cur)
						firstmatch = NULL;
				}
			}
		}
		if (strlen(tabptr->zone_attr_value) > 0) {
			if ((fetchprop(cur, DTD_ATTR_VALUE, value,
			    sizeof (value)) == Z_OK)) {
				if (strcmp(tabptr->zone_attr_value, value) ==
				    0) {
					if (firstmatch == NULL)
						firstmatch = cur;
					else if (firstmatch != cur)
						return (Z_INSUFFICIENT_SPEC);
				} else {
					/*
					 * If another property matched but this
					 * one doesn't then reset firstmatch.
					 */
					if (firstmatch == cur)
						firstmatch = NULL;
				}
			}
		}
	}
	if (firstmatch == NULL)
		return (Z_NO_RESOURCE_ID);

	cur = firstmatch;

	if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_attr_name,
	    sizeof (tabptr->zone_attr_name))) != Z_OK)
		return (err);

	if ((err = fetchprop(cur, DTD_ATTR_TYPE, tabptr->zone_attr_type,
	    sizeof (tabptr->zone_attr_type))) != Z_OK)
		return (err);

	if ((err = fetchprop(cur, DTD_ATTR_VALUE, tabptr->zone_attr_value,
	    sizeof (tabptr->zone_attr_value))) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_add_attr_core(zone_dochandle_t handle, struct zone_attrtab *tabptr)
{
	xmlNodePtr newnode, cur = handle->zone_dh_cur;
	int err;

	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_ATTR, NULL);
	err = newprop(newnode, DTD_ATTR_NAME, tabptr->zone_attr_name);
	if (err != Z_OK)
		return (err);
	err = newprop(newnode, DTD_ATTR_TYPE, tabptr->zone_attr_type);
	if (err != Z_OK)
		return (err);
	err = newprop(newnode, DTD_ATTR_VALUE, tabptr->zone_attr_value);
	if (err != Z_OK)
		return (err);
	return (Z_OK);
}

int
zonecfg_add_attr(zone_dochandle_t handle, struct zone_attrtab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_attr_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_delete_attr_core(zone_dochandle_t handle, struct zone_attrtab *tabptr)
{
	xmlNodePtr cur = handle->zone_dh_cur;
	int name_match, type_match, value_match;

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_ATTR))
			continue;

		name_match = match_prop(cur, DTD_ATTR_NAME,
		    tabptr->zone_attr_name);
		type_match = match_prop(cur, DTD_ATTR_TYPE,
		    tabptr->zone_attr_type);
		value_match = match_prop(cur, DTD_ATTR_VALUE,
		    tabptr->zone_attr_value);

		if (name_match && type_match && value_match) {
			xmlUnlinkNode(cur);
			xmlFreeNode(cur);
			return (Z_OK);
		}
	}
	return (Z_NO_RESOURCE_ID);
}

int
zonecfg_delete_attr(zone_dochandle_t handle, struct zone_attrtab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_attr_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_modify_attr(
	zone_dochandle_t handle,
	struct zone_attrtab *oldtabptr,
	struct zone_attrtab *newtabptr)
{
	int err;

	if (oldtabptr == NULL || newtabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_attr_core(handle, oldtabptr)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_attr_core(handle, newtabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_get_attr_boolean(const struct zone_attrtab *attr, boolean_t *value)
{
	if (attr == NULL)
		return (Z_INVAL);

	if (strcmp(attr->zone_attr_type, DTD_ENTITY_BOOLEAN) != 0)
		return (Z_INVAL);

	if (strcmp(attr->zone_attr_value, DTD_ENTITY_TRUE) == 0) {
		*value = B_TRUE;
		return (Z_OK);
	}
	if (strcmp(attr->zone_attr_value, DTD_ENTITY_FALSE) == 0) {
		*value = B_FALSE;
		return (Z_OK);
	}
	return (Z_INVAL);
}

int
zonecfg_get_attr_int(const struct zone_attrtab *attr, int64_t *value)
{
	long long result;
	char *endptr;

	if (attr == NULL)
		return (Z_INVAL);

	if (strcmp(attr->zone_attr_type, DTD_ENTITY_INT) != 0)
		return (Z_INVAL);

	errno = 0;
	result = strtoll(attr->zone_attr_value, &endptr, 10);
	if (errno != 0 || *endptr != '\0')
		return (Z_INVAL);
	*value = result;
	return (Z_OK);
}

int
zonecfg_get_attr_string(const struct zone_attrtab *attr, char *value,
    size_t val_sz)
{
	if (attr == NULL)
		return (Z_INVAL);

	if (strcmp(attr->zone_attr_type, DTD_ENTITY_STRING) != 0)
		return (Z_INVAL);

	if (strlcpy(value, attr->zone_attr_value, val_sz) >= val_sz)
		return (Z_TOO_BIG);
	return (Z_OK);
}

int
zonecfg_get_attr_uint(const struct zone_attrtab *attr, uint64_t *value)
{
	unsigned long long result;
	long long neg_result;
	char *endptr;

	if (attr == NULL)
		return (Z_INVAL);

	if (strcmp(attr->zone_attr_type, DTD_ENTITY_UINT) != 0)
		return (Z_INVAL);

	errno = 0;
	result = strtoull(attr->zone_attr_value, &endptr, 10);
	if (errno != 0 || *endptr != '\0')
		return (Z_INVAL);
	errno = 0;
	neg_result = strtoll(attr->zone_attr_value, &endptr, 10);
	/*
	 * Incredibly, strtoull("<negative number>", ...) will not fail but
	 * return whatever (negative) number cast as a u_longlong_t, so we
	 * need to look for this here.
	 */
	if (errno == 0 && neg_result < 0)
		return (Z_INVAL);
	*value = result;
	return (Z_OK);
}

int
zonecfg_lookup_rctl(zone_dochandle_t handle, struct zone_rctltab *tabptr)
{
	xmlNodePtr cur, val;
	char savedname[MAXNAMELEN];
	struct zone_rctlvaltab *valptr;
	int err;

	if (strlen(tabptr->zone_rctl_name) == 0)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_RCTL))
			continue;
		if ((fetchprop(cur, DTD_ATTR_NAME, savedname,
		    sizeof (savedname)) == Z_OK) &&
		    (strcmp(savedname, tabptr->zone_rctl_name) == 0)) {
			tabptr->zone_rctl_valptr = NULL;
			for (val = cur->xmlChildrenNode; val != NULL;
			    val = val->next) {
				valptr = (struct zone_rctlvaltab *)malloc(
				    sizeof (struct zone_rctlvaltab));
				if (valptr == NULL)
					return (Z_NOMEM);
				if ((fetchprop(val, DTD_ATTR_PRIV,
				    valptr->zone_rctlval_priv,
				    sizeof (valptr->zone_rctlval_priv)) !=
				    Z_OK))
					break;
				if ((fetchprop(val, DTD_ATTR_LIMIT,
				    valptr->zone_rctlval_limit,
				    sizeof (valptr->zone_rctlval_limit)) !=
				    Z_OK))
					break;
				if ((fetchprop(val, DTD_ATTR_ACTION,
				    valptr->zone_rctlval_action,
				    sizeof (valptr->zone_rctlval_action)) !=
				    Z_OK))
					break;
				if (zonecfg_add_rctl_value(tabptr, valptr) !=
				    Z_OK)
					break;
			}
			return (Z_OK);
		}
	}
	return (Z_NO_RESOURCE_ID);
}

static int
zonecfg_add_rctl_core(zone_dochandle_t handle, struct zone_rctltab *tabptr)
{
	xmlNodePtr newnode, cur = handle->zone_dh_cur, valnode;
	struct zone_rctlvaltab *valptr;
	int err;

	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_RCTL, NULL);
	err = newprop(newnode, DTD_ATTR_NAME, tabptr->zone_rctl_name);
	if (err != Z_OK)
		return (err);
	for (valptr = tabptr->zone_rctl_valptr; valptr != NULL;
	    valptr = valptr->zone_rctlval_next) {
		valnode = xmlNewTextChild(newnode, NULL,
		    DTD_ELEM_RCTLVALUE, NULL);
		err = newprop(valnode, DTD_ATTR_PRIV,
		    valptr->zone_rctlval_priv);
		if (err != Z_OK)
			return (err);
		err = newprop(valnode, DTD_ATTR_LIMIT,
		    valptr->zone_rctlval_limit);
		if (err != Z_OK)
			return (err);
		err = newprop(valnode, DTD_ATTR_ACTION,
		    valptr->zone_rctlval_action);
		if (err != Z_OK)
			return (err);
	}
	return (Z_OK);
}

int
zonecfg_add_rctl(zone_dochandle_t handle, struct zone_rctltab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_rctl_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_delete_rctl_core(zone_dochandle_t handle, struct zone_rctltab *tabptr)
{
	xmlNodePtr cur = handle->zone_dh_cur;
	xmlChar *savedname;
	int name_result;

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_RCTL))
			continue;

		savedname = xmlGetProp(cur, DTD_ATTR_NAME);
		if (savedname == NULL)	/* shouldn't happen */
			continue;
		name_result = xmlStrcmp(savedname,
		    (const xmlChar *) tabptr->zone_rctl_name);
		xmlFree(savedname);

		if (name_result == 0) {
			xmlUnlinkNode(cur);
			xmlFreeNode(cur);
			return (Z_OK);
		}
	}
	return (Z_NO_RESOURCE_ID);
}

int
zonecfg_delete_rctl(zone_dochandle_t handle, struct zone_rctltab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_rctl_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_modify_rctl(
	zone_dochandle_t handle,
	struct zone_rctltab *oldtabptr,
	struct zone_rctltab *newtabptr)
{
	int err;

	if (oldtabptr == NULL || newtabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_rctl_core(handle, oldtabptr)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_rctl_core(handle, newtabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_add_rctl_value(
	struct zone_rctltab *tabptr,
	struct zone_rctlvaltab *valtabptr)
{
	struct zone_rctlvaltab *last, *old, *new;
	rctlblk_t *rctlblk = alloca(rctlblk_size());

	last = tabptr->zone_rctl_valptr;
	for (old = last; old != NULL; old = old->zone_rctlval_next)
		last = old;	/* walk to the end of the list */
	new = valtabptr;	/* alloc'd by caller */
	new->zone_rctlval_next = NULL;
	if (zonecfg_construct_rctlblk(valtabptr, rctlblk) != Z_OK)
		return (Z_INVAL);
	if (!zonecfg_valid_rctlblk(rctlblk))
		return (Z_INVAL);
	if (last == NULL)
		tabptr->zone_rctl_valptr = new;
	else
		last->zone_rctlval_next = new;
	return (Z_OK);
}

int
zonecfg_remove_rctl_value(
	struct zone_rctltab *tabptr,
	struct zone_rctlvaltab *valtabptr)
{
	struct zone_rctlvaltab *last, *this, *next;

	last = tabptr->zone_rctl_valptr;
	for (this = last; this != NULL; this = this->zone_rctlval_next) {
		if (strcmp(this->zone_rctlval_priv,
		    valtabptr->zone_rctlval_priv) == 0 &&
		    strcmp(this->zone_rctlval_limit,
		    valtabptr->zone_rctlval_limit) == 0 &&
		    strcmp(this->zone_rctlval_action,
		    valtabptr->zone_rctlval_action) == 0) {
			next = this->zone_rctlval_next;
			if (this == tabptr->zone_rctl_valptr)
				tabptr->zone_rctl_valptr = next;
			else
				last->zone_rctlval_next = next;
			free(this);
			return (Z_OK);
		} else
			last = this;
	}
	return (Z_NO_PROPERTY_ID);
}

void
zonecfg_set_swinv(zone_dochandle_t handle)
{
	handle->zone_dh_sw_inv = B_TRUE;
}

/*
 * Add the pkg to the sw inventory on the handle.
 */
int
zonecfg_add_pkg(zone_dochandle_t handle, char *name, char *version)
{
	xmlNodePtr newnode;
	xmlNodePtr cur;
	int err;

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_PACKAGE, NULL);
	if ((err = newprop(newnode, DTD_ATTR_NAME, name)) != Z_OK)
		return (err);
	if ((err = newprop(newnode, DTD_ATTR_VERSION, version)) != Z_OK)
		return (err);
	return (Z_OK);
}

char *
zonecfg_strerror(int errnum)
{
	switch (errnum) {
	case Z_OK:
		return (dgettext(TEXT_DOMAIN, "OK"));
	case Z_EMPTY_DOCUMENT:
		return (dgettext(TEXT_DOMAIN, "Empty document"));
	case Z_WRONG_DOC_TYPE:
		return (dgettext(TEXT_DOMAIN, "Wrong document type"));
	case Z_BAD_PROPERTY:
		return (dgettext(TEXT_DOMAIN, "Bad document property"));
	case Z_TEMP_FILE:
		return (dgettext(TEXT_DOMAIN,
		    "Problem creating temporary file"));
	case Z_SAVING_FILE:
		return (dgettext(TEXT_DOMAIN, "Problem saving file"));
	case Z_NO_ENTRY:
		return (dgettext(TEXT_DOMAIN, "No such entry"));
	case Z_BOGUS_ZONE_NAME:
		return (dgettext(TEXT_DOMAIN, "Bogus zone name"));
	case Z_REQD_RESOURCE_MISSING:
		return (dgettext(TEXT_DOMAIN, "Required resource missing"));
	case Z_REQD_PROPERTY_MISSING:
		return (dgettext(TEXT_DOMAIN, "Required property missing"));
	case Z_BAD_HANDLE:
		return (dgettext(TEXT_DOMAIN, "Bad handle"));
	case Z_NOMEM:
		return (dgettext(TEXT_DOMAIN, "Out of memory"));
	case Z_INVAL:
		return (dgettext(TEXT_DOMAIN, "Invalid argument"));
	case Z_ACCES:
		return (dgettext(TEXT_DOMAIN, "Permission denied"));
	case Z_TOO_BIG:
		return (dgettext(TEXT_DOMAIN, "Argument list too long"));
	case Z_MISC_FS:
		return (dgettext(TEXT_DOMAIN,
		    "Miscellaneous file system error"));
	case Z_NO_ZONE:
		return (dgettext(TEXT_DOMAIN, "No such zone configured"));
	case Z_NO_RESOURCE_TYPE:
		return (dgettext(TEXT_DOMAIN, "No such resource type"));
	case Z_NO_RESOURCE_ID:
		return (dgettext(TEXT_DOMAIN, "No such resource with that id"));
	case Z_NO_PROPERTY_TYPE:
		return (dgettext(TEXT_DOMAIN, "No such property type"));
	case Z_NO_PROPERTY_ID:
		return (dgettext(TEXT_DOMAIN, "No such property with that id"));
	case Z_BAD_ZONE_STATE:
		return (dgettext(TEXT_DOMAIN,
		    "Zone state is invalid for the requested operation"));
	case Z_INVALID_DOCUMENT:
		return (dgettext(TEXT_DOMAIN, "Invalid document"));
	case Z_NAME_IN_USE:
		return (dgettext(TEXT_DOMAIN, "Zone name already in use"));
	case Z_NO_SUCH_ID:
		return (dgettext(TEXT_DOMAIN, "No such zone ID"));
	case Z_UPDATING_INDEX:
		return (dgettext(TEXT_DOMAIN, "Problem updating index file"));
	case Z_LOCKING_FILE:
		return (dgettext(TEXT_DOMAIN, "Locking index file"));
	case Z_UNLOCKING_FILE:
		return (dgettext(TEXT_DOMAIN, "Unlocking index file"));
	case Z_INSUFFICIENT_SPEC:
		return (dgettext(TEXT_DOMAIN, "Insufficient specification"));
	case Z_RESOLVED_PATH:
		return (dgettext(TEXT_DOMAIN, "Resolved path mismatch"));
	case Z_IPV6_ADDR_PREFIX_LEN:
		return (dgettext(TEXT_DOMAIN,
		    "IPv6 address missing required prefix length"));
	case Z_BOGUS_ADDRESS:
		return (dgettext(TEXT_DOMAIN,
		    "Neither an IPv4 nor an IPv6 address nor a host name"));
	case Z_PRIV_PROHIBITED:
		return (dgettext(TEXT_DOMAIN,
		    "Specified privilege is prohibited"));
	case Z_PRIV_REQUIRED:
		return (dgettext(TEXT_DOMAIN,
		    "Required privilege is missing"));
	case Z_PRIV_UNKNOWN:
		return (dgettext(TEXT_DOMAIN,
		    "Specified privilege is unknown"));
	case Z_BRAND_ERROR:
		return (dgettext(TEXT_DOMAIN,
		    "Brand-specific error"));
	case Z_INCOMPATIBLE:
		return (dgettext(TEXT_DOMAIN, "Incompatible settings"));
	case Z_ALIAS_DISALLOW:
		return (dgettext(TEXT_DOMAIN,
		    "An incompatible rctl already exists for this property"));
	case Z_CLEAR_DISALLOW:
		return (dgettext(TEXT_DOMAIN,
		    "Clearing this property is not allowed"));
	case Z_POOL:
		return (dgettext(TEXT_DOMAIN, "libpool(3LIB) error"));
	case Z_POOLS_NOT_ACTIVE:
		return (dgettext(TEXT_DOMAIN, "Pools facility not active; "
		    "zone will not be bound to pool"));
	case Z_POOL_ENABLE:
		return (dgettext(TEXT_DOMAIN,
		    "Could not enable pools facility"));
	case Z_NO_POOL:
		return (dgettext(TEXT_DOMAIN,
		    "Pool not found; using default pool"));
	case Z_POOL_CREATE:
		return (dgettext(TEXT_DOMAIN,
		    "Could not create a temporary pool"));
	case Z_POOL_BIND:
		return (dgettext(TEXT_DOMAIN, "Could not bind zone to pool"));
	case Z_INVALID_PROPERTY:
		return (dgettext(TEXT_DOMAIN, "Specified property is invalid"));
	case Z_SYSTEM:
		return (strerror(errno));
	default:
		return (dgettext(TEXT_DOMAIN, "Unknown error"));
	}
}

/*
 * Note that the zonecfg_setXent() and zonecfg_endXent() calls are all the
 * same, as they just turn around and call zonecfg_setent() / zonecfg_endent().
 */

static int
zonecfg_setent(zone_dochandle_t handle)
{
	xmlNodePtr cur;
	int err;

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

	if ((err = operation_prep(handle)) != Z_OK) {
		handle->zone_dh_cur = NULL;
		return (err);
	}
	cur = handle->zone_dh_cur;
	cur = cur->xmlChildrenNode;
	handle->zone_dh_cur = cur;
	return (Z_OK);
}

static int
zonecfg_endent(zone_dochandle_t handle)
{
	if (handle == NULL)
		return (Z_INVAL);

	handle->zone_dh_cur = handle->zone_dh_top;
	return (Z_OK);
}

/*
 * Do the work required to manipulate a process through libproc.
 * If grab_process() returns no errors (0), then release_process()
 * must eventually be called.
 *
 * Return values:
 *      0 Successful creation of agent thread
 *      1 Error grabbing
 *      2 Error creating agent
 */
static int
grab_process(pr_info_handle_t *p)
{
	int ret;

	if ((p->pr = Pgrab(p->pid, 0, &ret)) != NULL) {

		if (Psetflags(p->pr, PR_RLC) != 0) {
			Prelease(p->pr, 0);
			return (1);
		}
		if (Pcreate_agent(p->pr) == 0) {
			return (0);

		} else {
			Prelease(p->pr, 0);
			return (2);
		}
	} else {
		return (1);
	}
}

/*
 * Release the specified process. This destroys the agent
 * and releases the process. If the process is NULL, nothing
 * is done. This function should only be called if grab_process()
 * has previously been called and returned success.
 *
 * This function is Pgrab-safe.
 */
static void
release_process(struct ps_prochandle *Pr)
{
	if (Pr == NULL)
		return;

	Pdestroy_agent(Pr);
	Prelease(Pr, 0);
}

static boolean_t
grab_zone_proc(char *zonename, pr_info_handle_t *p)
{
	DIR *dirp;
	struct dirent *dentp;
	zoneid_t zoneid;
	int pid_self;
	psinfo_t psinfo;

	if (zone_get_id(zonename, &zoneid) != 0)
		return (B_FALSE);

	pid_self = getpid();

	if ((dirp = opendir("/proc")) == NULL)
		return (B_FALSE);

	while (dentp = readdir(dirp)) {
		p->pid = atoi(dentp->d_name);

		/* Skip self */
		if (p->pid == pid_self)
			continue;

		if (proc_get_psinfo(p->pid, &psinfo) != 0)
			continue;

		if (psinfo.pr_zoneid != zoneid)
			continue;

		/* attempt to grab process */
		if (grab_process(p) != 0)
			continue;

		if (pr_getzoneid(p->pr) != zoneid) {
			release_process(p->pr);
			continue;
		}

		(void) closedir(dirp);
		return (B_TRUE);
	}

	(void) closedir(dirp);
	return (B_FALSE);
}

static boolean_t
get_priv_rctl(struct ps_prochandle *pr, char *name, rctlblk_t *rblk)
{
	if (pr_getrctl(pr, name, NULL, rblk, RCTL_FIRST))
		return (B_FALSE);

	if (rctlblk_get_privilege(rblk) == RCPRIV_PRIVILEGED)
		return (B_TRUE);

	while (pr_getrctl(pr, name, rblk, rblk, RCTL_NEXT) == 0) {
		if (rctlblk_get_privilege(rblk) == RCPRIV_PRIVILEGED)
			return (B_TRUE);
	}

	return (B_FALSE);
}

/*
 * Apply the current rctl settings to the specified, running zone.
 */
int
zonecfg_apply_rctls(char *zone_name, zone_dochandle_t handle)
{
	int err;
	int res = Z_OK;
	rctlblk_t *rblk;
	pr_info_handle_t p;
	struct zone_rctltab rctl;

	if ((err = zonecfg_setrctlent(handle)) != Z_OK)
		return (err);

	if ((rblk = (rctlblk_t *)malloc(rctlblk_size())) == NULL) {
		(void) zonecfg_endrctlent(handle);
		return (Z_NOMEM);
	}

	if (!grab_zone_proc(zone_name, &p)) {
		(void) zonecfg_endrctlent(handle);
		free(rblk);
		return (Z_SYSTEM);
	}

	while (zonecfg_getrctlent(handle, &rctl) == Z_OK) {
		char *rname;
		struct zone_rctlvaltab *valptr;

		rname = rctl.zone_rctl_name;

		/* first delete all current privileged settings for this rctl */
		while (get_priv_rctl(p.pr, rname, rblk)) {
			if (pr_setrctl(p.pr, rname, NULL, rblk, RCTL_DELETE) !=
			    0) {
				res = Z_SYSTEM;
				goto done;
			}
		}

		/* now set each new value for the rctl */
		for (valptr = rctl.zone_rctl_valptr; valptr != NULL;
		    valptr = valptr->zone_rctlval_next) {
			if ((err = zonecfg_construct_rctlblk(valptr, rblk))
			    != Z_OK) {
				res = errno = err;
				goto done;
			}

			if (pr_setrctl(p.pr, rname, NULL, rblk, RCTL_INSERT)) {
				res = Z_SYSTEM;
				goto done;
			}
		}
	}

done:
	release_process(p.pr);
	free(rblk);
	(void) zonecfg_endrctlent(handle);

	return (res);
}

static const xmlChar *
nm_to_dtd(char *nm)
{
	if (strcmp(nm, "device") == 0)
		return (DTD_ELEM_DEVICE);
	if (strcmp(nm, "fs") == 0)
		return (DTD_ELEM_FS);
	if (strcmp(nm, "net") == 0)
		return (DTD_ELEM_NET);
	if (strcmp(nm, "attr") == 0)
		return (DTD_ELEM_ATTR);
	if (strcmp(nm, "rctl") == 0)
		return (DTD_ELEM_RCTL);
	if (strcmp(nm, "dataset") == 0)
		return (DTD_ELEM_DATASET);
	if (strcmp(nm, "admin") == 0)
		return (DTD_ELEM_ADMIN);

	return (NULL);
}

int
zonecfg_num_resources(zone_dochandle_t handle, char *rsrc)
{
	int num = 0;
	const xmlChar *dtd;
	xmlNodePtr cur;

	if ((dtd = nm_to_dtd(rsrc)) == NULL)
		return (num);

	if (zonecfg_setent(handle) != Z_OK)
		return (num);

	for (cur = handle->zone_dh_cur; cur != NULL; cur = cur->next)
		if (xmlStrcmp(cur->name, dtd) == 0)
			num++;

	(void) zonecfg_endent(handle);

	return (num);
}

int
zonecfg_del_all_resources(zone_dochandle_t handle, char *rsrc)
{
	int err;
	const xmlChar *dtd;
	xmlNodePtr cur;

	if ((dtd = nm_to_dtd(rsrc)) == NULL)
		return (Z_NO_RESOURCE_TYPE);

	if ((err = zonecfg_setent(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	while (cur != NULL) {
		xmlNodePtr tmp;

		if (xmlStrcmp(cur->name, dtd)) {
			cur = cur->next;
			continue;
		}

		tmp = cur->next;
		xmlUnlinkNode(cur);
		xmlFreeNode(cur);
		cur = tmp;
	}

	(void) zonecfg_endent(handle);
	return (Z_OK);
}

static boolean_t
valid_uint(char *s, uint64_t *n)
{
	char *endp;

	/* strtoull accepts '-'?! so we want to flag that as an error */
	if (strchr(s, '-') != NULL)
		return (B_FALSE);

	errno = 0;
	*n = strtoull(s, &endp, 10);

	if (errno != 0 || *endp != '\0')
		return (B_FALSE);
	return (B_TRUE);
}

/*
 * Convert a string representing a number (possibly a fraction) into an integer.
 * The string can have a modifier (K, M, G or T).   The modifiers are treated
 * as powers of two (not 10).
 */
int
zonecfg_str_to_bytes(char *str, uint64_t *bytes)
{
	long double val;
	char *unitp;
	uint64_t scale;

	if ((val = strtold(str, &unitp)) < 0)
		return (-1);

	/* remove any leading white space from units string */
	while (isspace(*unitp) != 0)
		++unitp;

	/* if no units explicitly set, error */
	if (unitp == NULL || *unitp == '\0') {
		scale = 1;
	} else {
		int i;
		char *units[] = {"K", "M", "G", "T", NULL};

		scale = 1024;

		/* update scale based on units */
		for (i = 0; units[i] != NULL; i++) {
			if (strcasecmp(unitp, units[i]) == 0)
				break;
			scale <<= 10;
		}

		if (units[i] == NULL)
			return (-1);
	}

	*bytes = (uint64_t)(val * scale);
	return (0);
}

boolean_t
zonecfg_valid_ncpus(char *lowstr, char *highstr)
{
	uint64_t low, high;

	if (!valid_uint(lowstr, &low) || !valid_uint(highstr, &high) ||
	    low < 1 || low > high)
		return (B_FALSE);

	return (B_TRUE);
}

boolean_t
zonecfg_valid_importance(char *impstr)
{
	uint64_t num;

	if (!valid_uint(impstr, &num))
		return (B_FALSE);

	return (B_TRUE);
}

boolean_t
zonecfg_valid_alias_limit(char *name, char *limitstr, uint64_t *limit)
{
	int i;

	for (i = 0; aliases[i].shortname != NULL; i++)
		if (strcmp(name, aliases[i].shortname) == 0)
			break;

	if (aliases[i].shortname == NULL)
		return (B_FALSE);

	if (!valid_uint(limitstr, limit) || *limit < aliases[i].low_limit)
		return (B_FALSE);

	return (B_TRUE);
}

boolean_t
zonecfg_valid_memlimit(char *memstr, uint64_t *mem_val)
{
	if (zonecfg_str_to_bytes(memstr, mem_val) != 0)
		return (B_FALSE);

	return (B_TRUE);
}

static int
zerr_pool(char *pool_err, int err_size, int res)
{
	(void) strlcpy(pool_err, pool_strerror(pool_error()), err_size);
	return (res);
}

static int
create_tmp_pset(char *pool_err, int err_size, pool_conf_t *pconf, pool_t *pool,
    char *name, int min, int max)
{
	pool_resource_t *res;
	pool_elem_t *elem;
	pool_value_t *val;

	if ((res = pool_resource_create(pconf, "pset", name)) == NULL)
		return (zerr_pool(pool_err, err_size, Z_POOL));

	if (pool_associate(pconf, pool, res) != PO_SUCCESS)
		return (zerr_pool(pool_err, err_size, Z_POOL));

	if ((elem = pool_resource_to_elem(pconf, res)) == NULL)
		return (zerr_pool(pool_err, err_size, Z_POOL));

	if ((val = pool_value_alloc()) == NULL)
		return (zerr_pool(pool_err, err_size, Z_POOL));

	/* set the maximum number of cpus for the pset */
	pool_value_set_uint64(val, (uint64_t)max);

	if (pool_put_property(pconf, elem, "pset.max", val) != PO_SUCCESS) {
		pool_value_free(val);
		return (zerr_pool(pool_err, err_size, Z_POOL));
	}

	/* set the minimum number of cpus for the pset */
	pool_value_set_uint64(val, (uint64_t)min);

	if (pool_put_property(pconf, elem, "pset.min", val) != PO_SUCCESS) {
		pool_value_free(val);
		return (zerr_pool(pool_err, err_size, Z_POOL));
	}

	pool_value_free(val);

	return (Z_OK);
}

static int
create_tmp_pool(char *pool_err, int err_size, pool_conf_t *pconf, char *name,
    struct zone_psettab *pset_tab)
{
	pool_t *pool;
	int res = Z_OK;

	/* create a temporary pool configuration */
	if (pool_conf_open(pconf, NULL, PO_TEMP) != PO_SUCCESS) {
		res = zerr_pool(pool_err, err_size, Z_POOL);
		return (res);
	}

	if ((pool = pool_create(pconf, name)) == NULL) {
		res = zerr_pool(pool_err, err_size, Z_POOL_CREATE);
		goto done;
	}

	/* set pool importance */
	if (pset_tab->zone_importance[0] != '\0') {
		pool_elem_t *elem;
		pool_value_t *val;

		if ((elem = pool_to_elem(pconf, pool)) == NULL) {
			res = zerr_pool(pool_err, err_size, Z_POOL);
			goto done;
		}

		if ((val = pool_value_alloc()) == NULL) {
			res = zerr_pool(pool_err, err_size, Z_POOL);
			goto done;
		}

		pool_value_set_int64(val,
		    (int64_t)atoi(pset_tab->zone_importance));

		if (pool_put_property(pconf, elem, "pool.importance", val)
		    != PO_SUCCESS) {
			res = zerr_pool(pool_err, err_size, Z_POOL);
			pool_value_free(val);
			goto done;
		}

		pool_value_free(val);
	}

	if ((res = create_tmp_pset(pool_err, err_size, pconf, pool, name,
	    atoi(pset_tab->zone_ncpu_min),
	    atoi(pset_tab->zone_ncpu_max))) != Z_OK)
		goto done;

	/* validation */
	if (pool_conf_status(pconf) == POF_INVALID) {
		res = zerr_pool(pool_err, err_size, Z_POOL);
		goto done;
	}

	/*
	 * This validation is the one we expect to fail if the user specified
	 * an invalid configuration (too many cpus) for this system.
	 */
	if (pool_conf_validate(pconf, POV_RUNTIME) != PO_SUCCESS) {
		res = zerr_pool(pool_err, err_size, Z_POOL_CREATE);
		goto done;
	}

	/*
	 * Commit the dynamic configuration but not the pool configuration
	 * file.
	 */
	if (pool_conf_commit(pconf, 1) != PO_SUCCESS)
		res = zerr_pool(pool_err, err_size, Z_POOL);

done:
	(void) pool_conf_close(pconf);
	return (res);
}

static int
get_running_tmp_pset(pool_conf_t *pconf, pool_t *pool, pool_resource_t *pset,
    struct zone_psettab *pset_tab)
{
	int nfound = 0;
	pool_elem_t *pe;
	pool_value_t *pv = pool_value_alloc();
	uint64_t val_uint;

	if (pool != NULL) {
		pe = pool_to_elem(pconf, pool);
		if (pool_get_property(pconf, pe, "pool.importance", pv)
		    != POC_INVAL) {
			int64_t val_int;

			(void) pool_value_get_int64(pv, &val_int);
			(void) snprintf(pset_tab->zone_importance,
			    sizeof (pset_tab->zone_importance), "%d", val_int);
			nfound++;
		}
	}

	if (pset != NULL) {
		pe = pool_resource_to_elem(pconf, pset);
		if (pool_get_property(pconf, pe, "pset.min", pv) != POC_INVAL) {
			(void) pool_value_get_uint64(pv, &val_uint);
			(void) snprintf(pset_tab->zone_ncpu_min,
			    sizeof (pset_tab->zone_ncpu_min), "%u", val_uint);
			nfound++;
		}

		if (pool_get_property(pconf, pe, "pset.max", pv) != POC_INVAL) {
			(void) pool_value_get_uint64(pv, &val_uint);
			(void) snprintf(pset_tab->zone_ncpu_max,
			    sizeof (pset_tab->zone_ncpu_max), "%u", val_uint);
			nfound++;
		}
	}

	pool_value_free(pv);

	if (nfound == 3)
		return (PO_SUCCESS);

	return (PO_FAIL);
}

/*
 * Determine if a tmp pool is configured and if so, if the configuration is
 * still valid or if it has been changed since the tmp pool was created.
 * If the tmp pool configuration is no longer valid, delete the tmp pool.
 *
 * Set *valid=B_TRUE if there is an existing, valid tmp pool configuration.
 */
static int
verify_del_tmp_pool(pool_conf_t *pconf, char *tmp_name, char *pool_err,
    int err_size, struct zone_psettab *pset_tab, boolean_t *exists)
{
	int res = Z_OK;
	pool_t *pool;
	pool_resource_t *pset;
	struct zone_psettab pset_current;

	*exists = B_FALSE;

	if (pool_conf_open(pconf, pool_dynamic_location(), PO_RDWR)
	    != PO_SUCCESS) {
		res = zerr_pool(pool_err, err_size, Z_POOL);
		return (res);
	}

	pool = pool_get_pool(pconf, tmp_name);
	pset = pool_get_resource(pconf, "pset", tmp_name);

	if (pool == NULL && pset == NULL) {
		/* no tmp pool configured */
		goto done;
	}

	/*
	 * If an existing tmp pool for this zone is configured with the proper
	 * settings, then the tmp pool is valid.
	 */
	if (get_running_tmp_pset(pconf, pool, pset, &pset_current)
	    == PO_SUCCESS &&
	    strcmp(pset_tab->zone_ncpu_min,
	    pset_current.zone_ncpu_min) == 0 &&
	    strcmp(pset_tab->zone_ncpu_max,
	    pset_current.zone_ncpu_max) == 0 &&
	    strcmp(pset_tab->zone_importance,
	    pset_current.zone_importance) == 0) {
		*exists = B_TRUE;

	} else {
		/*
		 * An out-of-date tmp pool configuration exists.  Delete it
		 * so that we can create the correct tmp pool config.
		 */
		if (pset != NULL &&
		    pool_resource_destroy(pconf, pset) != PO_SUCCESS) {
			res = zerr_pool(pool_err, err_size, Z_POOL);
			goto done;
		}

		if (pool != NULL &&
		    pool_destroy(pconf, pool) != PO_SUCCESS) {
			res = zerr_pool(pool_err, err_size, Z_POOL);
			goto done;
		}

		/* commit dynamic config */
		if (pool_conf_commit(pconf, 0) != PO_SUCCESS)
			res = zerr_pool(pool_err, err_size, Z_POOL);
	}

done:
	(void) pool_conf_close(pconf);

	return (res);
}

/*
 * Destroy any existing tmp pool.
 */
int
zonecfg_destroy_tmp_pool(char *zone_name, char *pool_err, int err_size)
{
	int status;
	int res = Z_OK;
	pool_conf_t *pconf;
	pool_t *pool;
	pool_resource_t *pset;
	char tmp_name[MAX_TMP_POOL_NAME];

	/* if pools not enabled then nothing to do */
	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED)
		return (Z_OK);

	if ((pconf = pool_conf_alloc()) == NULL)
		return (zerr_pool(pool_err, err_size, Z_POOL));

	(void) snprintf(tmp_name, sizeof (tmp_name), TMP_POOL_NAME, zone_name);

	if (pool_conf_open(pconf, pool_dynamic_location(), PO_RDWR)
	    != PO_SUCCESS) {
		res = zerr_pool(pool_err, err_size, Z_POOL);
		pool_conf_free(pconf);
		return (res);
	}

	pool = pool_get_pool(pconf, tmp_name);
	pset = pool_get_resource(pconf, "pset", tmp_name);

	if (pool == NULL && pset == NULL) {
		/* nothing to destroy, we're done */
		goto done;
	}

	if (pset != NULL && pool_resource_destroy(pconf, pset) != PO_SUCCESS) {
		res = zerr_pool(pool_err, err_size, Z_POOL);
		goto done;
	}

	if (pool != NULL && pool_destroy(pconf, pool) != PO_SUCCESS) {
		res = zerr_pool(pool_err, err_size, Z_POOL);
		goto done;
	}

	/* commit dynamic config */
	if (pool_conf_commit(pconf, 0) != PO_SUCCESS)
		res = zerr_pool(pool_err, err_size, Z_POOL);

done:
	(void) pool_conf_close(pconf);
	pool_conf_free(pconf);

	return (res);
}

/*
 * Attempt to bind to a tmp pool for this zone.  If there is no tmp pool
 * configured, we just return Z_OK.
 *
 * We either attempt to create the tmp pool for this zone or rebind to an
 * existing tmp pool for this zone.
 *
 * Rebinding is used when a zone with a tmp pool reboots so that we don't have
 * to recreate the tmp pool.  To do this we need to be sure we work correctly
 * for the following cases:
 *
 *	- there is an existing, properly configured tmp pool.
 *	- zonecfg added tmp pool after zone was booted, must now create.
 *	- zonecfg updated tmp pool config after zone was booted, in this case
 *	  we destroy the old tmp pool and create a new one.
 */
int
zonecfg_bind_tmp_pool(zone_dochandle_t handle, zoneid_t zoneid, char *pool_err,
    int err_size)
{
	struct zone_psettab pset_tab;
	int err;
	int status;
	pool_conf_t *pconf;
	boolean_t exists;
	char zone_name[ZONENAME_MAX];
	char tmp_name[MAX_TMP_POOL_NAME];

	(void) getzonenamebyid(zoneid, zone_name, sizeof (zone_name));

	err = zonecfg_lookup_pset(handle, &pset_tab);

	/* if no temporary pool configured, we're done */
	if (err == Z_NO_ENTRY)
		return (Z_OK);

	/*
	 * importance might not have a value but we need to validate it here,
	 * so set the default.
	 */
	if (pset_tab.zone_importance[0] == '\0')
		(void) strlcpy(pset_tab.zone_importance, "1",
		    sizeof (pset_tab.zone_importance));

	/* if pools not enabled, enable them now */
	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
		if (pool_set_status(POOL_ENABLED) != PO_SUCCESS)
			return (Z_POOL_ENABLE);
	}

	if ((pconf = pool_conf_alloc()) == NULL)
		return (zerr_pool(pool_err, err_size, Z_POOL));

	(void) snprintf(tmp_name, sizeof (tmp_name), TMP_POOL_NAME, zone_name);

	/*
	 * Check if a valid tmp pool/pset already exists.  If so, we just
	 * reuse it.
	 */
	if ((err = verify_del_tmp_pool(pconf, tmp_name, pool_err, err_size,
	    &pset_tab, &exists)) != Z_OK) {
		pool_conf_free(pconf);
		return (err);
	}

	if (!exists)
		err = create_tmp_pool(pool_err, err_size, pconf, tmp_name,
		    &pset_tab);

	pool_conf_free(pconf);

	if (err != Z_OK)
		return (err);

	/* Bind the zone to the pool. */
	if (pool_set_binding(tmp_name, P_ZONEID, zoneid) != PO_SUCCESS)
		return (zerr_pool(pool_err, err_size, Z_POOL_BIND));

	return (Z_OK);
}

/*
 * Attempt to bind to a permanent pool for this zone.  If there is no
 * permanent pool configured, we just return Z_OK.
 */
int
zonecfg_bind_pool(zone_dochandle_t handle, zoneid_t zoneid, char *pool_err,
    int err_size)
{
	pool_conf_t *poolconf;
	pool_t *pool;
	char poolname[MAXPATHLEN];
	int status;
	int error;

	/*
	 * Find the pool mentioned in the zone configuration, and bind to it.
	 */
	error = zonecfg_get_pool(handle, poolname, sizeof (poolname));
	if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
		/*
		 * The property is not set on the zone, so the pool
		 * should be bound to the default pool.  But that's
		 * already done by the kernel, so we can just return.
		 */
		return (Z_OK);
	}
	if (error != Z_OK) {
		/*
		 * Not an error, even though it shouldn't be happening.
		 */
		return (Z_OK);
	}
	/*
	 * Don't do anything if pools aren't enabled.
	 */
	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED)
		return (Z_POOLS_NOT_ACTIVE);

	/*
	 * Try to provide a sane error message if the requested pool doesn't
	 * exist.
	 */
	if ((poolconf = pool_conf_alloc()) == NULL)
		return (zerr_pool(pool_err, err_size, Z_POOL));

	if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
	    PO_SUCCESS) {
		pool_conf_free(poolconf);
		return (zerr_pool(pool_err, err_size, Z_POOL));
	}
	pool = pool_get_pool(poolconf, poolname);
	(void) pool_conf_close(poolconf);
	pool_conf_free(poolconf);
	if (pool == NULL)
		return (Z_NO_POOL);

	/*
	 * Bind the zone to the pool.
	 */
	if (pool_set_binding(poolname, P_ZONEID, zoneid) != PO_SUCCESS) {
		/* if bind fails, return poolname for the error msg */
		(void) strlcpy(pool_err, poolname, err_size);
		return (Z_POOL_BIND);
	}

	return (Z_OK);
}

int
zonecfg_get_poolname(zone_dochandle_t handle, char *zone, char *pool,
    size_t poolsize)
{
	int err;
	struct zone_psettab pset_tab;

	err = zonecfg_lookup_pset(handle, &pset_tab);
	if ((err != Z_NO_ENTRY) && (err != Z_OK))
		return (err);

	/* pset was found so a temporary pool was created */
	if (err == Z_OK) {
		(void) snprintf(pool, poolsize, TMP_POOL_NAME, zone);
		return (Z_OK);
	}

	/* lookup the poolname in zonecfg */
	return (zonecfg_get_pool(handle, pool, poolsize));
}

static boolean_t
svc_enabled(char *svc_name)
{
	scf_simple_prop_t	*prop;
	boolean_t		found = B_FALSE;

	prop = scf_simple_prop_get(NULL, svc_name, SCF_PG_GENERAL,
	    SCF_PROPERTY_ENABLED);

	if (scf_simple_prop_numvalues(prop) == 1 &&
	    *scf_simple_prop_next_boolean(prop) != 0)
		found = B_TRUE;

	scf_simple_prop_free(prop);

	return (found);
}

/*
 * If the zone has capped-memory, make sure the rcap service is enabled.
 */
int
zonecfg_enable_rcapd(char *err, int size)
{
	if (!svc_enabled(RCAP_SERVICE) &&
	    smf_enable_instance(RCAP_SERVICE, 0) == -1) {
		(void) strlcpy(err, scf_strerror(scf_error()), size);
		return (Z_SYSTEM);
	}

	return (Z_OK);
}

/*
 * Return true if pset has cpu range specified and poold is not enabled.
 */
boolean_t
zonecfg_warn_poold(zone_dochandle_t handle)
{
	struct zone_psettab pset_tab;
	int min, max;
	int err;

	err = zonecfg_lookup_pset(handle, &pset_tab);

	/* if no temporary pool configured, we're done */
	if (err == Z_NO_ENTRY)
		return (B_FALSE);

	min = atoi(pset_tab.zone_ncpu_min);
	max = atoi(pset_tab.zone_ncpu_max);

	/* range not specified, no need for poold */
	if (min == max)
		return (B_FALSE);

	/* we have a range, check if poold service is enabled */
	if (svc_enabled(POOLD_SERVICE))
		return (B_FALSE);

	return (B_TRUE);
}

/*
 * Retrieve the specified pool's thread scheduling class.  'poolname' must
 * refer to the name of a configured resource pool.  The thread scheduling
 * class specified by the pool will be stored in the buffer to which 'class'
 * points.  'clsize' is the byte size of the buffer to which 'class' points.
 *
 * This function returns Z_OK if it successfully stored the specified pool's
 * thread scheduling class into the buffer to which 'class' points.  It returns
 * Z_NO_POOL if resource pools are not enabled, the function is unable to
 * access the system's resource pools configuration, or the specified pool
 * does not exist.  The function returns Z_TOO_BIG if the buffer to which
 * 'class' points is not large enough to contain the thread scheduling class'
 * name.  The function returns Z_NO_ENTRY if the pool does not specify a thread
 * scheduling class.
 */
static int
get_pool_sched_class(char *poolname, char *class, int clsize)
{
	int status;
	pool_conf_t *poolconf;
	pool_t *pool;
	pool_elem_t *pe;
	pool_value_t *pv = pool_value_alloc();
	const char *sched_str;

	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED)
		return (Z_NO_POOL);

	if ((poolconf = pool_conf_alloc()) == NULL)
		return (Z_NO_POOL);

	if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
	    PO_SUCCESS) {
		pool_conf_free(poolconf);
		return (Z_NO_POOL);
	}

	if ((pool = pool_get_pool(poolconf, poolname)) == NULL) {
		(void) pool_conf_close(poolconf);
		pool_conf_free(poolconf);
		return (Z_NO_POOL);
	}

	pe = pool_to_elem(poolconf, pool);
	if (pool_get_property(poolconf, pe, "pool.scheduler", pv) !=
	    POC_STRING) {
		(void) pool_conf_close(poolconf);
		pool_conf_free(poolconf);
		return (Z_NO_ENTRY);
	}
	(void) pool_value_get_string(pv, &sched_str);
	(void) pool_conf_close(poolconf);
	pool_conf_free(poolconf);
	if (strlcpy(class, sched_str, clsize) >= clsize)
		return (Z_TOO_BIG);
	return (Z_OK);
}

/*
 * Get the default scheduling class for the zone.  This will either be the
 * class set on the zone's pool or the system default scheduling class.
 */
int
zonecfg_get_dflt_sched_class(zone_dochandle_t handle, char *class, int clsize)
{
	char poolname[MAXPATHLEN];

	if (zonecfg_get_pool(handle, poolname, sizeof (poolname)) == Z_OK) {
		/* check if the zone's pool specified a sched class */
		if (get_pool_sched_class(poolname, class, clsize) == Z_OK)
			return (Z_OK);
	}

	if (priocntl(0, 0, PC_GETDFLCL, class, (uint64_t)clsize) == -1)
		return (Z_TOO_BIG);

	return (Z_OK);
}

int
zonecfg_setfsent(zone_dochandle_t handle)
{
	return (zonecfg_setent(handle));
}

int
zonecfg_getfsent(zone_dochandle_t handle, struct zone_fstab *tabptr)
{
	xmlNodePtr cur, options;
	char options_str[MAX_MNTOPT_STR];
	int err;

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

	if ((cur = handle->zone_dh_cur) == NULL)
		return (Z_NO_ENTRY);

	for (; cur != NULL; cur = cur->next)
		if (!xmlStrcmp(cur->name, DTD_ELEM_FS))
			break;
	if (cur == NULL) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (Z_NO_ENTRY);
	}

	if ((err = fetchprop(cur, DTD_ATTR_SPECIAL, tabptr->zone_fs_special,
	    sizeof (tabptr->zone_fs_special))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	if ((err = fetchprop(cur, DTD_ATTR_RAW, tabptr->zone_fs_raw,
	    sizeof (tabptr->zone_fs_raw))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	if ((err = fetchprop(cur, DTD_ATTR_DIR, tabptr->zone_fs_dir,
	    sizeof (tabptr->zone_fs_dir))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	if ((err = fetchprop(cur, DTD_ATTR_TYPE, tabptr->zone_fs_type,
	    sizeof (tabptr->zone_fs_type))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	/* OK for options to be NULL */
	tabptr->zone_fs_options = NULL;
	for (options = cur->xmlChildrenNode; options != NULL;
	    options = options->next) {
		if (fetchprop(options, DTD_ATTR_NAME, options_str,
		    sizeof (options_str)) != Z_OK)
			break;
		if (zonecfg_add_fs_option(tabptr, options_str) != Z_OK)
			break;
	}

	handle->zone_dh_cur = cur->next;
	return (Z_OK);
}

int
zonecfg_endfsent(zone_dochandle_t handle)
{
	return (zonecfg_endent(handle));
}

int
zonecfg_setnwifent(zone_dochandle_t handle)
{
	return (zonecfg_setent(handle));
}

int
zonecfg_getnwifent(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
{
	xmlNodePtr cur;
	int err;

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

	if ((cur = handle->zone_dh_cur) == NULL)
		return (Z_NO_ENTRY);

	for (; cur != NULL; cur = cur->next)
		if (!xmlStrcmp(cur->name, DTD_ELEM_NET))
			break;
	if (cur == NULL) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (Z_NO_ENTRY);
	}

	if ((err = fetchprop(cur, DTD_ATTR_ADDRESS, tabptr->zone_nwif_address,
	    sizeof (tabptr->zone_nwif_address))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	if ((err = fetchprop(cur, DTD_ATTR_ALLOWED_ADDRESS,
	    tabptr->zone_nwif_allowed_address,
	    sizeof (tabptr->zone_nwif_allowed_address))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	if ((err = fetchprop(cur, DTD_ATTR_PHYSICAL, tabptr->zone_nwif_physical,
	    sizeof (tabptr->zone_nwif_physical))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	if ((err = fetchprop(cur, DTD_ATTR_DEFROUTER,
	    tabptr->zone_nwif_defrouter,
	    sizeof (tabptr->zone_nwif_defrouter))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	handle->zone_dh_cur = cur->next;
	return (Z_OK);
}

int
zonecfg_endnwifent(zone_dochandle_t handle)
{
	return (zonecfg_endent(handle));
}

int
zonecfg_setdevent(zone_dochandle_t handle)
{
	return (zonecfg_setent(handle));
}

int
zonecfg_getdevent(zone_dochandle_t handle, struct zone_devtab *tabptr)
{
	xmlNodePtr cur;
	int err;

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

	if ((cur = handle->zone_dh_cur) == NULL)
		return (Z_NO_ENTRY);

	for (; cur != NULL; cur = cur->next)
		if (!xmlStrcmp(cur->name, DTD_ELEM_DEVICE))
			break;
	if (cur == NULL) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (Z_NO_ENTRY);
	}

	if ((err = fetchprop(cur, DTD_ATTR_MATCH, tabptr->zone_dev_match,
	    sizeof (tabptr->zone_dev_match))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	handle->zone_dh_cur = cur->next;
	return (Z_OK);
}

int
zonecfg_enddevent(zone_dochandle_t handle)
{
	return (zonecfg_endent(handle));
}

int
zonecfg_setrctlent(zone_dochandle_t handle)
{
	return (zonecfg_setent(handle));
}

int
zonecfg_getrctlent(zone_dochandle_t handle, struct zone_rctltab *tabptr)
{
	xmlNodePtr cur, val;
	struct zone_rctlvaltab *valptr;
	int err;

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

	if ((cur = handle->zone_dh_cur) == NULL)
		return (Z_NO_ENTRY);

	for (; cur != NULL; cur = cur->next)
		if (!xmlStrcmp(cur->name, DTD_ELEM_RCTL))
			break;
	if (cur == NULL) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (Z_NO_ENTRY);
	}

	if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_rctl_name,
	    sizeof (tabptr->zone_rctl_name))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	tabptr->zone_rctl_valptr = NULL;
	for (val = cur->xmlChildrenNode; val != NULL; val = val->next) {
		valptr = (struct zone_rctlvaltab *)malloc(
		    sizeof (struct zone_rctlvaltab));
		if (valptr == NULL)
			return (Z_NOMEM);
		if (fetchprop(val, DTD_ATTR_PRIV, valptr->zone_rctlval_priv,
		    sizeof (valptr->zone_rctlval_priv)) != Z_OK)
			break;
		if (fetchprop(val, DTD_ATTR_LIMIT, valptr->zone_rctlval_limit,
		    sizeof (valptr->zone_rctlval_limit)) != Z_OK)
			break;
		if (fetchprop(val, DTD_ATTR_ACTION, valptr->zone_rctlval_action,
		    sizeof (valptr->zone_rctlval_action)) != Z_OK)
			break;
		if (zonecfg_add_rctl_value(tabptr, valptr) != Z_OK)
			break;
	}

	handle->zone_dh_cur = cur->next;
	return (Z_OK);
}

int
zonecfg_endrctlent(zone_dochandle_t handle)
{
	return (zonecfg_endent(handle));
}

int
zonecfg_setattrent(zone_dochandle_t handle)
{
	return (zonecfg_setent(handle));
}

int
zonecfg_getattrent(zone_dochandle_t handle, struct zone_attrtab *tabptr)
{
	xmlNodePtr cur;
	int err;

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

	if ((cur = handle->zone_dh_cur) == NULL)
		return (Z_NO_ENTRY);

	for (; cur != NULL; cur = cur->next)
		if (!xmlStrcmp(cur->name, DTD_ELEM_ATTR))
			break;
	if (cur == NULL) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (Z_NO_ENTRY);
	}

	if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_attr_name,
	    sizeof (tabptr->zone_attr_name))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	if ((err = fetchprop(cur, DTD_ATTR_TYPE, tabptr->zone_attr_type,
	    sizeof (tabptr->zone_attr_type))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	if ((err = fetchprop(cur, DTD_ATTR_VALUE, tabptr->zone_attr_value,
	    sizeof (tabptr->zone_attr_value))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	handle->zone_dh_cur = cur->next;
	return (Z_OK);
}

int
zonecfg_endattrent(zone_dochandle_t handle)
{
	return (zonecfg_endent(handle));
}

int
zonecfg_setadminent(zone_dochandle_t handle)
{
	return (zonecfg_setent(handle));
}

int
zonecfg_getadminent(zone_dochandle_t handle, struct zone_admintab *tabptr)
{
	xmlNodePtr cur;
	int err;

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

	if ((cur = handle->zone_dh_cur) == NULL)
		return (Z_NO_ENTRY);

	for (; cur != NULL; cur = cur->next)
		if (!xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
			break;
	if (cur == NULL) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (Z_NO_ENTRY);
	}

	if ((err = fetchprop(cur, DTD_ATTR_USER, tabptr->zone_admin_user,
	    sizeof (tabptr->zone_admin_user))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}


	if ((err = fetchprop(cur, DTD_ATTR_AUTHS, tabptr->zone_admin_auths,
	    sizeof (tabptr->zone_admin_auths))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	handle->zone_dh_cur = cur->next;
	return (Z_OK);
}

int
zonecfg_endadminent(zone_dochandle_t handle)
{
	return (zonecfg_endent(handle));
}

/*
 * The privileges available on the system and described in privileges(7)
 * fall into four categories with respect to non-global zones:
 *
 *      Default set of privileges considered safe for all non-global
 *      zones.  These privileges are "safe" in the sense that a
 *      privileged process in the zone cannot affect processes in any
 *      other zone on the system.
 *
 *      Set of privileges not currently permitted within a non-global
 *      zone.  These privileges are considered by default, "unsafe,"
 *      and include ones which affect global resources (such as the
 *      system clock or physical memory) or are overly broad and cover
 *      more than one mechanism in the system.  In other cases, there
 *      has not been sufficient virtualization in the parts of the
 *      system the privilege covers to allow its use within a
 *      non-global zone.
 *
 *      Set of privileges required in order to get a zone booted and
 *      init(8) started.  These cannot be removed from the zone's
 *      privilege set.
 *
 * All other privileges are optional and are potentially useful for
 * processes executing inside a non-global zone.
 *
 * When privileges are added to the system, a determination needs to be
 * made as to which category the privilege belongs to.  Ideally,
 * privileges should be fine-grained enough and the mechanisms they cover
 * virtualized enough so that they can be made available to non-global
 * zones.
 */

/*
 * Define some of the tokens that priv_str_to_set(3C) recognizes.  Since
 * the privilege string separator can be any character, although it is
 * usually a comma character, define these here as well in the event that
 * they change or are augmented in the future.
 */
#define	BASIC_TOKEN		"basic"
#define	DEFAULT_TOKEN		"default"
#define	ZONE_TOKEN		"zone"
#define	TOKEN_PRIV_CHAR		','
#define	TOKEN_PRIV_STR		","

typedef struct priv_node {
	struct priv_node	*pn_next;	/* Next privilege */
	char			*pn_priv;	/* Privileges name */
} priv_node_t;

/* Privileges lists can differ across brands */
typedef struct priv_lists {
	/* Privileges considered safe for all non-global zones of a brand */
	struct priv_node	*pl_default;

	/* Privileges not permitted for all non-global zones of a brand */
	struct priv_node	*pl_prohibited;

	/* Privileges required for all non-global zones of a brand */
	struct priv_node	*pl_required;

	/*
	 * ip-type of the zone these privileges lists apply to.
	 * It is used to pass ip-type to the callback function,
	 * priv_lists_cb, which has no way of getting the ip-type.
	 */
	const char		*pl_iptype;
} priv_lists_t;

static int
priv_lists_cb(void *data, priv_iter_t *priv_iter)
{
	priv_lists_t *plp = (priv_lists_t *)data;
	priv_node_t *pnp;

	/* Skip this privilege if ip-type does not match */
	if ((strcmp(priv_iter->pi_iptype, "all") != 0) &&
	    (strcmp(priv_iter->pi_iptype, plp->pl_iptype) != 0))
		return (0);

	/* Allocate a new priv list node. */
	if ((pnp = malloc(sizeof (*pnp))) == NULL)
		return (-1);
	if ((pnp->pn_priv = strdup(priv_iter->pi_name)) == NULL) {
		free(pnp);
		return (-1);
	}

	/* Insert the new priv list node into the right list */
	if (strcmp(priv_iter->pi_set, "default") == 0) {
		pnp->pn_next = plp->pl_default;
		plp->pl_default = pnp;
	} else if (strcmp(priv_iter->pi_set, "prohibited") == 0) {
		pnp->pn_next = plp->pl_prohibited;
		plp->pl_prohibited = pnp;
	} else if (strcmp(priv_iter->pi_set, "required") == 0) {
		pnp->pn_next = plp->pl_required;
		plp->pl_required = pnp;
	} else {
		free(pnp->pn_priv);
		free(pnp);
		return (-1);
	}
	return (0);
}

static void
priv_lists_destroy(priv_lists_t *plp)
{
	priv_node_t *pnp;

	assert(plp != NULL);

	while ((pnp = plp->pl_default) != NULL) {
		plp->pl_default = pnp->pn_next;
		free(pnp->pn_priv);
		free(pnp);
	}
	while ((pnp = plp->pl_prohibited) != NULL) {
		plp->pl_prohibited = pnp->pn_next;
		free(pnp->pn_priv);
		free(pnp);
	}
	while ((pnp = plp->pl_required) != NULL) {
		plp->pl_required = pnp->pn_next;
		free(pnp->pn_priv);
		free(pnp);
	}
	free(plp);
}

static int
priv_lists_create(zone_dochandle_t handle, char *brand, priv_lists_t **plpp,
    const char *curr_iptype)
{
	priv_lists_t *plp;
	brand_handle_t bh;
	char brand_str[MAXNAMELEN];

	/* handle or brand must be set, but never both */
	assert((handle != NULL) || (brand != NULL));
	assert((handle == NULL) || (brand == NULL));

	if (handle != NULL) {
		brand = brand_str;
		if (zonecfg_get_brand(handle, brand, sizeof (brand_str)) != 0)
			return (Z_BRAND_ERROR);
	}

	if ((bh = brand_open(brand)) == NULL)
		return (Z_BRAND_ERROR);

	if ((plp = calloc(1, sizeof (priv_lists_t))) == NULL) {
		brand_close(bh);
		return (Z_NOMEM);
	}

	plp->pl_iptype = curr_iptype;

	/* construct the privilege lists */
	if (brand_config_iter_privilege(bh, priv_lists_cb, plp) != 0) {
		priv_lists_destroy(plp);
		brand_close(bh);
		return (Z_BRAND_ERROR);
	}

	brand_close(bh);
	*plpp = plp;
	return (Z_OK);
}

static int
get_default_privset(priv_set_t *privs, priv_lists_t *plp)
{
	priv_node_t *pnp;
	priv_set_t *basic;

	basic = priv_str_to_set(BASIC_TOKEN, TOKEN_PRIV_STR, NULL);
	if (basic == NULL)
		return (errno == ENOMEM ? Z_NOMEM : Z_INVAL);

	priv_union(basic, privs);
	priv_freeset(basic);

	for (pnp = plp->pl_default; pnp != NULL; pnp = pnp->pn_next) {
		if (priv_addset(privs, pnp->pn_priv) != 0)
			return (Z_INVAL);
	}

	return (Z_OK);
}

int
zonecfg_default_brand(char *brand, size_t brandsize)
{
	zone_dochandle_t handle;
	int myzoneid = getzoneid();
	int ret;

	/*
	 * If we're running within a zone, then the default brand is the
	 * current zone's brand.
	 */
	if (myzoneid != GLOBAL_ZONEID) {
		ret = zone_getattr(myzoneid, ZONE_ATTR_BRAND, brand, brandsize);
		if (ret < 0)
			return ((errno == EFAULT) ? Z_TOO_BIG : Z_INVAL);
		return (Z_OK);
	}

	if ((handle = zonecfg_init_handle()) == NULL)
		return (Z_NOMEM);
	if ((ret = zonecfg_get_handle("SUNWdefault", handle)) == Z_OK) {
		ret = i_zonecfg_get_brand(handle, brand, brandsize, B_TRUE);
		zonecfg_fini_handle(handle);
		return (ret);
	}
	return (ret);
}

int
zonecfg_default_privset(priv_set_t *privs, const char *curr_iptype)
{
	priv_lists_t *plp;
	char buf[MAXNAMELEN];
	int ret;

	if ((ret = zonecfg_default_brand(buf, sizeof (buf))) != Z_OK)
		return (ret);
	if ((ret = priv_lists_create(NULL, buf, &plp, curr_iptype)) != Z_OK)
		return (ret);
	ret = get_default_privset(privs, plp);
	priv_lists_destroy(plp);
	return (ret);
}

void
append_priv_token(char *priv, char *str, size_t strlen)
{
	if (*str != '\0')
		(void) strlcat(str, TOKEN_PRIV_STR, strlen);
	(void) strlcat(str, priv, strlen);
}

/*
 * Verify that the supplied string is a valid privilege limit set for a
 * non-global zone.  This string must not only be acceptable to
 * priv_str_to_set(3C) which parses it, but it also must resolve to a
 * privilege set that includes certain required privileges and lacks
 * certain prohibited privileges.
 */
static int
verify_privset(char *privbuf, priv_set_t *privs, char **privname,
    boolean_t add_default, priv_lists_t *plp)
{
	priv_node_t *pnp;
	char *tmp, *cp, *lasts;
	size_t len;
	priv_set_t *mergeset;
	const char *token;

	/*
	 * The verification of the privilege string occurs in several
	 * phases.  In the first phase, the supplied string is scanned for
	 * the ZONE_TOKEN token which is not support as part of the
	 * "limitpriv" property.
	 *
	 * Duplicate the supplied privilege string since strtok_r(3C)
	 * tokenizes its input by null-terminating the tokens.
	 */
	if ((tmp = strdup(privbuf)) == NULL)
		return (Z_NOMEM);
	for (cp = strtok_r(tmp, TOKEN_PRIV_STR, &lasts); cp != NULL;
	    cp = strtok_r(NULL, TOKEN_PRIV_STR, &lasts)) {
		if (strcmp(cp, ZONE_TOKEN) == 0) {
			free(tmp);
			if ((*privname = strdup(ZONE_TOKEN)) == NULL)
				return (Z_NOMEM);
			else
				return (Z_PRIV_UNKNOWN);
		}
	}
	free(tmp);

	if (add_default) {
		/*
		 * If DEFAULT_TOKEN was specified, a string needs to be
		 * built containing the privileges from the default, safe
		 * set along with those of the "limitpriv" property.
		 */
		len = strlen(privbuf) + sizeof (BASIC_TOKEN) + 2;

		for (pnp = plp->pl_default; pnp != NULL; pnp = pnp->pn_next)
			len += strlen(pnp->pn_priv) + 1;
		tmp = alloca(len);
		*tmp = '\0';

		append_priv_token(BASIC_TOKEN, tmp, len);
		for (pnp = plp->pl_default; pnp != NULL; pnp = pnp->pn_next)
			append_priv_token(pnp->pn_priv, tmp, len);
		(void) strlcat(tmp, TOKEN_PRIV_STR, len);
		(void) strlcat(tmp, privbuf, len);
	} else {
		tmp = privbuf;
	}


	/*
	 * In the next phase, attempt to convert the merged privilege
	 * string into a privilege set.  In the case of an error, either
	 * there was a memory allocation failure or there was an invalid
	 * privilege token in the string.  In either case, return an
	 * appropriate error code but in the event of an invalid token,
	 * allocate a string containing its name and return that back to
	 * the caller.
	 */
	mergeset = priv_str_to_set(tmp, TOKEN_PRIV_STR, &token);
	if (mergeset == NULL) {
		if (token == NULL)
			return (Z_NOMEM);
		if ((cp = strchr(token, TOKEN_PRIV_CHAR)) != NULL)
			*cp = '\0';
		if ((*privname = strdup(token)) == NULL)
			return (Z_NOMEM);
		else
			return (Z_PRIV_UNKNOWN);
	}

	/*
	 * Next, verify that none of the prohibited zone privileges are
	 * present in the merged privilege set.
	 */
	for (pnp = plp->pl_prohibited; pnp != NULL; pnp = pnp->pn_next) {
		if (priv_ismember(mergeset, pnp->pn_priv)) {
			priv_freeset(mergeset);
			if ((*privname = strdup(pnp->pn_priv)) == NULL)
				return (Z_NOMEM);
			else
				return (Z_PRIV_PROHIBITED);
		}
	}

	/*
	 * Finally, verify that all of the required zone privileges are
	 * present in the merged privilege set.
	 */
	for (pnp = plp->pl_required; pnp != NULL; pnp = pnp->pn_next) {
		if (!priv_ismember(mergeset, pnp->pn_priv)) {
			priv_freeset(mergeset);
			if ((*privname = strdup(pnp->pn_priv)) == NULL)
				return (Z_NOMEM);
			else
				return (Z_PRIV_REQUIRED);
		}
	}

	priv_copyset(mergeset, privs);
	priv_freeset(mergeset);
	return (Z_OK);
}

/*
 * Fill in the supplied privilege set with either the default, safe set of
 * privileges suitable for a non-global zone, or one based on the
 * "limitpriv" property in the zone's configuration.
 *
 * In the event of an invalid privilege specification in the
 * configuration, a string is allocated and returned containing the
 * "privilege" causing the issue.  It is the caller's responsibility to
 * free this memory when it is done with it.
 */
int
zonecfg_get_privset(zone_dochandle_t handle, priv_set_t *privs,
    char **privname)
{
	priv_lists_t *plp;
	char *cp, *limitpriv = NULL;
	int err, limitlen;
	zone_iptype_t iptype;
	const char *curr_iptype;

	/*
	 * Attempt to lookup the "limitpriv" property.  If it does not
	 * exist or matches the string DEFAULT_TOKEN exactly, then the
	 * default, safe privilege set is returned.
	 */
	if ((err = zonecfg_get_limitpriv(handle, &limitpriv)) != Z_OK)
		return (err);

	if ((err = zonecfg_get_iptype(handle, &iptype)) != Z_OK)
		return (err);

	switch (iptype) {
	case ZS_SHARED:
		curr_iptype = "shared";
		break;
	case ZS_EXCLUSIVE:
		curr_iptype = "exclusive";
		break;
	}

	if ((err = priv_lists_create(handle, NULL, &plp, curr_iptype)) != Z_OK)
		return (err);

	limitlen = strlen(limitpriv);
	if (limitlen == 0 || strcmp(limitpriv, DEFAULT_TOKEN) == 0) {
		free(limitpriv);
		err = get_default_privset(privs, plp);
		priv_lists_destroy(plp);
		return (err);
	}

	/*
	 * Check if the string DEFAULT_TOKEN is the first token in a list
	 * of privileges.
	 */
	cp = strchr(limitpriv, TOKEN_PRIV_CHAR);
	if (cp != NULL &&
	    strncmp(limitpriv, DEFAULT_TOKEN, cp - limitpriv) == 0)
		err = verify_privset(cp + 1, privs, privname, B_TRUE, plp);
	else
		err = verify_privset(limitpriv, privs, privname, B_FALSE, plp);

	free(limitpriv);
	priv_lists_destroy(plp);
	return (err);
}

int
zone_get_zonepath(char *zone_name, char *zonepath, size_t rp_sz)
{
	zone_dochandle_t handle;
	boolean_t found = B_FALSE;
	struct zoneent *ze;
	FILE *cookie;
	int err;
	char *cp;

	if (zone_name == NULL)
		return (Z_INVAL);

	(void) strlcpy(zonepath, zonecfg_root, rp_sz);
	cp = zonepath + strlen(zonepath);
	while (cp > zonepath && cp[-1] == '/')
		*--cp = '\0';

	if (strcmp(zone_name, GLOBAL_ZONENAME) == 0) {
		if (zonepath[0] == '\0')
			(void) strlcpy(zonepath, "/", rp_sz);
		return (Z_OK);
	}

	/*
	 * First check the index file.  Because older versions did not have
	 * a copy of the zone path, allow for it to be zero length, in which
	 * case we ignore this result and fall back to the XML files.
	 */
	cookie = setzoneent();
	while ((ze = getzoneent_private(cookie)) != NULL) {
		if (strcmp(ze->zone_name, zone_name) == 0) {
			found = B_TRUE;
			if (ze->zone_path[0] != '\0')
				(void) strlcpy(cp, ze->zone_path,
				    rp_sz - (cp - zonepath));
		}
		free(ze);
		if (found)
			break;
	}
	endzoneent(cookie);
	if (found && *cp != '\0')
		return (Z_OK);

	/* Fall back to the XML files. */
	if ((handle = zonecfg_init_handle()) == NULL)
		return (Z_NOMEM);

	/*
	 * Check the snapshot first: if a zone is running, its zonepath
	 * may have changed.
	 */
	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
		if ((err = zonecfg_get_handle(zone_name, handle)) != Z_OK) {
			zonecfg_fini_handle(handle);
			return (err);
		}
	}
	err = zonecfg_get_zonepath(handle, zonepath, rp_sz);
	zonecfg_fini_handle(handle);
	return (err);
}

int
zone_get_rootpath(char *zone_name, char *rootpath, size_t rp_sz)
{
	int err;

	/* This function makes sense for non-global zones only. */
	if (strcmp(zone_name, GLOBAL_ZONENAME) == 0)
		return (Z_BOGUS_ZONE_NAME);
	if ((err = zone_get_zonepath(zone_name, rootpath, rp_sz)) != Z_OK)
		return (err);
	if (strlcat(rootpath, "/root", rp_sz) >= rp_sz)
		return (Z_TOO_BIG);
	return (Z_OK);
}

int
zone_get_brand(char *zone_name, char *brandname, size_t rp_sz)
{
	int err;
	zone_dochandle_t handle;
	char myzone[MAXNAMELEN];
	int myzoneid = getzoneid();

	/*
	 * If we are not in the global zone, then we don't have the zone
	 * .xml files with the brand name available.  Thus, we are going to
	 * have to ask the kernel for the information.
	 */
	if (myzoneid != GLOBAL_ZONEID) {
		if (is_system_labeled()) {
			(void) strlcpy(brandname, NATIVE_BRAND_NAME, rp_sz);
			return (Z_OK);
		}
		if (zone_getattr(myzoneid, ZONE_ATTR_NAME, myzone,
		    sizeof (myzone)) < 0)
			return (Z_NO_ZONE);
		if (!zonecfg_is_scratch(myzone)) {
			if (strncmp(zone_name, myzone, MAXNAMELEN) != 0)
				return (Z_NO_ZONE);
		}
		err = zone_getattr(myzoneid, ZONE_ATTR_BRAND, brandname, rp_sz);
		if (err < 0)
			return ((errno == EFAULT) ? Z_TOO_BIG : Z_INVAL);

		return (Z_OK);
	}

	if (strcmp(zone_name, "global") == 0)
		return (zonecfg_default_brand(brandname, rp_sz));

	if ((handle = zonecfg_init_handle()) == NULL)
		return (Z_NOMEM);

	err = zonecfg_get_handle((char *)zone_name, handle);
	if (err == Z_OK)
		err = zonecfg_get_brand(handle, brandname, rp_sz);

	zonecfg_fini_handle(handle);
	return (err);
}

/*
 * Return the appropriate root for the active /dev.
 * For normal zone, the path is $ZONEPATH/root;
 * for scratch zone, the dev path is $ZONEPATH/lu.
 */
int
zone_get_devroot(char *zone_name, char *devroot, size_t rp_sz)
{
	int err;
	char *suffix;
	zone_state_t state;

	/* This function makes sense for non-global zones only. */
	if (strcmp(zone_name, GLOBAL_ZONENAME) == 0)
		return (Z_BOGUS_ZONE_NAME);
	if ((err = zone_get_zonepath(zone_name, devroot, rp_sz)) != Z_OK)
		return (err);

	if (zone_get_state(zone_name, &state) == Z_OK &&
	    state == ZONE_STATE_MOUNTED)
		suffix = "/lu";
	else
		suffix = "/root";
	if (strlcat(devroot, suffix, rp_sz) >= rp_sz)
		return (Z_TOO_BIG);
	return (Z_OK);
}

static zone_state_t
kernel_state_to_user_state(zoneid_t zoneid, zone_status_t kernel_state)
{
	char zoneroot[MAXPATHLEN];
	size_t zlen;

	assert(kernel_state <= ZONE_MAX_STATE);
	switch (kernel_state) {
		case ZONE_IS_UNINITIALIZED:
		case ZONE_IS_INITIALIZED:
			/* The kernel will not return these two states */
			return (ZONE_STATE_READY);
		case ZONE_IS_READY:
			/*
			 * If the zone's root is mounted on $ZONEPATH/lu, then
			 * it's a mounted scratch zone.
			 */
			if (zone_getattr(zoneid, ZONE_ATTR_ROOT, zoneroot,
			    sizeof (zoneroot)) >= 0) {
				zlen = strlen(zoneroot);
				if (zlen > 3 &&
				    strcmp(zoneroot + zlen - 3, "/lu") == 0)
					return (ZONE_STATE_MOUNTED);
			}
			return (ZONE_STATE_READY);
		case ZONE_IS_BOOTING:
		case ZONE_IS_RUNNING:
			return (ZONE_STATE_RUNNING);
		case ZONE_IS_SHUTTING_DOWN:
		case ZONE_IS_EMPTY:
			return (ZONE_STATE_SHUTTING_DOWN);
		case ZONE_IS_DOWN:
		case ZONE_IS_DYING:
		case ZONE_IS_DEAD:
		default:
			return (ZONE_STATE_DOWN);
	}
	/* NOTREACHED */
}

int
zone_get_state(char *zone_name, zone_state_t *state_num)
{
	zone_status_t status;
	zoneid_t zone_id;
	struct zoneent *ze;
	boolean_t found = B_FALSE;
	FILE *cookie;
	char kernzone[ZONENAME_MAX];
	FILE *fp;

	if (zone_name == NULL)
		return (Z_INVAL);

	/*
	 * If we're looking at an alternate root, then we need to query the
	 * kernel using the scratch zone name.
	 */
	zone_id = -1;
	if (*zonecfg_root != '\0' && !zonecfg_is_scratch(zone_name)) {
		if ((fp = zonecfg_open_scratch("", B_FALSE)) != NULL) {
			if (zonecfg_find_scratch(fp, zone_name, zonecfg_root,
			    kernzone, sizeof (kernzone)) == 0)
				zone_id = getzoneidbyname(kernzone);
			zonecfg_close_scratch(fp);
		}
	} else {
		zone_id = getzoneidbyname(zone_name);
	}

	/* check to see if zone is running */
	if (zone_id != -1 &&
	    zone_getattr(zone_id, ZONE_ATTR_STATUS, &status,
	    sizeof (status)) >= 0) {
		*state_num = kernel_state_to_user_state(zone_id, status);
		return (Z_OK);
	}

	cookie = setzoneent();
	while ((ze = getzoneent_private(cookie)) != NULL) {
		if (strcmp(ze->zone_name, zone_name) == 0) {
			found = B_TRUE;
			*state_num = ze->zone_state;
		}
		free(ze);
		if (found)
			break;
	}
	endzoneent(cookie);
	return ((found) ? Z_OK : Z_NO_ZONE);
}

int
zone_set_state(char *zone, zone_state_t state)
{
	struct zoneent ze;

	if (state != ZONE_STATE_CONFIGURED && state != ZONE_STATE_INSTALLED &&
	    state != ZONE_STATE_INCOMPLETE)
		return (Z_INVAL);

	bzero(&ze, sizeof (ze));
	(void) strlcpy(ze.zone_name, zone, sizeof (ze.zone_name));
	ze.zone_state = state;
	(void) strlcpy(ze.zone_path, "", sizeof (ze.zone_path));
	return (putzoneent(&ze, PZE_MODIFY));
}

/*
 * Get id (if any) for specified zone.  There are four possible outcomes:
 * - If the string corresponds to the numeric id of an active (booted)
 *   zone, sets *zip to the zone id and returns 0.
 * - If the string corresponds to the name of an active (booted) zone,
 *   sets *zip to the zone id and returns 0.
 * - If the string is a name in the configuration but is not booted,
 *   sets *zip to ZONE_ID_UNDEFINED and returns 0.
 * - Otherwise, leaves *zip unchanged and returns -1.
 *
 * This function acts as an auxiliary filter on the function of the same
 * name in libc; the linker binds to this version if libzonecfg exists,
 * and the libc version if it doesn't.  Any changes to this version of
 * the function should probably be reflected in the libc version as well.
 */
int
zone_get_id(const char *str, zoneid_t *zip)
{
	zone_dochandle_t hdl;
	zoneid_t zoneid;
	char *cp;
	int err;

	/* first try looking for active zone by id */
	errno = 0;
	zoneid = (zoneid_t)strtol(str, &cp, 0);
	if (errno == 0 && cp != str && *cp == '\0' &&
	    getzonenamebyid(zoneid, NULL, 0) != -1) {
		*zip = zoneid;
		return (0);
	}

	/* then look for active zone by name */
	if ((zoneid = getzoneidbyname(str)) != -1) {
		*zip = zoneid;
		return (0);
	}

	/* if in global zone, try looking up name in configuration database */
	if (getzoneid() != GLOBAL_ZONEID ||
	    (hdl = zonecfg_init_handle()) == NULL)
		return (-1);

	if (zonecfg_get_handle(str, hdl) == Z_OK) {
		/* zone exists but isn't active */
		*zip = ZONE_ID_UNDEFINED;
		err = 0;
	} else {
		err = -1;
	}

	zonecfg_fini_handle(hdl);
	return (err);
}

char *
zone_state_str(zone_state_t state_num)
{
	switch (state_num) {
	case ZONE_STATE_CONFIGURED:
		return (ZONE_STATE_STR_CONFIGURED);
	case ZONE_STATE_INCOMPLETE:
		return (ZONE_STATE_STR_INCOMPLETE);
	case ZONE_STATE_INSTALLED:
		return (ZONE_STATE_STR_INSTALLED);
	case ZONE_STATE_READY:
		return (ZONE_STATE_STR_READY);
	case ZONE_STATE_MOUNTED:
		return (ZONE_STATE_STR_MOUNTED);
	case ZONE_STATE_RUNNING:
		return (ZONE_STATE_STR_RUNNING);
	case ZONE_STATE_SHUTTING_DOWN:
		return (ZONE_STATE_STR_SHUTTING_DOWN);
	case ZONE_STATE_DOWN:
		return (ZONE_STATE_STR_DOWN);
	default:
		return ("unknown");
	}
}

/*
 * Given a UUID value, find an associated zone name.  This is intended to be
 * used by callers who set up some 'default' name (corresponding to the
 * expected name for the zone) in the zonename buffer, and thus the function
 * doesn't touch this buffer on failure.
 */
int
zonecfg_get_name_by_uuid(const uuid_t uuidin, char *zonename, size_t namelen)
{
	FILE *fp;
	struct zoneent *ze;
	uchar_t *uuid;

	/*
	 * A small amount of subterfuge via casts is necessary here because
	 * libuuid doesn't use const correctly, but we don't want to export
	 * this brokenness to our clients.
	 */
	uuid = (uchar_t *)uuidin;
	if (uuid_is_null(uuid))
		return (Z_NO_ZONE);
	if ((fp = setzoneent()) == NULL)
		return (Z_NO_ZONE);
	while ((ze = getzoneent_private(fp)) != NULL) {
		if (uuid_compare(uuid, ze->zone_uuid) == 0)
			break;
		free(ze);
	}
	endzoneent(fp);
	if (ze != NULL) {
		(void) strlcpy(zonename, ze->zone_name, namelen);
		free(ze);
		return (Z_OK);
	} else {
		return (Z_NO_ZONE);
	}
}

/*
 * Given a zone name, get its UUID.  Returns a "NULL" UUID value if the zone
 * exists but the file doesn't have a value set yet.  Returns an error if the
 * zone cannot be located.
 */
int
zonecfg_get_uuid(const char *zonename, uuid_t uuid)
{
	FILE *fp;
	struct zoneent *ze;

	if ((fp = setzoneent()) == NULL)
		return (Z_NO_ZONE);
	while ((ze = getzoneent_private(fp)) != NULL) {
		if (strcmp(ze->zone_name, zonename) == 0)
			break;
		free(ze);
	}
	endzoneent(fp);
	if (ze != NULL) {
		uuid_copy(uuid, ze->zone_uuid);
		free(ze);
		return (Z_OK);
	} else {
		return (Z_NO_ZONE);
	}
}

/*
 * File-system convenience functions.
 */
boolean_t
zonecfg_valid_fs_type(const char *type)
{
	/*
	 * We already know which FS types don't work.
	 */
	if (strcmp(type, "proc") == 0 ||
	    strcmp(type, "mntfs") == 0 ||
	    strcmp(type, "autofs") == 0 ||
	    strncmp(type, "nfs", sizeof ("nfs") - 1) == 0)
		return (B_FALSE);
	/*
	 * The caller may do more detailed verification to make sure other
	 * aspects of this filesystem type make sense.
	 */
	return (B_TRUE);
}

/*
 * Generally uninteresting rctl convenience functions.
 */

int
zonecfg_construct_rctlblk(const struct zone_rctlvaltab *rctlval,
    rctlblk_t *rctlblk)
{
	unsigned long long ull;
	char *endp;
	rctl_priv_t priv;
	rctl_qty_t limit;
	uint_t action;

	/* Get the privilege */
	if (strcmp(rctlval->zone_rctlval_priv, "basic") == 0) {
		priv = RCPRIV_BASIC;
	} else if (strcmp(rctlval->zone_rctlval_priv, "privileged") == 0) {
		priv = RCPRIV_PRIVILEGED;
	} else {
		/* Invalid privilege */
		return (Z_INVAL);
	}

	/* deal with negative input; strtoull(3c) doesn't do what we want */
	if (rctlval->zone_rctlval_limit[0] == '-')
		return (Z_INVAL);
	/* Get the limit */
	errno = 0;
	ull = strtoull(rctlval->zone_rctlval_limit, &endp, 0);
	if (errno != 0 || *endp != '\0') {
		/* parse failed */
		return (Z_INVAL);
	}
	limit = (rctl_qty_t)ull;

	/* Get the action */
	if (strcmp(rctlval->zone_rctlval_action, "none") == 0) {
		action = RCTL_LOCAL_NOACTION;
	} else if (strcmp(rctlval->zone_rctlval_action, "signal") == 0) {
		action = RCTL_LOCAL_SIGNAL;
	} else if (strcmp(rctlval->zone_rctlval_action, "deny") == 0) {
		action = RCTL_LOCAL_DENY;
	} else {
		/* Invalid Action */
		return (Z_INVAL);
	}
	rctlblk_set_local_action(rctlblk, action, 0);
	rctlblk_set_privilege(rctlblk, priv);
	rctlblk_set_value(rctlblk, limit);
	return (Z_OK);
}

static int
rctl_check(const char *rctlname, void *arg)
{
	const char *attrname = arg;

	/*
	 * Returning 1 here is our signal to zonecfg_is_rctl() that it is
	 * indeed an rctl name recognized by the system.
	 */
	return (strcmp(rctlname, attrname) == 0 ? 1 : 0);
}

boolean_t
zonecfg_is_rctl(const char *name)
{
	return (rctl_walk(rctl_check, (void *)name) == 1);
}

boolean_t
zonecfg_valid_rctlname(const char *name)
{
	const char *c;

	if (strncmp(name, "zone.", sizeof ("zone.") - 1) != 0)
		return (B_FALSE);
	if (strlen(name) == sizeof ("zone.") - 1)
		return (B_FALSE);
	for (c = name + sizeof ("zone.") - 1; *c != '\0'; c++) {
		if (!isalpha(*c) && *c != '-')
			return (B_FALSE);
	}
	return (B_TRUE);
}

boolean_t
zonecfg_valid_rctlblk(const rctlblk_t *rctlblk)
{
	rctl_priv_t priv = rctlblk_get_privilege((rctlblk_t *)rctlblk);
	uint_t action = rctlblk_get_local_action((rctlblk_t *)rctlblk, NULL);

	if (priv != RCPRIV_PRIVILEGED)
		return (B_FALSE);
	if (action != RCTL_LOCAL_NOACTION && action != RCTL_LOCAL_DENY)
		return (B_FALSE);
	return (B_TRUE);
}

boolean_t
zonecfg_valid_rctl(const char *name, const rctlblk_t *rctlblk)
{
	rctlblk_t *current, *next;
	rctl_qty_t limit = rctlblk_get_value((rctlblk_t *)rctlblk);
	uint_t action = rctlblk_get_local_action((rctlblk_t *)rctlblk, NULL);
	uint_t global_flags;

	if (!zonecfg_valid_rctlblk(rctlblk))
		return (B_FALSE);
	if (!zonecfg_valid_rctlname(name))
		return (B_FALSE);

	current = alloca(rctlblk_size());
	if (getrctl(name, NULL, current, RCTL_FIRST) != 0)
		return (B_TRUE);	/* not an rctl on this system */
	/*
	 * Make sure the proposed value isn't greater than the current system
	 * value.
	 */
	next = alloca(rctlblk_size());
	while (rctlblk_get_privilege(current) != RCPRIV_SYSTEM) {
		rctlblk_t *tmp;

		if (getrctl(name, current, next, RCTL_NEXT) != 0)
			return (B_FALSE);	/* shouldn't happen */
		tmp = current;
		current = next;
		next = tmp;
	}
	if (limit > rctlblk_get_value(current))
		return (B_FALSE);

	/*
	 * Make sure the proposed action is allowed.
	 */
	global_flags = rctlblk_get_global_flags(current);
	if ((global_flags & RCTL_GLOBAL_DENY_NEVER) &&
	    action == RCTL_LOCAL_DENY)
		return (B_FALSE);
	if ((global_flags & RCTL_GLOBAL_DENY_ALWAYS) &&
	    action == RCTL_LOCAL_NOACTION)
		return (B_FALSE);

	return (B_TRUE);
}

/*
 * There is always a race condition between reading the initial copy of
 * a zones state and its state changing.  We address this by providing
 * zonecfg_notify_critical_enter and zonecfg_noticy_critical_exit functions.
 * When zonecfg_critical_enter is called, sets the state field to LOCKED
 * and aquires biglock. Biglock protects against other threads executing
 * critical_enter and the state field protects against state changes during
 * the critical period.
 *
 * If any state changes occur, zn_cb will set the failed field of the znotify
 * structure.  This will cause the critical_exit function to re-lock the
 * channel and return an error. Since evsnts may be delayed, the critical_exit
 * function "flushes" the queue by putting an event on the queue and waiting for
 * zn_cb to notify critical_exit that it received the ping event.
 */
static const char *
string_get_tok(const char *in, char delim, int num)
{
	int i = 0;

	for (; i < num; in++) {
		if (*in == delim)
			i++;
		if (*in == 0)
			return (NULL);
	}
	return (in);
}

static boolean_t
is_ping(sysevent_t *ev)
{
	if (strcmp(sysevent_get_subclass_name(ev),
	    ZONE_EVENT_PING_SUBCLASS) == 0) {
		return (B_TRUE);
	} else {
		return (B_FALSE);
	}
}

static boolean_t
is_my_ping(sysevent_t *ev)
{
	const char *sender;
	char mypid[sizeof (pid_t) * 3 + 1];

	(void) snprintf(mypid, sizeof (mypid), "%i", getpid());
	sender = string_get_tok(sysevent_get_pub(ev), ':', 3);
	if (sender == NULL)
		return (B_FALSE);
	if (strcmp(sender, mypid) != 0)
		return (B_FALSE);
	return (B_TRUE);
}

static int
do_callback(struct znotify *zevtchan, sysevent_t *ev)
{
	nvlist_t *l;
	int zid;
	char *zonename;
	char *newstate;
	char *oldstate;
	int ret;
	hrtime_t when;

	if (strcmp(sysevent_get_subclass_name(ev),
	    ZONE_EVENT_STATUS_SUBCLASS) == 0) {

		if (sysevent_get_attr_list(ev, &l) != 0) {
			if (errno == ENOMEM) {
				zevtchan->zn_failure_count++;
				return (EAGAIN);
			}
			return (0);
		}
		ret = 0;

		if ((nvlist_lookup_string(l, ZONE_CB_NAME, &zonename) == 0) &&
		    (nvlist_lookup_string(l, ZONE_CB_NEWSTATE, &newstate)
		    == 0) &&
		    (nvlist_lookup_string(l, ZONE_CB_OLDSTATE, &oldstate)
		    == 0) &&
		    (nvlist_lookup_uint64(l, ZONE_CB_TIMESTAMP,
		    (uint64_t *)&when) == 0) &&
		    (nvlist_lookup_int32(l, ZONE_CB_ZONEID, &zid) == 0)) {
			ret = zevtchan->zn_callback(zonename, zid, newstate,
			    oldstate, when, zevtchan->zn_private);
		}

		zevtchan->zn_failure_count = 0;
		nvlist_free(l);
		return (ret);
	} else {
		/*
		 * We have received an event in an unknown subclass. Ignore.
		 */
		zevtchan->zn_failure_count = 0;
		return (0);
	}
}

static int
zn_cb(sysevent_t *ev, void *p)
{
	struct znotify *zevtchan = p;
	int error;

	(void) pthread_mutex_lock(&(zevtchan->zn_mutex));

	if (is_ping(ev) && !is_my_ping(ev)) {
		(void) pthread_mutex_unlock((&zevtchan->zn_mutex));
		return (0);
	}

	if (zevtchan->zn_state == ZN_LOCKED) {
		assert(!is_ping(ev));
		zevtchan->zn_failed = B_TRUE;
		(void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
		return (0);
	}

	if (zevtchan->zn_state == ZN_PING_INFLIGHT) {
		if (is_ping(ev)) {
			zevtchan->zn_state = ZN_PING_RECEIVED;
			(void) pthread_cond_signal(&(zevtchan->zn_cond));
			(void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
			return (0);
		} else {
			zevtchan->zn_failed = B_TRUE;
			(void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
			return (0);
		}
	}

	if (zevtchan->zn_state == ZN_UNLOCKED) {

		error = do_callback(zevtchan, ev);
		(void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
		/*
		 * Every ENOMEM failure causes do_callback to increment
		 * zn_failure_count and every success causes it to
		 * set zn_failure_count to zero.  If we got EAGAIN,
		 * we will sleep for zn_failure_count seconds and return
		 * EAGAIN to gpec to try again.
		 *
		 * After 55 seconds, or 10 try's we give up and drop the
		 * event.
		 */
		if (error == EAGAIN) {
			if (zevtchan->zn_failure_count > ZONE_CB_RETRY_COUNT) {
				return (0);
			}
			(void) sleep(zevtchan->zn_failure_count);
		}
		return (error);
	}

	if (zevtchan->zn_state == ZN_PING_RECEIVED) {
		(void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
		return (0);
	}

	abort();
	return (0);
}

void
zonecfg_notify_critical_enter(void *h)
{
	struct znotify *zevtchan = h;

	(void) pthread_mutex_lock(&(zevtchan->zn_bigmutex));
	zevtchan->zn_state = ZN_LOCKED;
}

int
zonecfg_notify_critical_exit(void * h)
{

	struct znotify *zevtchan = h;

	if (zevtchan->zn_state == ZN_UNLOCKED)
		return (0);

	(void) pthread_mutex_lock(&(zevtchan->zn_mutex));
	zevtchan->zn_state = ZN_PING_INFLIGHT;

	(void) sysevent_evc_publish(zevtchan->zn_eventchan,
	    ZONE_EVENT_STATUS_CLASS,
	    ZONE_EVENT_PING_SUBCLASS, ZONE_EVENT_PING_PUBLISHER,
	    zevtchan->zn_subscriber_id, NULL, EVCH_SLEEP);

	while (zevtchan->zn_state != ZN_PING_RECEIVED) {
		(void) pthread_cond_wait(&(zevtchan->zn_cond),
		    &(zevtchan->zn_mutex));
	}

	if (zevtchan->zn_failed == B_TRUE) {
		zevtchan->zn_state = ZN_LOCKED;
		zevtchan->zn_failed = B_FALSE;
		(void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
		return (1);
	}

	zevtchan->zn_state = ZN_UNLOCKED;
	(void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
	(void) pthread_mutex_unlock(&(zevtchan->zn_bigmutex));
	return (0);
}

void
zonecfg_notify_critical_abort(void *h)
{
	struct znotify *zevtchan = h;

	zevtchan->zn_state = ZN_UNLOCKED;
	zevtchan->zn_failed = B_FALSE;
	/*
	 * Don't do anything about zn_lock. If it is held, it could only be
	 * held by zn_cb and it will be unlocked soon.
	 */
	(void) pthread_mutex_unlock(&(zevtchan->zn_bigmutex));
}

void *
zonecfg_notify_bind(int(*func)(const char *zonename, zoneid_t zid,
    const char *newstate, const char *oldstate, hrtime_t when, void *p),
    void *p)
{
	struct znotify *zevtchan;
	int i = 1;
	int r;

	zevtchan = malloc(sizeof (struct znotify));

	if (zevtchan == NULL)
		return (NULL);

	zevtchan->zn_private = p;
	zevtchan->zn_callback = func;
	zevtchan->zn_state = ZN_UNLOCKED;
	zevtchan->zn_failed = B_FALSE;

	if (pthread_mutex_init(&(zevtchan->zn_mutex), NULL))
		goto out3;
	if (pthread_cond_init(&(zevtchan->zn_cond), NULL)) {
		(void) pthread_mutex_destroy(&(zevtchan->zn_mutex));
		goto out3;
	}
	if (pthread_mutex_init(&(zevtchan->zn_bigmutex), NULL)) {
		(void) pthread_mutex_destroy(&(zevtchan->zn_mutex));
		(void) pthread_cond_destroy(&(zevtchan->zn_cond));
		goto out3;
	}

	if (sysevent_evc_bind(ZONE_EVENT_CHANNEL, &(zevtchan->zn_eventchan),
	    0) != 0)
		goto out2;

	do {
		/*
		 * At 4 digits the subscriber ID gets too long and we have
		 * no chance of successfully registering.
		 */
		if (i > 999)
			goto out1;

		(void) sprintf(zevtchan->zn_subscriber_id, "zone_%li_%i",
		    getpid() % 999999l, i);

		r = sysevent_evc_subscribe(zevtchan->zn_eventchan,
		    zevtchan->zn_subscriber_id, ZONE_EVENT_STATUS_CLASS, zn_cb,
		    zevtchan, 0);

		i++;

	} while (r);

	return (zevtchan);
out1:
	(void) sysevent_evc_unbind(zevtchan->zn_eventchan);
out2:
	(void) pthread_mutex_destroy(&zevtchan->zn_mutex);
	(void) pthread_cond_destroy(&zevtchan->zn_cond);
	(void) pthread_mutex_destroy(&(zevtchan->zn_bigmutex));
out3:
	free(zevtchan);

	return (NULL);
}

void
zonecfg_notify_unbind(void *handle)
{

	int ret;

	(void) sysevent_evc_unbind(((struct znotify *)handle)->zn_eventchan);
	/*
	 * Check that all evc threads have gone away. This should be
	 * enforced by sysevent_evc_unbind.
	 */
	ret = pthread_mutex_trylock(&((struct znotify *)handle)->zn_mutex);

	if (ret)
		abort();

	(void) pthread_mutex_unlock(&((struct znotify *)handle)->zn_mutex);
	(void) pthread_mutex_destroy(&((struct znotify *)handle)->zn_mutex);
	(void) pthread_cond_destroy(&((struct znotify *)handle)->zn_cond);
	(void) pthread_mutex_destroy(&((struct znotify *)handle)->zn_bigmutex);

	free(handle);
}

static int
zonecfg_add_ds_core(zone_dochandle_t handle, struct zone_dstab *tabptr)
{
	xmlNodePtr newnode, cur = handle->zone_dh_cur;
	int err;

	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_DATASET, NULL);
	if ((err = newprop(newnode, DTD_ATTR_NAME,
	    tabptr->zone_dataset_name)) != Z_OK)
		return (err);
	return (Z_OK);
}

int
zonecfg_add_ds(zone_dochandle_t handle, struct zone_dstab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_ds_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

static int
zonecfg_delete_ds_core(zone_dochandle_t handle, struct zone_dstab *tabptr)
{
	xmlNodePtr cur = handle->zone_dh_cur;

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_DATASET))
			continue;

		if (match_prop(cur, DTD_ATTR_NAME,
		    tabptr->zone_dataset_name)) {
			xmlUnlinkNode(cur);
			xmlFreeNode(cur);
			return (Z_OK);
		}
	}
	return (Z_NO_RESOURCE_ID);
}

int
zonecfg_delete_ds(zone_dochandle_t handle, struct zone_dstab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_ds_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_modify_ds(
	zone_dochandle_t handle,
	struct zone_dstab *oldtabptr,
	struct zone_dstab *newtabptr)
{
	int err;

	if (oldtabptr == NULL || newtabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = zonecfg_delete_ds_core(handle, oldtabptr)) != Z_OK)
		return (err);

	if ((err = zonecfg_add_ds_core(handle, newtabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_lookup_ds(zone_dochandle_t handle, struct zone_dstab *tabptr)
{
	xmlNodePtr cur, firstmatch;
	int err;
	char dataset[MAXNAMELEN];

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	firstmatch = NULL;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_DATASET))
			continue;
		if (strlen(tabptr->zone_dataset_name) > 0) {
			if ((fetchprop(cur, DTD_ATTR_NAME, dataset,
			    sizeof (dataset)) == Z_OK) &&
			    (strcmp(tabptr->zone_dataset_name,
			    dataset) == 0)) {
				if (firstmatch == NULL)
					firstmatch = cur;
				else
					return (Z_INSUFFICIENT_SPEC);
			}
		}
	}
	if (firstmatch == NULL)
		return (Z_NO_RESOURCE_ID);

	cur = firstmatch;

	if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_dataset_name,
	    sizeof (tabptr->zone_dataset_name))) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_setdsent(zone_dochandle_t handle)
{
	return (zonecfg_setent(handle));
}

int
zonecfg_getdsent(zone_dochandle_t handle, struct zone_dstab *tabptr)
{
	xmlNodePtr cur;
	int err;

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

	if ((cur = handle->zone_dh_cur) == NULL)
		return (Z_NO_ENTRY);

	for (; cur != NULL; cur = cur->next)
		if (!xmlStrcmp(cur->name, DTD_ELEM_DATASET))
			break;
	if (cur == NULL) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (Z_NO_ENTRY);
	}

	if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_dataset_name,
	    sizeof (tabptr->zone_dataset_name))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	handle->zone_dh_cur = cur->next;
	return (Z_OK);
}

int
zonecfg_enddsent(zone_dochandle_t handle)
{
	return (zonecfg_endent(handle));
}

/*
 * Support for aliased rctls; that is, rctls that have simplified names in
 * zonecfg.  For example, max-lwps is an alias for a well defined zone.max-lwps
 * rctl.  If there are multiple existing values for one of these rctls or if
 * there is a single value that does not match the well defined template (i.e.
 * it has a different action) then we cannot treat the rctl as having an alias
 * so we return Z_ALIAS_DISALLOW.  That means that the rctl cannot be
 * managed in zonecfg via an alias and that the standard rctl syntax must be
 * used.
 *
 * The possible return values are:
 *	Z_NO_PROPERTY_ID - invalid alias name
 *	Z_ALIAS_DISALLOW - pre-existing, incompatible rctl definition
 *	Z_NO_ENTRY - no rctl is configured for this alias
 *	Z_OK - we got a valid rctl for the specified alias
 */
int
zonecfg_get_aliased_rctl(zone_dochandle_t handle, char *name, uint64_t *rval)
{
	boolean_t found = B_FALSE;
	boolean_t found_val = B_FALSE;
	xmlNodePtr cur, val;
	char savedname[MAXNAMELEN];
	struct zone_rctlvaltab rctl;
	int i;
	int err;

	for (i = 0; aliases[i].shortname != NULL; i++)
		if (strcmp(name, aliases[i].shortname) == 0)
			break;

	if (aliases[i].shortname == NULL)
		return (Z_NO_PROPERTY_ID);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_RCTL) != 0)
			continue;
		if ((fetchprop(cur, DTD_ATTR_NAME, savedname,
		    sizeof (savedname)) == Z_OK) &&
		    (strcmp(savedname, aliases[i].realname) == 0)) {

			/*
			 * If we already saw one of these, we can't have an
			 * alias since we just found another.
			 */
			if (found)
				return (Z_ALIAS_DISALLOW);
			found = B_TRUE;

			for (val = cur->xmlChildrenNode; val != NULL;
			    val = val->next) {
				/*
				 * If we already have one value, we can't have
				 * an alias since we just found another.
				 */
				if (found_val)
					return (Z_ALIAS_DISALLOW);
				found_val = B_TRUE;

				if ((fetchprop(val, DTD_ATTR_PRIV,
				    rctl.zone_rctlval_priv,
				    sizeof (rctl.zone_rctlval_priv)) != Z_OK))
					break;
				if ((fetchprop(val, DTD_ATTR_LIMIT,
				    rctl.zone_rctlval_limit,
				    sizeof (rctl.zone_rctlval_limit)) != Z_OK))
					break;
				if ((fetchprop(val, DTD_ATTR_ACTION,
				    rctl.zone_rctlval_action,
				    sizeof (rctl.zone_rctlval_action)) != Z_OK))
					break;
			}

			/* check priv and action match the expected vals */
			if (strcmp(rctl.zone_rctlval_priv,
			    aliases[i].priv) != 0 ||
			    strcmp(rctl.zone_rctlval_action,
			    aliases[i].action) != 0)
				return (Z_ALIAS_DISALLOW);
		}
	}

	if (found) {
		*rval = strtoull(rctl.zone_rctlval_limit, NULL, 10);
		return (Z_OK);
	}

	return (Z_NO_ENTRY);
}

int
zonecfg_rm_aliased_rctl(zone_dochandle_t handle, char *name)
{
	int i;
	uint64_t val;
	struct zone_rctltab rctltab;

	/*
	 * First check that we have a valid aliased rctl to remove.
	 * This will catch an rctl entry with non-standard values or
	 * multiple rctl values for this name.  We need to ignore those
	 * rctl entries.
	 */
	if (zonecfg_get_aliased_rctl(handle, name, &val) != Z_OK)
		return (Z_OK);

	for (i = 0; aliases[i].shortname != NULL; i++)
		if (strcmp(name, aliases[i].shortname) == 0)
			break;

	if (aliases[i].shortname == NULL)
		return (Z_NO_RESOURCE_ID);

	(void) strlcpy(rctltab.zone_rctl_name, aliases[i].realname,
	    sizeof (rctltab.zone_rctl_name));

	return (zonecfg_delete_rctl(handle, &rctltab));
}

boolean_t
zonecfg_aliased_rctl_ok(zone_dochandle_t handle, char *name)
{
	uint64_t tmp_val;

	switch (zonecfg_get_aliased_rctl(handle, name, &tmp_val)) {
	case Z_OK:
		/*FALLTHRU*/
	case Z_NO_ENTRY:
		return (B_TRUE);
	default:
		return (B_FALSE);
	}
}

int
zonecfg_set_aliased_rctl(zone_dochandle_t handle, char *name, uint64_t val)
{
	int i;
	int err;
	struct zone_rctltab rctltab;
	struct zone_rctlvaltab *rctlvaltab;
	char buf[128];

	if (!zonecfg_aliased_rctl_ok(handle, name))
		return (Z_ALIAS_DISALLOW);

	for (i = 0; aliases[i].shortname != NULL; i++)
		if (strcmp(name, aliases[i].shortname) == 0)
			break;

	if (aliases[i].shortname == NULL)
		return (Z_NO_RESOURCE_ID);

	/* remove any pre-existing definition for this rctl */
	(void) zonecfg_rm_aliased_rctl(handle, name);

	(void) strlcpy(rctltab.zone_rctl_name, aliases[i].realname,
	    sizeof (rctltab.zone_rctl_name));

	rctltab.zone_rctl_valptr = NULL;

	if ((rctlvaltab = calloc(1, sizeof (struct zone_rctlvaltab))) == NULL)
		return (Z_NOMEM);

	(void) snprintf(buf, sizeof (buf), "%llu", (long long)val);

	(void) strlcpy(rctlvaltab->zone_rctlval_priv, aliases[i].priv,
	    sizeof (rctlvaltab->zone_rctlval_priv));
	(void) strlcpy(rctlvaltab->zone_rctlval_limit, buf,
	    sizeof (rctlvaltab->zone_rctlval_limit));
	(void) strlcpy(rctlvaltab->zone_rctlval_action, aliases[i].action,
	    sizeof (rctlvaltab->zone_rctlval_action));

	rctlvaltab->zone_rctlval_next = NULL;

	if ((err = zonecfg_add_rctl_value(&rctltab, rctlvaltab)) != Z_OK)
		return (err);

	return (zonecfg_add_rctl(handle, &rctltab));
}

static int
delete_tmp_pool(zone_dochandle_t handle)
{
	int err;
	xmlNodePtr cur = handle->zone_dh_cur;

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_TMPPOOL) == 0) {
			xmlUnlinkNode(cur);
			xmlFreeNode(cur);
			return (Z_OK);
		}
	}

	return (Z_NO_RESOURCE_ID);
}

static int
modify_tmp_pool(zone_dochandle_t handle, char *pool_importance)
{
	int err;
	xmlNodePtr cur = handle->zone_dh_cur;
	xmlNodePtr newnode;

	err = delete_tmp_pool(handle);
	if (err != Z_OK && err != Z_NO_RESOURCE_ID)
		return (err);

	if (*pool_importance != '\0') {
		if ((err = operation_prep(handle)) != Z_OK)
			return (err);

		newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_TMPPOOL, NULL);
		if ((err = newprop(newnode, DTD_ATTR_IMPORTANCE,
		    pool_importance)) != Z_OK)
			return (err);
	}

	return (Z_OK);
}

static int
add_pset_core(zone_dochandle_t handle, struct zone_psettab *tabptr)
{
	xmlNodePtr newnode, cur = handle->zone_dh_cur;
	int err;

	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_PSET, NULL);
	if ((err = newprop(newnode, DTD_ATTR_NCPU_MIN,
	    tabptr->zone_ncpu_min)) != Z_OK)
		return (err);
	if ((err = newprop(newnode, DTD_ATTR_NCPU_MAX,
	    tabptr->zone_ncpu_max)) != Z_OK)
		return (err);

	if ((err = modify_tmp_pool(handle, tabptr->zone_importance)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_add_pset(zone_dochandle_t handle, struct zone_psettab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	if ((err = add_pset_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_delete_pset(zone_dochandle_t handle)
{
	int err;
	int res = Z_NO_RESOURCE_ID;
	xmlNodePtr cur = handle->zone_dh_cur;

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_PSET) == 0) {
			xmlUnlinkNode(cur);
			xmlFreeNode(cur);
			res = Z_OK;
			break;
		}
	}

	/*
	 * Once we have msets, we should check that a mset
	 * do not exist before we delete the tmp_pool data.
	 */
	err = delete_tmp_pool(handle);
	if (err != Z_OK && err != Z_NO_RESOURCE_ID)
		return (err);

	return (res);
}

int
zonecfg_modify_pset(zone_dochandle_t handle, struct zone_psettab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = zonecfg_delete_pset(handle)) != Z_OK)
		return (err);

	if ((err = add_pset_core(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_lookup_pset(zone_dochandle_t handle, struct zone_psettab *tabptr)
{
	xmlNodePtr cur;
	int err;
	int res = Z_NO_ENTRY;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	/* this is an optional component */
	tabptr->zone_importance[0] = '\0';

	cur = handle->zone_dh_cur;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_PSET) == 0) {
			if ((err = fetchprop(cur, DTD_ATTR_NCPU_MIN,
			    tabptr->zone_ncpu_min,
			    sizeof (tabptr->zone_ncpu_min))) != Z_OK) {
				handle->zone_dh_cur = handle->zone_dh_top;
				return (err);
			}

			if ((err = fetchprop(cur, DTD_ATTR_NCPU_MAX,
			    tabptr->zone_ncpu_max,
			    sizeof (tabptr->zone_ncpu_max))) != Z_OK) {
				handle->zone_dh_cur = handle->zone_dh_top;
				return (err);
			}

			res = Z_OK;

		} else if (xmlStrcmp(cur->name, DTD_ELEM_TMPPOOL) == 0) {
			if ((err = fetchprop(cur, DTD_ATTR_IMPORTANCE,
			    tabptr->zone_importance,
			    sizeof (tabptr->zone_importance))) != Z_OK) {
				handle->zone_dh_cur = handle->zone_dh_top;
				return (err);
			}
		}
	}

	return (res);
}

int
zonecfg_getpsetent(zone_dochandle_t handle, struct zone_psettab *tabptr)
{
	int err;

	if ((err = zonecfg_setent(handle)) != Z_OK)
		return (err);

	err = zonecfg_lookup_pset(handle, tabptr);

	(void) zonecfg_endent(handle);

	return (err);
}

static int
add_mcap(zone_dochandle_t handle, struct zone_mcaptab *tabptr)
{
	xmlNodePtr newnode, cur = handle->zone_dh_cur;
	int err;

	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_MCAP, NULL);
	if ((err = newprop(newnode, DTD_ATTR_PHYSCAP, tabptr->zone_physmem_cap))
	    != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_delete_mcap(zone_dochandle_t handle)
{
	int err;
	xmlNodePtr cur = handle->zone_dh_cur;

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_MCAP) != 0)
			continue;

		xmlUnlinkNode(cur);
		xmlFreeNode(cur);
		return (Z_OK);
	}
	return (Z_NO_RESOURCE_ID);
}

int
zonecfg_modify_mcap(zone_dochandle_t handle, struct zone_mcaptab *tabptr)
{
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	err = zonecfg_delete_mcap(handle);
	/* it is ok if there is no mcap entry */
	if (err != Z_OK && err != Z_NO_RESOURCE_ID)
		return (err);

	if ((err = add_mcap(handle, tabptr)) != Z_OK)
		return (err);

	return (Z_OK);
}

int
zonecfg_lookup_mcap(zone_dochandle_t handle, struct zone_mcaptab *tabptr)
{
	xmlNodePtr cur;
	int err;

	if (tabptr == NULL)
		return (Z_INVAL);

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_MCAP) != 0)
			continue;
		if ((err = fetchprop(cur, DTD_ATTR_PHYSCAP,
		    tabptr->zone_physmem_cap,
		    sizeof (tabptr->zone_physmem_cap))) != Z_OK) {
			handle->zone_dh_cur = handle->zone_dh_top;
			return (err);
		}

		return (Z_OK);
	}

	return (Z_NO_ENTRY);
}

int
zonecfg_getsecflagsent(zone_dochandle_t handle,
    struct zone_secflagstab *tabptr)
{
	int err;
	xmlNodePtr cur;

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

	if ((err = zonecfg_setent(handle)) != Z_OK)
		return (err);


	if ((cur = handle->zone_dh_cur) == NULL)
		return (Z_NO_ENTRY);

	for (; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_SECFLAGS) == 0)
			break;
	}

	if (cur == NULL) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (Z_NO_ENTRY);
	}

	if ((err = fetchprop(cur, DTD_ATTR_DEFAULT,
	    tabptr->zone_secflags_default,
	    sizeof (tabptr->zone_secflags_default))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	if ((err = fetchprop(cur, DTD_ATTR_LOWER,
	    tabptr->zone_secflags_lower,
	    sizeof (tabptr->zone_secflags_lower))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	if ((err = fetchprop(cur, DTD_ATTR_UPPER,
	    tabptr->zone_secflags_upper,
	    sizeof (tabptr->zone_secflags_upper))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	handle->zone_dh_cur = cur->next;

	(void) zonecfg_endent(handle);

	return (err);
}

static int
getmcapent_core(zone_dochandle_t handle, struct zone_mcaptab *tabptr)
{
	xmlNodePtr cur;
	int err;

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

	if ((cur = handle->zone_dh_cur) == NULL)
		return (Z_NO_ENTRY);

	for (; cur != NULL; cur = cur->next)
		if (xmlStrcmp(cur->name, DTD_ELEM_MCAP) == 0)
			break;
	if (cur == NULL) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (Z_NO_ENTRY);
	}

	if ((err = fetchprop(cur, DTD_ATTR_PHYSCAP, tabptr->zone_physmem_cap,
	    sizeof (tabptr->zone_physmem_cap))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	handle->zone_dh_cur = cur->next;
	return (Z_OK);
}

int
zonecfg_getmcapent(zone_dochandle_t handle, struct zone_mcaptab *tabptr)
{
	int err;

	if ((err = zonecfg_setent(handle)) != Z_OK)
		return (err);

	err = getmcapent_core(handle, tabptr);

	(void) zonecfg_endent(handle);

	return (err);
}

/*
 * Get the full tree of pkg metadata in a set of nested AVL trees.
 * pkgs_avl is an AVL tree of pkgs.
 *
 * The zone xml data contains DTD_ELEM_PACKAGE elements.
 */
int
zonecfg_getpkgdata(zone_dochandle_t handle, uu_avl_pool_t *pkg_pool,
    uu_avl_t *pkgs_avl)
{
	xmlNodePtr cur;
	int res;
	zone_pkg_entry_t *pkg;
	char name[MAXNAMELEN];
	char version[ZONE_PKG_VERSMAX];

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

	if ((res = zonecfg_setent(handle)) != Z_OK)
		return (res);

	if ((cur = handle->zone_dh_cur) == NULL) {
		res = Z_NO_ENTRY;
		goto done;
	}

	for (; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_PACKAGE) == 0) {
			uu_avl_index_t where;

			if ((res = fetchprop(cur, DTD_ATTR_NAME, name,
			    sizeof (name))) != Z_OK)
				goto done;

			if ((res = fetchprop(cur, DTD_ATTR_VERSION, version,
			    sizeof (version))) != Z_OK)
				goto done;

			if ((pkg = (zone_pkg_entry_t *)
			    malloc(sizeof (zone_pkg_entry_t))) == NULL) {
				res = Z_NOMEM;
				goto done;
			}

			if ((pkg->zpe_name = strdup(name)) == NULL) {
				free(pkg);
				res = Z_NOMEM;
				goto done;
			}

			if ((pkg->zpe_vers = strdup(version)) == NULL) {
				free(pkg->zpe_name);
				free(pkg);
				res = Z_NOMEM;
				goto done;
			}

			uu_avl_node_init(pkg, &pkg->zpe_entry, pkg_pool);
			if (uu_avl_find(pkgs_avl, pkg, NULL, &where) != NULL) {
				free(pkg->zpe_name);
				free(pkg->zpe_vers);
				free(pkg);
			} else {
				uu_avl_insert(pkgs_avl, pkg, where);
			}
		}
	}

done:
	(void) zonecfg_endent(handle);
	return (res);
}

int
zonecfg_setdevperment(zone_dochandle_t handle)
{
	return (zonecfg_setent(handle));
}

int
zonecfg_getdevperment(zone_dochandle_t handle, struct zone_devpermtab *tabptr)
{
	xmlNodePtr cur;
	int err;
	char buf[128];

	tabptr->zone_devperm_acl = NULL;

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

	if ((cur = handle->zone_dh_cur) == NULL)
		return (Z_NO_ENTRY);

	for (; cur != NULL; cur = cur->next)
		if (!xmlStrcmp(cur->name, DTD_ELEM_DEV_PERM))
			break;
	if (cur == NULL) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (Z_NO_ENTRY);
	}

	if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_devperm_name,
	    sizeof (tabptr->zone_devperm_name))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	if ((err = fetchprop(cur, DTD_ATTR_UID, buf, sizeof (buf))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}
	tabptr->zone_devperm_uid = (uid_t)atol(buf);

	if ((err = fetchprop(cur, DTD_ATTR_GID, buf, sizeof (buf))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}
	tabptr->zone_devperm_gid = (gid_t)atol(buf);

	if ((err = fetchprop(cur, DTD_ATTR_MODE, buf, sizeof (buf))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}
	tabptr->zone_devperm_mode = (mode_t)strtol(buf, (char **)NULL, 8);

	if ((err = fetch_alloc_prop(cur, DTD_ATTR_ACL,
	    &(tabptr->zone_devperm_acl))) != Z_OK) {
		handle->zone_dh_cur = handle->zone_dh_top;
		return (err);
	}

	handle->zone_dh_cur = cur->next;
	return (Z_OK);
}

int
zonecfg_enddevperment(zone_dochandle_t handle)
{
	return (zonecfg_endent(handle));
}

/* PRINTFLIKE1 */
static void
zerror(const char *zone_name, const char *fmt, ...)
{
	va_list alist;

	va_start(alist, fmt);
	(void) fprintf(stderr, "zone '%s': ", zone_name);
	(void) vfprintf(stderr, fmt, alist);
	(void) fprintf(stderr, "\n");
	va_end(alist);
}

static void
zperror(const char *str)
{
	(void) fprintf(stderr, "%s: %s\n", str, strerror(errno));
}

/*
 * The following three routines implement a simple locking mechanism to
 * ensure that only one instance of zoneadm at a time is able to manipulate
 * a given zone.  The lock is built on top of an fcntl(2) lock of
 * [<altroot>]/var/run/zones/<zonename>.zoneadm.lock.  If a zoneadm instance
 * can grab that lock, it is allowed to manipulate the zone.
 *
 * Since zoneadm may call external applications which in turn invoke
 * zoneadm again, we introduce the notion of "lock inheritance".  Any
 * instance of zoneadm that has another instance in its ancestry is assumed
 * to be acting on behalf of the original zoneadm, and is thus allowed to
 * manipulate its zone.
 *
 * This inheritance is implemented via the _ZONEADM_LOCK_HELD environment
 * variable.  When zoneadm is granted a lock on its zone, this environment
 * variable is set to 1.  When it releases the lock, the variable is set to
 * 0.  Since a child process inherits its parent's environment, checking
 * the state of this variable indicates whether or not any ancestor owns
 * the lock.
 */
void
zonecfg_init_lock_file(const char *zone_name, char **lock_env)
{
	*lock_env = getenv(LOCK_ENV_VAR);
	if (*lock_env == NULL) {
		if (putenv(zoneadm_lock_not_held) != 0) {
			zerror(zone_name, gettext("could not set env: %s"),
			    strerror(errno));
			exit(1);
		}
	} else {
		if (atoi(*lock_env) == 1)
			zone_lock_cnt = 1;
	}
}

void
zonecfg_release_lock_file(const char *zone_name, int lockfd)
{
	/*
	 * If we are cleaning up from a failed attempt to lock the zone for
	 * the first time, we might have a zone_lock_cnt of 0.  In that
	 * error case, we don't want to do anything but close the lock
	 * file.
	 */
	assert(zone_lock_cnt >= 0);
	if (zone_lock_cnt > 0) {
		assert(getenv(LOCK_ENV_VAR) != NULL);
		assert(atoi(getenv(LOCK_ENV_VAR)) == 1);
		if (--zone_lock_cnt > 0) {
			assert(lockfd == -1);
			return;
		}
		if (putenv(zoneadm_lock_not_held) != 0) {
			zerror(zone_name, gettext("could not set env: %s"),
			    strerror(errno));
			exit(1);
		}
	}
	assert(lockfd >= 0);
	(void) close(lockfd);
}

int
zonecfg_grab_lock_file(const char *zone_name, int *lockfd)
{
	char pathbuf[PATH_MAX];
	struct flock flock;

	/*
	 * If we already have the lock, we can skip this expensive song
	 * and dance.
	 */
	assert(zone_lock_cnt >= 0);
	assert(getenv(LOCK_ENV_VAR) != NULL);
	if (zone_lock_cnt > 0) {
		assert(atoi(getenv(LOCK_ENV_VAR)) == 1);
		zone_lock_cnt++;
		*lockfd = -1;
		return (Z_OK);
	}
	assert(getenv(LOCK_ENV_VAR) != NULL);
	assert(atoi(getenv(LOCK_ENV_VAR)) == 0);

	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s", zonecfg_get_root(),
	    ZONES_TMPDIR) >= sizeof (pathbuf)) {
		zerror(zone_name, gettext("alternate root path is too long"));
		return (-1);
	}
	if (mkdir(pathbuf, S_IRWXU) < 0 && errno != EEXIST) {
		zerror(zone_name, gettext("could not mkdir %s: %s"), pathbuf,
		    strerror(errno));
		return (-1);
	}
	(void) chmod(pathbuf, S_IRWXU);

	/*
	 * One of these lock files is created for each zone (when needed).
	 * The lock files are not cleaned up (except on system reboot),
	 * but since there is only one per zone, there is no resource
	 * starvation issue.
	 */
	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s/%s.zoneadm.lock",
	    zonecfg_get_root(), ZONES_TMPDIR, zone_name) >= sizeof (pathbuf)) {
		zerror(zone_name, gettext("alternate root path is too long"));
		return (-1);
	}
	if ((*lockfd = open(pathbuf, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
		zerror(zone_name, gettext("could not open %s: %s"), pathbuf,
		    strerror(errno));
		return (-1);
	}
	/*
	 * Lock the file to synchronize with other zoneadmds
	 */
	flock.l_type = F_WRLCK;
	flock.l_whence = SEEK_SET;
	flock.l_start = (off_t)0;
	flock.l_len = (off_t)0;
	if ((fcntl(*lockfd, F_SETLKW, &flock) < 0) ||
	    (putenv(zoneadm_lock_held) != 0)) {
		zerror(zone_name, gettext("unable to lock %s: %s"), pathbuf,
		    strerror(errno));
		zonecfg_release_lock_file(zone_name, *lockfd);
		return (-1);
	}
	zone_lock_cnt = 1;
	return (Z_OK);
}

boolean_t
zonecfg_lock_file_held(int *lockfd)
{
	if (*lockfd >= 0 || zone_lock_cnt > 0)
		return (B_TRUE);
	return (B_FALSE);
}

static boolean_t
get_doorname(const char *zone_name, char *buffer)
{
	return (snprintf(buffer, PATH_MAX, "%s" ZONE_DOOR_PATH,
	    zonecfg_get_root(), zone_name) < PATH_MAX);
}

/*
 * system daemons are not audited.  For the global zone, this occurs
 * "naturally" since init is started with the default audit
 * characteristics.  Since zoneadmd is a system daemon and it starts
 * init for a zone, it is necessary to clear out the audit
 * characteristics inherited from whomever started zoneadmd.  This is
 * indicated by the audit id, which is set from the ruid parameter of
 * adt_set_user(), below.
 */

static void
prepare_audit_context(const char *zone_name)
{
	adt_session_data_t	*ah;
	char			*failure = gettext("audit failure: %s");

	if (adt_start_session(&ah, NULL, 0)) {
		zerror(zone_name, failure, strerror(errno));
		return;
	}
	if (adt_set_user(ah, ADT_NO_AUDIT, ADT_NO_AUDIT,
	    ADT_NO_AUDIT, ADT_NO_AUDIT, NULL, ADT_NEW)) {
		zerror(zone_name, failure, strerror(errno));
		(void) adt_end_session(ah);
		return;
	}
	if (adt_set_proc(ah))
		zerror(zone_name, failure, strerror(errno));

	(void) adt_end_session(ah);
}

static const char **
get_zoneadmd_envp(void)
{
	const char **envp = NULL;
	size_t envlen;
	size_t envslot = 0;
	const char *tok;
	void *dstate = NULL;

	/*
	 * This initial array size is enough to hold the two variables
	 * set below, up to five additional entries from /etc/default/init,
	 * and the NULL terminator. /etc/default/init commonly includes only
	 * TZ, LANG and LC_ALL. The array will be grown if necessary by
	 * doubling the size whenever it is full.
	 */
	envlen = 8;

	if ((envp = recallocarray(NULL, 0, envlen, sizeof (char *))) == NULL)
		return (NULL);

	/*
	 * See the comment above zonecfg_init_lock_file() for details on the
	 * implementation of the locking mechanism.
	 * zoneadmd is started with an inherited lock, indicated by the
	 * environment variable being set. Once the starting zoneadm exits,
	 * zoneadmd may persist and will continue to believe that it has the
	 * lock. This is okay as long as the only things that connect to the
	 * zoneadmd door and cause it to do work that requires a lock have
	 * grabbed the lock in advance, which zoneadm does in all cases today.
	 */
	envp[envslot++] = zoneadm_lock_held;

	if (asprintf((char **)&tok, "PATH=%s", ZONEADMD_PATH) == -1) {
		free(envp);
		return (NULL);
	}
	envp[envslot++] = tok;

	if (definit_open(DEFINIT_DEFAULT_FILE, &dstate) != 0) {
		if (errno == ENOENT) {
			/*
			 * If the configuration file does not exist, return the
			 * environment populated so far (with PATH and the
			 * zoneadm lock).
			 */
			envp[envslot] = NULL;
			return (envp);
		}
		goto err;
	}

	while ((tok = definit_token(dstate)) != NULL) {

		if (strncmp(tok, "CMASK=", 6) == 0) {
			long t;

			t = strtol(tok + 6, NULL, 8);

			if (t >= DEFINIT_MIN_UMASK && t <= DEFINIT_MAX_UMASK)
				(void) umask((int)t);
			continue;
		}

		/*
		 * Always ensure there is space for a terminating
		 * NULL in addition to the new entry being added.
		 */
		if (envslot + 2 >= envlen) {
			const char **newenvp;

			newenvp = recallocarray(envp, envlen, envlen * 2,
			    sizeof (char *));
			if (newenvp == NULL)
				goto err;
			envp = newenvp;
			envlen *= 2;
		}

		envp[envslot] = strdup(tok);
		if (envp[envslot] == NULL)
			goto err;
		envslot++;
	}

	definit_close(dstate);
	envp[envslot] = NULL;
	return (envp);

err:
	if (dstate != NULL)
		definit_close(dstate);

	/*
	 * The first slot in envp is 'zoneadm_lock_held' and should not be
	 * freed.
	 */
	while (--envslot > 0)
		free((void *)envp[envslot]);
	free(envp);

	return (NULL);
}

static int
start_zoneadmd(const char *zone_name, boolean_t lock)
{
	char doorpath[PATH_MAX];
	pid_t child_pid;
	int error = -1;
	int doorfd, lockfd;
	struct door_info info;

	if (!get_doorname(zone_name, doorpath))
		return (-1);

	if (lock)
		if (zonecfg_grab_lock_file(zone_name, &lockfd) != Z_OK)
			return (-1);

	/*
	 * Now that we have the lock, re-confirm that the daemon is
	 * *not* up and working fine.  If it is still down, we have a green
	 * light to start it.
	 */
	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
		if (errno != ENOENT) {
			zperror(doorpath);
			goto out;
		}
	} else {
		if (door_info(doorfd, &info) == 0 &&
		    ((info.di_attributes & DOOR_REVOKED) == 0)) {
			error = Z_OK;
			(void) close(doorfd);
			goto out;
		}
		(void) close(doorfd);
	}

	if ((child_pid = fork()) == -1) {
		zperror(gettext("could not fork"));
		goto out;
	}

	if (child_pid == 0) {
		const char *argv[6], **ap;
		const char **envp;

		/* child process */
		prepare_audit_context(zone_name);

		ap = argv;
		*ap++ = "zoneadmd";
		*ap++ = "-z";
		*ap++ = zone_name;
		if (zonecfg_in_alt_root()) {
			*ap++ = "-R";
			*ap++ = zonecfg_get_root();
		}
		*ap = NULL;

		envp = get_zoneadmd_envp();
		if (envp == NULL) {
			zperror(gettext(
			    "could not build environment for zoneadmd"));
			_exit(1);
		}

		(void) execve("/usr/lib/zones/zoneadmd",
		    (char * const *)argv, (char * const *)envp);
		/*
		 * TRANSLATION_NOTE
		 * zoneadmd is a literal that should not be translated.
		 */
		zperror(gettext("could not exec zoneadmd"));
		_exit(1);
	} else {
		/* parent process */
		pid_t retval;
		int pstatus = 0;

		do {
			retval = waitpid(child_pid, &pstatus, 0);
		} while (retval != child_pid);
		if (WIFSIGNALED(pstatus) || (WIFEXITED(pstatus) &&
		    WEXITSTATUS(pstatus) != 0)) {
			zerror(zone_name, gettext("could not start %s"),
			    "zoneadmd");
			goto out;
		}
	}
	error = Z_OK;
out:
	if (lock)
		zonecfg_release_lock_file(zone_name, lockfd);
	return (error);
}

int
zonecfg_ping_zoneadmd(const char *zone_name)
{
	char doorpath[PATH_MAX];
	int doorfd;
	struct door_info info;

	if (!get_doorname(zone_name, doorpath))
		return (-1);

	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
		return (-1);
	}
	if (door_info(doorfd, &info) == 0 &&
	    ((info.di_attributes & DOOR_REVOKED) == 0)) {
		(void) close(doorfd);
		return (Z_OK);
	}
	(void) close(doorfd);
	return (-1);
}

int
zonecfg_call_zoneadmd(const char *zone_name, zone_cmd_arg_t *arg, char *locale,
    boolean_t lock)
{
	char doorpath[PATH_MAX];
	int doorfd, result;
	door_arg_t darg;

	zoneid_t zoneid;
	uint64_t uniqid = 0;

	zone_cmd_rval_t *rvalp;
	size_t rlen;
	char *cp, *errbuf;

	rlen = getpagesize();
	if ((rvalp = malloc(rlen)) == NULL) {
		zerror(zone_name, gettext("failed to allocate %lu bytes: %s"),
		    rlen, strerror(errno));
		return (-1);
	}

	if ((zoneid = getzoneidbyname(zone_name)) != ZONE_ID_UNDEFINED) {
		(void) zone_getattr(zoneid, ZONE_ATTR_UNIQID, &uniqid,
		    sizeof (uniqid));
	}
	arg->uniqid = uniqid;
	(void) strlcpy(arg->locale, locale, sizeof (arg->locale));
	if (!get_doorname(zone_name, doorpath)) {
		zerror(zone_name, gettext("alternate root path is too long"));
		free(rvalp);
		return (-1);
	}

	/*
	 * Loop trying to start zoneadmd; if something goes seriously
	 * wrong we break out and fail.
	 */
	for (;;) {
		if (start_zoneadmd(zone_name, lock) != Z_OK)
			break;

		if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
			zperror(gettext("failed to open zone door"));
			break;
		}

		darg.data_ptr = (char *)arg;
		darg.data_size = sizeof (*arg);
		darg.desc_ptr = NULL;
		darg.desc_num = 0;
		darg.rbuf = (char *)rvalp;
		darg.rsize = rlen;
		if (door_call(doorfd, &darg) != 0) {
			(void) close(doorfd);
			/*
			 * We'll get EBADF if the door has been revoked.
			 */
			if (errno != EBADF) {
				zperror(gettext("door_call failed"));
				break;
			}
			continue;	/* take another lap */
		}
		(void) close(doorfd);

		if (darg.data_size == 0) {
			/* Door server is going away; kick it again. */
			continue;
		}

		errbuf = rvalp->errbuf;
		while (*errbuf != '\0') {
			/*
			 * Remove any newlines since zerror()
			 * will append one automatically.
			 */
			cp = strchr(errbuf, '\n');
			if (cp != NULL)
				*cp = '\0';
			zerror(zone_name, "%s", errbuf);
			if (cp == NULL)
				break;
			errbuf = cp + 1;
		}
		result = rvalp->rval == 0 ? 0 : -1;
		free(rvalp);
		return (result);
	}

	free(rvalp);
	return (-1);
}

boolean_t
zonecfg_valid_auths(const char *auths, const char *zonename)
{
	char *right;
	char *tmpauths;
	char *lasts;
	char authname[MAXAUTHS];
	boolean_t status = B_TRUE;

	tmpauths = strdup(auths);
	if (tmpauths == NULL) {
		zerror(zonename, gettext("Out of memory"));
		return (B_FALSE);
	}
	right = strtok_r(tmpauths, ",", &lasts);
	while (right != NULL) {
		(void) snprintf(authname, MAXAUTHS, "%s%s",
		    ZONE_AUTH_PREFIX, right);
		if (getauthnam(authname) == NULL) {
			status = B_FALSE;
			zerror(zonename,
			    gettext("'%s' is not a valid authorization"),
			    right);
		}
		right = strtok_r(NULL, ",", &lasts);
	}
	free(tmpauths);
	return (status);
}

int
zonecfg_delete_admins(zone_dochandle_t handle, char *zonename)
{
	int err;
	struct zone_admintab admintab;
	boolean_t changed = B_FALSE;

	if ((err = zonecfg_setadminent(handle)) != Z_OK) {
		return (err);
	}
	while (zonecfg_getadminent(handle, &admintab) == Z_OK) {
		err = zonecfg_delete_admin(handle, &admintab,
		    zonename);
		if (err != Z_OK) {
			(void) zonecfg_endadminent(handle);
			return (err);
		} else {
			changed = B_TRUE;
		}
		if ((err = zonecfg_setadminent(handle)) != Z_OK) {
			return (err);
		}
	}
	(void) zonecfg_endadminent(handle);
	return (changed? Z_OK:Z_NO_ENTRY);
}

/*
 * Checks if a long authorization applies to this zone.
 * If so, it returns true, after destructively stripping
 * the authorization of its prefix and zone suffix.
 */
static boolean_t
is_zone_auth(char **auth, char *zonename, char *oldzonename)
{
	char *suffix;
	size_t offset;

	offset = strlen(ZONE_AUTH_PREFIX);
	if ((strncmp(*auth, ZONE_AUTH_PREFIX, offset) == 0) &&
	    ((suffix = strchr(*auth, '/')) != NULL)) {
		if (strcmp(suffix + 1, zonename) == 0) {
			*auth += offset;
			suffix[0] = '\0';
			return (B_TRUE);
		} else if ((oldzonename != NULL) &&
		    (strcmp(suffix + 1, oldzonename) == 0)) {
			*auth += offset;
			suffix[0] = '\0';
			return (B_TRUE);
		}
	}
	return (B_FALSE);
}

/*
 * This function determines whether the zone-specific authorization
 * assignments in /etc/user_attr have been changed more recently
 * than the equivalent data stored in the zone's configuration file.
 * This should only happen if the zone-specific authorizations in
 * the user_attr file were modified using a tool other than zonecfg.
 * If the configuration file is out-of-date with respect to these
 * authorization assignments, it is updated to match those specified
 * in /etc/user_attr.
 */

int
zonecfg_update_userauths(zone_dochandle_t handle, char *zonename)
{
	userattr_t *ua_ptr;
	char *authlist;
	char *lasts;
	FILE  *uaf;
	struct zone_admintab admintab;
	struct stat config_st, ua_st;
	char config_file[MAXPATHLEN];
	boolean_t changed = B_FALSE;
	int err;

	if ((uaf = fopen(USERATTR_FILENAME, "r")) == NULL) {
		zerror(zonename, gettext("could not open file %s: %s"),
		    USERATTR_FILENAME, strerror(errno));
		if (errno == EACCES)
			return (Z_ACCES);
		if (errno == ENOENT)
			return (Z_NO_ZONE);
		return (Z_MISC_FS);
	}
	if ((err = fstat(fileno(uaf), &ua_st)) != 0) {
		zerror(zonename, gettext("could not stat file %s: %s"),
		    USERATTR_FILENAME, strerror(errno));
		(void) fclose(uaf);
		return (Z_MISC_FS);
	}
	if (!config_file_path(zonename, config_file)) {
		(void) fclose(uaf);
		return (Z_MISC_FS);
	}

	if ((err = stat(config_file, &config_st)) != 0) {
		zerror(zonename, gettext("could not stat file %s: %s"),
		    config_file, strerror(errno));
		(void) fclose(uaf);
		return (Z_MISC_FS);
	}
	if (config_st.st_mtime >= ua_st.st_mtime) {
		(void) fclose(uaf);
		return (Z_NO_ENTRY);
	}
	if ((err = zonecfg_delete_admins(handle, zonename)) == Z_OK) {
		changed = B_TRUE;
	} else if (err != Z_NO_ENTRY) {
		(void) fclose(uaf);
		return (err);
	}
	while ((ua_ptr = fgetuserattr(uaf)) != NULL) {
		if (ua_ptr->name[0] == '#') {
			continue;
		}
		authlist = kva_match(ua_ptr->attr, USERATTR_AUTHS_KW);
		if (authlist != NULL) {
			char *cur_auth;
			boolean_t first;

			first = B_TRUE;
			bzero(&admintab.zone_admin_auths, MAXAUTHS);
			cur_auth = strtok_r(authlist, ",", &lasts);
			while (cur_auth != NULL) {
				if (is_zone_auth(&cur_auth, zonename,
				    NULL)) {
					/*
					 * Add auths for this zone
					 */
					if (first) {
						first = B_FALSE;
					} else {
						(void) strlcat(
						    admintab.zone_admin_auths,
						    ",", MAXAUTHS);
					}
					(void) strlcat(
					    admintab.zone_admin_auths,
					    cur_auth, MAXAUTHS);
				}
				cur_auth = strtok_r(NULL, ",", &lasts);
			}
			if (!first) {
				/*
				 * Add this right to config file
				 */
				(void) strlcpy(admintab.zone_admin_user,
				    ua_ptr->name,
				    sizeof (admintab.zone_admin_user));
				err = zonecfg_add_admin(handle,
				    &admintab, zonename);
				if (err != Z_OK) {
					(void) fclose(uaf);
					return (err);
				} else {
					changed = B_TRUE;
				}
			}
		}
	} /* end-of-while-loop */
	(void) fclose(uaf);
	return (changed? Z_OK: Z_NO_ENTRY);
}

static void
update_profiles(char *rbac_profs, boolean_t add)
{
	char new_profs[MAXPROFS];
	char *cur_prof;
	boolean_t first = B_TRUE;
	boolean_t found = B_FALSE;
	char *lasts;

	cur_prof = strtok_r(rbac_profs, ",", &lasts);
	while (cur_prof != NULL) {
		if (strcmp(cur_prof, ZONE_MGMT_PROF) == 0) {
			found = B_TRUE;
			if (!add) {
				cur_prof = strtok_r(NULL, ",", &lasts);
				continue;
			}
		}
		if (first) {
			first = B_FALSE;
		} else {
			(void) strlcat(new_profs, ",",
			    MAXPROFS);
		}
		(void) strlcat(new_profs, cur_prof,
		    MAXPROFS);
		cur_prof = strtok_r(NULL, ",", &lasts);
	}
	/*
	 * Now prepend the Zone Management profile at the beginning
	 * of the list if it is needed, and append the rest.
	 * Return the updated list in the original buffer.
	 */
	if (add && !found) {
		first = B_FALSE;
		(void) strlcpy(rbac_profs, ZONE_MGMT_PROF, MAXPROFS);
	} else {
		first = B_TRUE;
		rbac_profs[0] = '\0';
	}
	if (strlen(new_profs) > 0) {
		if (!first)
			(void) strlcat(rbac_profs, ",", MAXPROFS);
		(void) strlcat(rbac_profs, new_profs, MAXPROFS);
	}
}

#define	MAX_CMD_LEN	1024

static int
do_subproc(char *zonename, char *cmdbuf)
{
	char inbuf[MAX_CMD_LEN];
	FILE *file;
	int status;

	file = popen(cmdbuf, "r");
	if (file == NULL) {
		zerror(zonename, gettext("Could not launch: %s"), cmdbuf);
		return (-1);
	}

	while (fgets(inbuf, sizeof (inbuf), file) != NULL)
		(void) fprintf(stderr, "%s", inbuf);
	status = pclose(file);

	if (WIFSIGNALED(status)) {
		zerror(zonename, gettext("%s unexpectedly terminated "
		    "due to signal %d"),
		    cmdbuf, WTERMSIG(status));
		return (-1);
	}
	assert(WIFEXITED(status));
	return (WEXITSTATUS(status));
}

/*
 * This function updates the local /etc/user_attr file to
 * correspond to the admin settings that are currently being
 * committed. The updates are done via usermod and/or rolemod
 * depending on the type of the specified user. It is also
 * invoked to remove entries from user_attr corresponding to
 * removed admin assignments, using an empty auths string.
 *
 * Because the removed entries are no longer included in the
 * cofiguration that is being committed, a linked list of
 * removed admin entries is maintained to keep track of such
 * transactions. The head of the list is stored in the zone_dh_userauths
 * element of the handle strcture.
 */
static int
zonecfg_authorize_user_impl(zone_dochandle_t handle, char *user,
    char *auths, char *zonename)
{
	char *right;
	char old_auths[MAXAUTHS];
	char new_auths[MAXAUTHS];
	char rbac_profs[MAXPROFS];
	char *lasts;
	userattr_t *u;
	boolean_t first = B_TRUE;
	boolean_t is_zone_admin = B_FALSE;
	char user_cmd[] = "/usr/sbin/usermod";
	char role_cmd[] = "/usr/sbin/rolemod";
	char *auths_cmd = user_cmd;	/* either usermod or rolemod */
	char *new_auth_start;		/* string containing the new auths */
	int new_auth_cnt = 0;		/* delta of changed authorizations */

	/*
	 * First get the existing authorizations for this user
	 */

	bzero(&old_auths, sizeof (old_auths));
	bzero(&new_auths, sizeof (new_auths));
	bzero(&rbac_profs, sizeof (rbac_profs));
	if ((u = getusernam(user)) != NULL) {
		char *current_auths;
		char *current_profs;
		char *type;

		type = kva_match(u->attr, USERATTR_TYPE_KW);
		if (type != NULL) {
			if (strcmp(type, USERATTR_TYPE_NONADMIN_KW) == 0)
				auths_cmd = role_cmd;
		}

		current_auths = kva_match(u->attr, USERATTR_AUTHS_KW);
		if (current_auths != NULL) {
			char *cur_auth;
			char *delete_name;
			size_t offset;

			offset = strlen(ZONE_AUTH_PREFIX);

			(void) strlcpy(old_auths, current_auths, MAXAUTHS);
			cur_auth = strtok_r(current_auths, ",", &lasts);

			/*
			 * Next, remove any existing authorizations
			 * for this zone, and determine if the
			 * user still needs the Zone Management Profile.
			 */
			if (is_renaming(handle))
				delete_name = handle->zone_dh_delete_name;
			else
				delete_name = NULL;
			while (cur_auth != NULL) {
				if (!is_zone_auth(&cur_auth, zonename,
				    delete_name)) {
					if (first) {
						first = B_FALSE;
					} else {
						(void) strlcat(new_auths, ",",
						    MAXAUTHS);
					}
					(void) strlcat(new_auths, cur_auth,
					    MAXAUTHS);
					/*
					 * If the user has authorizations
					 * for other zones, then set a
					 * flag indicate that the Zone
					 * Management profile should be
					 * preserved in user_attr.
					 */
					if (strncmp(cur_auth,
					    ZONE_AUTH_PREFIX, offset) == 0)
						is_zone_admin = B_TRUE;
				} else {
					new_auth_cnt++;
				}
				cur_auth = strtok_r(NULL, ",", &lasts);
			}
		}
		current_profs = kva_match(u->attr, USERATTR_PROFILES_KW);
		if (current_profs != NULL) {
			(void) strlcpy(rbac_profs, current_profs, MAXPROFS);
		}
		free_userattr(u);
	}
	/*
	 * The following is done to avoid revisiting the
	 * user_attr entry for this user
	 */
	(void) zonecfg_remove_userauths(handle, user, "", B_FALSE);

	/*
	 * Convert each right into a properly formatted authorization
	 */
	new_auth_start = new_auths + strlen(new_auths);
	if (!first)
		new_auth_start++;
	right = strtok_r(auths, ",", &lasts);
	while (right != NULL) {
		char auth[MAXAUTHS];

		(void) snprintf(auth, MAXAUTHS, "%s%s/%s",
		    ZONE_AUTH_PREFIX, right, zonename);
		if (first) {
			first = B_FALSE;
		} else {
			(void) strlcat(new_auths, ",", MAXAUTHS);
		}
		(void) strlcat(new_auths, auth, MAXAUTHS);
		is_zone_admin = B_TRUE;
		new_auth_cnt--;
		right = strtok_r(NULL, ",", &lasts);
	}

	/*
	 * Need to update the authorizations in user_attr unless
	 * the number of old and new authorizations is unchanged
	 * and the new auths are a substrings of the old auths.
	 *
	 * If the user's previous authorizations have changed
	 * execute the usermod progam to update them in user_attr.
	 */
	if ((new_auth_cnt != 0) ||
	    (strstr(old_auths, new_auth_start) == NULL)) {
		char    *cmdbuf;
		size_t  cmd_len;

		update_profiles(rbac_profs, is_zone_admin);
		cmd_len = snprintf(NULL, 0, "%s -A \"%s\" -P \"%s\" %s",
		    auths_cmd, new_auths, rbac_profs, user) + 1;
		if ((cmdbuf = malloc(cmd_len)) == NULL) {
			return (Z_NOMEM);
		}
		(void) snprintf(cmdbuf, cmd_len, "%s -A \"%s\" -P \"%s\" %s",
		    auths_cmd, new_auths, rbac_profs, user);
		if (do_subproc(zonename, cmdbuf) != 0) {
			free(cmdbuf);
			return (Z_SYSTEM);
		}
		free(cmdbuf);
	}

	return (Z_OK);
}

int
zonecfg_authorize_users(zone_dochandle_t handle, char *zonename)
{
	xmlNodePtr cur;
	int err;
	char user[MAXUSERNAME];
	char auths[MAXAUTHS];

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
			continue;
		if (fetchprop(cur, DTD_ATTR_USER, user,
		    sizeof (user)) != Z_OK)
			continue;
		if (fetchprop(cur, DTD_ATTR_AUTHS, auths,
		    sizeof (auths)) != Z_OK)
			continue;
		if (zonecfg_authorize_user_impl(handle, user, auths, zonename)
		    != Z_OK)
			return (Z_SYSTEM);
	}
	(void) zonecfg_remove_userauths(handle, "", "", B_TRUE);

	return (Z_OK);
}

int
zonecfg_deauthorize_user(zone_dochandle_t handle, char *user, char *zonename)
{
	return (zonecfg_authorize_user_impl(handle, user, "", zonename));
}

int
zonecfg_deauthorize_users(zone_dochandle_t handle, char *zonename)
{
	xmlNodePtr cur;
	int err;
	char user[MAXUSERNAME];

	if ((err = operation_prep(handle)) != Z_OK)
		return (err);

	cur = handle->zone_dh_cur;
	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		if (xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
			continue;
		if (fetchprop(cur, DTD_ATTR_USER, user,
		    sizeof (user)) != Z_OK)
			continue;
		if ((err = zonecfg_deauthorize_user(handle, user,
		    zonename)) != Z_OK)
			return (err);
	}
	return (Z_OK);
}

int
zonecfg_insert_userauths(zone_dochandle_t handle, char *user, char *zonename)
{
	zone_userauths_t *new, **prev, *next;

	prev = &handle->zone_dh_userauths;
	next = *prev;
	while (next) {
		if ((strncmp(next->user, user, MAXUSERNAME) == 0) &&
		    (strncmp(next->zonename, zonename,
		    ZONENAME_MAX) == 0)) {
			/*
			 * user is already in list
			 * which isn't supposed to happen!
			 */
			return (Z_OK);
		}
		prev = &next->next;
		next = *prev;
	}
	new = (zone_userauths_t *)malloc(sizeof (zone_userauths_t));
	if (new == NULL)
		return (Z_NOMEM);

	(void) strlcpy(new->user, user, sizeof (new->user));
	(void) strlcpy(new->zonename, zonename, sizeof (new->zonename));
	new->next = NULL;
	*prev = new;
	return (Z_OK);
}

int
zonecfg_remove_userauths(zone_dochandle_t handle, char *user, char *zonename,
    boolean_t deauthorize)
{
	zone_userauths_t *new, **prev, *next;

	prev = &handle->zone_dh_userauths;
	next = *prev;

	while (next) {
		if ((strlen(user) == 0 ||
		    strncmp(next->user, user, MAXUSERNAME) == 0) &&
		    (strlen(zonename) == 0 ||
		    (strncmp(next->zonename, zonename, ZONENAME_MAX) == 0))) {
			new = next;
			*prev = next->next;
			next =  *prev;
			if (deauthorize)
				(void) zonecfg_deauthorize_user(handle,
				    new->user, new->zonename);
			free(new);
			continue;
		}
		prev = &next->next;
		next = *prev;
	}
	return (Z_OK);
}