summaryrefslogtreecommitdiff
path: root/usr/src/cmd/svc/svcadm/svcadm.c
blob: c5a046565f906acbeb654a8f3738f53f93af0ee3 (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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright 2020, Joyent, Inc. All rights reserved.
 */

/*
 * svcadm - request adminstrative actions for service instances
 */

#include <locale.h>
#include <libintl.h>
#include <libscf.h>
#include <libscf_priv.h>
#include <libcontract.h>
#include <libcontract_priv.h>
#include <sys/contract/process.h>
#include <libuutil.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <procfs.h>
#include <assert.h>
#include <errno.h>
#include <zone.h>

#ifndef TEXT_DOMAIN
#define	TEXT_DOMAIN	"SUNW_OST_OSCMD"
#endif /* TEXT_DOMAIN */

/* Must be a power of two */
#define	HT_BUCKETS	64

/*
 * Exit codes for enable and disable -s.
 */
#define	EXIT_SVC_FAILURE	3
#define	EXIT_DEP_FAILURE	4

#define	WALK_FLAGS	(SCF_WALK_UNIPARTIAL | SCF_WALK_MULTIPLE)

/*
 * How long we will wait (in seconds) for a service to change state
 * before re-checking its dependencies.
 */
#define	WAIT_INTERVAL		3

#define	bad_error(func, err)						\
	uu_panic("%s:%d: %s() failed with unexpected error %d.\n",	\
	    __FILE__, __LINE__, (func), (err));

struct ht_elt {
	struct ht_elt	*next;
	boolean_t	active;
	char		str[1];
};


/*
 * Callback data for enable/disable.
 */
#define	SET_ENABLED	0x1
#define	SET_TEMPORARY	0x2
#define	SET_RECURSIVE	0x4

typedef struct {
	char ed_comment[SCF_COMMENT_MAX_LENGTH];
	int ed_flags;
} enable_data_t;


scf_handle_t *h;
ssize_t max_scf_fmri_sz;
static const char *emsg_permission_denied;
static const char *emsg_nomem;
static const char *emsg_create_pg_perm_denied;
static const char *emsg_pg_perm_denied;
static const char *emsg_prop_perm_denied;
static const char *emsg_no_service;

static int exit_status = 0;
static int verbose = 0;
static char *scratch_fmri;
static char *g_zonename = NULL;
static char svcstate[80];
static boolean_t svcsearch = B_FALSE;

static struct ht_elt **visited;

void do_scfdie(int lineno) __NORETURN;
static void usage_milestone(void) __NORETURN;
static void set_astring_prop(const char *, const char *, const char *,
    uint32_t, const char *, const char *);
static void pr_warn(const char *format, ...);

/*
 * Visitors from synch.c, needed for enable -s and disable -s.
 */
extern int is_enabled(scf_instance_t *);
extern int has_potential(scf_instance_t *, int);

void
do_scfdie(int lineno)
{
	scf_error_t err;

	switch (err = scf_error()) {
	case SCF_ERROR_CONNECTION_BROKEN:
		uu_die(gettext("Connection to repository server broken.  "
		    "Exiting.\n"));
		/* NOTREACHED */

	case SCF_ERROR_BACKEND_READONLY:
		uu_die(gettext("Repository is read-only.  Exiting.\n"));
		/* NOTREACHED */

	default:
#ifdef NDEBUG
		uu_die(gettext("Unexpected libscf error: %s.  Exiting.\n"),
		    scf_strerror(err));
#else
		uu_die("Unexpected libscf error on line %d: %s.\n", lineno,
		    scf_strerror(err));
#endif
	}
}

#define	scfdie()	do_scfdie(__LINE__)

static void
usage()
{
	(void) fprintf(stderr, gettext(
	"Usage: %1$s [-S <state>] [-v] [-Z | -z zone] [cmd [args ... ]]\n\n"
	"\t%1$s enable [-rst] [<service> ...]\t- enable and online service(s)\n"
	"\t%1$s disable [-c comment] [-st] [<service> ...] - disable "
	"service(s)\n"
	"\t%1$s restart [-d] [<service> ...]\t- restart specified service(s)\n"
	"\t%1$s refresh [<service> ...]\t\t- re-read service configuration\n"
	"\t%1$s mark [-It] <state> [<service> ...] - set maintenance state\n"
	"\t%1$s clear [<service> ...]\t\t- clear maintenance state\n"
	"\t%1$s milestone [-d] <milestone>\t- advance to a service milestone\n"
	"\n\t"
	"Services can be specified using an FMRI, abbreviation, or fnmatch(5)\n"
	"\tpattern, as shown in these examples for svc:/network/smtp:sendmail\n"
	"\n"
	"\t%1$s <cmd> svc:/network/smtp:sendmail\n"
	"\t%1$s <cmd> network/smtp:sendmail\n"
	"\t%1$s <cmd> network/*mail\n"
	"\t%1$s <cmd> network/smtp\n"
	"\t%1$s <cmd> smtp:sendmail\n"
	"\t%1$s <cmd> smtp\n"
	"\t%1$s <cmd> sendmail\n"), uu_getpname());

	exit(UU_EXIT_USAGE);
}


/*
 * FMRI hash table for recursive enable.
 */

static uint32_t
hash_fmri(const char *str)
{
	uint32_t h = 0, g;
	const char *p;

	/* Generic hash function from uts/common/os/modhash.c . */
	for (p = str; *p != '\0'; ++p) {
		h = (h << 4) + *p;
		if ((g = (h & 0xf0000000)) != 0) {
			h ^= (g >> 24);
			h ^= g;
		}
	}

	return (h);
}

/*
 * Return 1 if str has been visited, 0 if it has not, and -1 if memory could not
 * be allocated.
 */
static int
visited_find_or_add(const char *str, struct ht_elt **hep)
{
	uint32_t h;
	uint_t i;
	struct ht_elt *he;

	h = hash_fmri(str);
	i = h & (HT_BUCKETS - 1);

	for (he = visited[i]; he != NULL; he = he->next) {
		if (strcmp(he->str, str) == 0) {
			if (hep)
				*hep = he;
			return (1);
		}
	}

	he = malloc(offsetof(struct ht_elt, str) + strlen(str) + 1);
	if (he == NULL)
		return (-1);

	(void) strcpy(he->str, str);

	he->next = visited[i];
	visited[i] = he;

	if (hep)
		*hep = he;
	return (0);
}


/*
 * Returns 0, ECANCELED if pg is deleted, ENOENT if propname doesn't exist,
 * EINVAL if the property is not of boolean type or has no values, and E2BIG
 * if it has more than one value.  *bp is set if 0 or E2BIG is returned.
 */
int
get_bool_prop(scf_propertygroup_t *pg, const char *propname, uint8_t *bp)
{
	scf_property_t *prop;
	scf_value_t *val;
	int ret;

	if ((prop = scf_property_create(h)) == NULL ||
	    (val = scf_value_create(h)) == NULL)
		scfdie();

	if (scf_pg_get_property(pg, propname, prop) != 0) {
		switch (scf_error()) {
		case SCF_ERROR_DELETED:
			ret = ECANCELED;
			goto out;

		case SCF_ERROR_NOT_FOUND:
			ret = ENOENT;
			goto out;

		case SCF_ERROR_NOT_SET:
			assert(0);
			abort();
			/* NOTREACHED */

		default:
			scfdie();
		}
	}

	if (scf_property_get_value(prop, val) == 0) {
		ret = 0;
	} else {
		switch (scf_error()) {
		case SCF_ERROR_DELETED:
			ret = ENOENT;
			goto out;

		case SCF_ERROR_NOT_FOUND:
			ret = EINVAL;
			goto out;

		case SCF_ERROR_CONSTRAINT_VIOLATED:
			ret = E2BIG;
			break;

		case SCF_ERROR_NOT_SET:
			assert(0);
			abort();
			/* NOTREACHED */

		default:
			scfdie();
		}
	}

	if (scf_value_get_boolean(val, bp) != 0) {
		if (scf_error() != SCF_ERROR_TYPE_MISMATCH)
			scfdie();

		ret = EINVAL;
		goto out;
	}

out:
	scf_value_destroy(val);
	scf_property_destroy(prop);
	return (ret);
}

/*
 * Returns 0, EPERM, or EROFS.
 */
static int
set_bool_prop(scf_propertygroup_t *pg, const char *propname, boolean_t b)
{
	scf_value_t *v;
	scf_transaction_t *tx;
	scf_transaction_entry_t *ent;
	int ret = 0, r;

	if ((tx = scf_transaction_create(h)) == NULL ||
	    (ent = scf_entry_create(h)) == NULL ||
	    (v = scf_value_create(h)) == NULL)
		scfdie();

	scf_value_set_boolean(v, b);

	for (;;) {
		if (scf_transaction_start(tx, pg) == -1) {
			switch (scf_error()) {
			case SCF_ERROR_PERMISSION_DENIED:
				ret = EPERM;
				goto out;

			case SCF_ERROR_BACKEND_READONLY:
				ret = EROFS;
				goto out;

			default:
				scfdie();
			}
		}

		if (scf_transaction_property_change_type(tx, ent, propname,
		    SCF_TYPE_BOOLEAN) != 0) {
			if (scf_error() != SCF_ERROR_NOT_FOUND)
				scfdie();

			if (scf_transaction_property_new(tx, ent, propname,
			    SCF_TYPE_BOOLEAN) != 0)
				scfdie();
		}

		r = scf_entry_add_value(ent, v);
		assert(r == 0);

		r = scf_transaction_commit(tx);
		if (r == 1)
			break;

		scf_transaction_reset(tx);

		if (r != 0) {
			switch (scf_error()) {
			case SCF_ERROR_PERMISSION_DENIED:
				ret = EPERM;
				goto out;

			case SCF_ERROR_BACKEND_READONLY:
				ret = EROFS;
				goto out;

			default:
				scfdie();
			}
		}

		if (scf_pg_update(pg) == -1)
			scfdie();
	}

out:
	scf_transaction_destroy(tx);
	scf_entry_destroy(ent);
	scf_value_destroy(v);
	return (ret);
}

/*
 * Gets the single astring value of the propname property of pg.  prop & v are
 * scratch space.  Returns the length of the string on success or
 *   -ENOENT - pg has no property named propname
 *   -E2BIG - property has no values or multiple values
 *   -EINVAL - property type is not compatible with astring
 */
ssize_t
get_astring_prop(const scf_propertygroup_t *pg, const char *propname,
    scf_property_t *prop, scf_value_t *v, char *buf, size_t bufsz)
{
	ssize_t sz;

	if (scf_pg_get_property(pg, propname, prop) != 0) {
		if (scf_error() != SCF_ERROR_NOT_FOUND)
			scfdie();

		return (-ENOENT);
	}

	if (scf_property_get_value(prop, v) != 0) {
		switch (scf_error()) {
		case SCF_ERROR_NOT_FOUND:
		case SCF_ERROR_CONSTRAINT_VIOLATED:
			return (-E2BIG);

		default:
			scfdie();
		}
	}

	sz = scf_value_get_astring(v, buf, bufsz);
	if (sz < 0) {
		if (scf_error() != SCF_ERROR_TYPE_MISMATCH)
			scfdie();

		return (-EINVAL);
	}

	return (sz);
}

/*
 * Returns 0 or EPERM.
 */
static int
pg_get_or_add(const scf_instance_t *inst, const char *pgname,
    const char *pgtype, uint32_t pgflags, scf_propertygroup_t *pg)
{
again:
	if (scf_instance_get_pg(inst, pgname, pg) == 0)
		return (0);

	if (scf_error() != SCF_ERROR_NOT_FOUND)
		scfdie();

	if (scf_instance_add_pg(inst, pgname, pgtype, pgflags, pg) == 0)
		return (0);

	switch (scf_error()) {
	case SCF_ERROR_EXISTS:
		goto again;

	case SCF_ERROR_PERMISSION_DENIED:
		return (EPERM);

	default:
		scfdie();
		/* NOTREACHED */
	}
}

static int
my_ct_name(char *out, size_t len)
{
	ct_stathdl_t st;
	char *ct_fmri;
	ctid_t ct;
	int fd, errno, ret;

	if ((ct = getctid()) == -1)
		uu_die(gettext("Could not get contract id for process"));

	fd = contract_open(ct, "process", "status", O_RDONLY);

	if ((errno = ct_status_read(fd, CTD_ALL, &st)) != 0)
		uu_warn(gettext("Could not read status of contract "
		    "%ld: %s.\n"), ct, strerror(errno));

	if ((errno = ct_pr_status_get_svc_fmri(st, &ct_fmri)) != 0)
		uu_warn(gettext("Could not get svc_fmri for contract "
		    "%ld: %s.\n"), ct, strerror(errno));

	ret = strlcpy(out, ct_fmri, len);

	ct_status_free(st);
	(void) close(fd);

	return (ret);
}

/*
 * Set auxiliary_tty and auxiliary_fmri properties in restarter_actions pg to
 * communicate whether the action is requested from a tty and the fmri of the
 * responsible process.
 *
 * Returns 0, EPERM, or EROFS
 */
static int
restarter_setup(const char *fmri, const scf_instance_t *inst)
{
	boolean_t b = B_FALSE;
	scf_propertygroup_t *pg = NULL;
	int ret = 0;

	if ((pg = scf_pg_create(h)) == NULL)
		scfdie();

	if (pg_get_or_add(inst, SCF_PG_RESTARTER_ACTIONS,
	    SCF_PG_RESTARTER_ACTIONS_TYPE, SCF_PG_RESTARTER_ACTIONS_FLAGS,
	    pg) == EPERM) {
		if (!verbose)
			uu_warn(emsg_permission_denied, fmri);
		else
			uu_warn(emsg_create_pg_perm_denied, fmri,
			    SCF_PG_RESTARTER_ACTIONS);

		ret = EPERM;
		goto out;
	}

	/* Set auxiliary_tty property */
	if (isatty(STDIN_FILENO))
		b = B_TRUE;

	/* Create and set state to disabled */
	switch (set_bool_prop(pg, SCF_PROPERTY_AUX_TTY, b)) {
	case 0:
		break;

	case EPERM:
		if (!verbose)
			uu_warn(emsg_permission_denied, fmri);
		else
			uu_warn(emsg_prop_perm_denied, fmri,
			    SCF_PG_RESTARTER_ACTIONS, SCF_PROPERTY_AUX_TTY);

		ret = EPERM;
		goto out;
		/* NOTREACHED */

	case EROFS:
		/* Shouldn't happen, but it can. */
		if (!verbose)
			uu_warn(gettext("%s: Repository read-only.\n"), fmri);
		else
			uu_warn(gettext("%s: Could not set %s/%s "
			    "(repository read-only).\n"), fmri,
			    SCF_PG_RESTARTER_ACTIONS, SCF_PROPERTY_AUX_TTY);

		ret = EROFS;
		goto out;
		/* NOTREACHED */

	default:
		scfdie();
	}

	if (my_ct_name(scratch_fmri, max_scf_fmri_sz) > 0) {
		set_astring_prop(fmri, SCF_PG_RESTARTER_ACTIONS,
		    SCF_PG_RESTARTER_ACTIONS_TYPE,
		    SCF_PG_RESTARTER_ACTIONS_FLAGS,
		    SCF_PROPERTY_AUX_FMRI, scratch_fmri);
	} else {
		uu_warn(gettext("%s: Could not set %s/%s: "
		    "my_ct_name failed.\n"), fmri,
		    SCF_PG_RESTARTER_ACTIONS, SCF_PROPERTY_AUX_FMRI);
	}

out:
	scf_pg_destroy(pg);
	return (ret);
}

static int
delete_prop(const char *fmri, scf_instance_t *inst, const char *pgname,
    const char *propname)
{
	int r = scf_instance_delete_prop(inst, pgname, propname);

	switch (r) {
	case 0:
		break;

	case ECANCELED:
		uu_warn(emsg_no_service, fmri);
		break;

	case EACCES:
		uu_warn(gettext("Could not delete %s/%s "
		    "property of %s: backend access denied.\n"),
		    pgname, propname, fmri);
		break;

	case EROFS:
		uu_warn(gettext("Could not delete %s/%s "
		    "property of %s: backend is read-only.\n"),
		    pgname, propname, fmri);
		break;

	default:
		bad_error("scf_instance_delete_prop", r);
	}

	return (r);
}

/*
 * Returns 0, EPERM, or EROFS.
 */
static int
set_enabled_props(scf_propertygroup_t *pg, enable_data_t *ed)
{
	scf_transaction_entry_t *ent1;
	scf_transaction_entry_t *ent2;
	scf_transaction_t *tx;
	scf_value_t *v2;
	scf_value_t *v1;
	int ret = 0, r;

	if ((tx = scf_transaction_create(h)) == NULL ||
	    (ent1 = scf_entry_create(h)) == NULL ||
	    (ent2 = scf_entry_create(h)) == NULL ||
	    (v1 = scf_value_create(h)) == NULL ||
	    (v2 = scf_value_create(h)) == NULL)
		scfdie();

	for (;;) {
		if (scf_transaction_start(tx, pg) == -1) {
			switch (scf_error()) {
			case SCF_ERROR_PERMISSION_DENIED:
				ret = EPERM;
				goto out;

			case SCF_ERROR_BACKEND_READONLY:
				ret = EROFS;
				goto out;

			default:
				scfdie();
			}
		}

		if (scf_transaction_property_change_type(tx, ent1,
		    SCF_PROPERTY_ENABLED, SCF_TYPE_BOOLEAN) != 0) {
			if (scf_error() != SCF_ERROR_NOT_FOUND)
				scfdie();

			if (scf_transaction_property_new(tx, ent1,
			    SCF_PROPERTY_ENABLED, SCF_TYPE_BOOLEAN) != 0)
				scfdie();
		}

		scf_value_set_boolean(v1, !!(ed->ed_flags & SET_ENABLED));

		r = scf_entry_add_value(ent1, v1);
		assert(r == 0);

		if (scf_transaction_property_change_type(tx, ent2,
		    SCF_PROPERTY_COMMENT, SCF_TYPE_ASTRING) != 0) {
			if (scf_error() != SCF_ERROR_NOT_FOUND)
				scfdie();

			if (scf_transaction_property_new(tx, ent2,
			    SCF_PROPERTY_COMMENT, SCF_TYPE_ASTRING) != 0)
				scfdie();
		}

		if (scf_value_set_astring(v2, ed->ed_comment) != SCF_SUCCESS)
			scfdie();

		if (scf_entry_add_value(ent2, v2) != SCF_SUCCESS)
			scfdie();

		r = scf_transaction_commit(tx);
		if (r == 1)
			break;

		scf_transaction_reset(tx);

		if (r != 0) {
			switch (scf_error()) {
			case SCF_ERROR_PERMISSION_DENIED:
				ret = EPERM;
				goto out;

			case SCF_ERROR_BACKEND_READONLY:
				ret = EROFS;
				goto out;

			default:
				scfdie();
			}
		}

		if (scf_pg_update(pg) == -1)
			scfdie();
	}

out:
	scf_transaction_destroy(tx);
	scf_entry_destroy(ent1);
	scf_entry_destroy(ent2);
	scf_value_destroy(v1);
	scf_value_destroy(v2);
	return (ret);
}

/*
 * Enable or disable an instance.  SET_TEMPORARY modifications apply to
 * general_ovr/ property group.
 */
static void
set_inst_enabled(const char *fmri, scf_instance_t *inst, enable_data_t *ed)
{
	scf_propertygroup_t *pg;
	uint8_t b;
	const char *pgname = NULL;	/* For emsg_pg_perm_denied */

	pg = scf_pg_create(h);
	if (pg == NULL)
		scfdie();

	if (restarter_setup(fmri, inst))
		goto out;

	/*
	 * An instance's configuration is incomplete if general/enabled
	 * doesn't exist. Create both the property group and property
	 * here if they don't exist.
	 */
	pgname = SCF_PG_GENERAL;
	if (pg_get_or_add(inst, pgname, SCF_PG_GENERAL_TYPE,
	    SCF_PG_GENERAL_FLAGS, pg) != 0)
		goto eperm;

	if (get_bool_prop(pg, SCF_PROPERTY_ENABLED, &b) != 0) {
		/* Create and set state to disabled */
		switch (set_bool_prop(pg, SCF_PROPERTY_ENABLED, B_FALSE)) {
		case 0:
			break;

		case EPERM:
			goto eperm;

		case EROFS:
			/* Shouldn't happen, but it can. */
			if (!verbose)
				uu_warn(gettext("%s: Repository read-only.\n"),
				    fmri);
			else
				uu_warn(gettext("%s: Could not set %s/%s "
				    "(repository read-only).\n"), fmri,
				    SCF_PG_GENERAL, SCF_PROPERTY_ENABLED);
			goto out;

		default:
			assert(0);
			abort();
		}
	}

	if (ed->ed_flags & SET_TEMPORARY) {
		pgname = SCF_PG_GENERAL_OVR;
		if (pg_get_or_add(inst, pgname, SCF_PG_GENERAL_OVR_TYPE,
		    SCF_PG_GENERAL_OVR_FLAGS, pg) != 0)
			goto eperm;

		switch (set_enabled_props(pg, ed)) {
		case 0:
			break;

		case EPERM:
			goto eperm;

		case EROFS:
			/* Shouldn't happen, but it can. */
			if (!verbose)
				uu_warn(gettext("%s: Repository read-only.\n"),
				    fmri);
			else
				uu_warn(gettext("%s: Could not set %s/%s "
				    "(repository read-only).\n"), fmri,
				    SCF_PG_GENERAL_OVR, SCF_PROPERTY_ENABLED);
			goto out;

		default:
			assert(0);
			abort();
		}

		if (verbose)
			(void) printf((ed->ed_flags & SET_ENABLED) ?
			    gettext("%s temporarily enabled.\n") :
			    gettext("%s temporarily disabled.\n"), fmri);
	} else {
again:
		/*
		 * Both pg and property should exist since we created
		 * them earlier. However, there's still a chance that
		 * someone may have deleted the property out from under
		 * us.
		 */
		if (pg_get_or_add(inst, pgname, SCF_PG_GENERAL_TYPE,
		    SCF_PG_GENERAL_FLAGS, pg) != 0)
			goto eperm;

		switch (set_enabled_props(pg, ed)) {
		case 0:
			break;

		case EPERM:
			goto eperm;

		case EROFS:
			/*
			 * If general/enabled is already set the way we want,
			 * proceed.
			 */
			switch (get_bool_prop(pg, SCF_PROPERTY_ENABLED, &b)) {
			case 0:
				if (!(b) == !(ed->ed_flags & SET_ENABLED))
					break;
				/* FALLTHROUGH */

			case ENOENT:
			case EINVAL:
			case E2BIG:
				if (!verbose)
					uu_warn(gettext("%s: Repository "
					    "read-only.\n"), fmri);
				else
					uu_warn(gettext("%s: Could not set "
					    "%s/%s (repository read-only).\n"),
					    fmri, SCF_PG_GENERAL,
					    SCF_PROPERTY_ENABLED);
				goto out;

			case ECANCELED:
				goto again;

			default:
				assert(0);
				abort();
			}
			break;

		default:
			assert(0);
			abort();
		}

		switch (delete_prop(fmri, inst, SCF_PG_GENERAL_OVR,
		    SCF_PROPERTY_ENABLED)) {
		case 0:
			break;

		case EPERM:
			goto eperm;

		default:
			goto out;
		}

		switch (delete_prop(fmri, inst, SCF_PG_GENERAL_OVR,
		    SCF_PROPERTY_COMMENT)) {
		case 0:
			break;

		case EPERM:
			goto eperm;

		default:
			goto out;
		}

		if (verbose) {
			(void) printf((ed->ed_flags & SET_ENABLED) ?
			    gettext("%s enabled.\n") :
			    gettext("%s disabled.\n"), fmri);
		}
	}

	scf_pg_destroy(pg);
	return;

eperm:
	assert(pgname != NULL);
	if (!verbose)
		uu_warn(emsg_permission_denied, fmri);
	else
		uu_warn(emsg_pg_perm_denied, fmri, pgname);

out:
	scf_pg_destroy(pg);
	exit_status = 1;
}

/*
 * Set inst to the instance which corresponds to fmri.  If fmri identifies
 * a service with a single instance, get that instance.
 *
 * Fails with
 *   ENOTSUP - fmri has an unsupported scheme
 *   EINVAL - fmri is invalid
 *   ENOTDIR - fmri does not identify a service or instance
 *   ENOENT - could not locate instance
 *   E2BIG - fmri is a service with multiple instances (warning not printed)
 */
static int
get_inst_mult(const char *fmri, scf_instance_t *inst)
{
	char *cfmri;
	const char *svc_name, *inst_name, *pg_name;
	scf_service_t *svc;
	scf_instance_t *inst2;
	scf_iter_t *iter;
	int ret;

	if (strncmp(fmri, "lrc:", sizeof ("lrc:") - 1) == 0) {
		uu_warn(gettext("FMRI \"%s\" is a legacy service.\n"), fmri);
		exit_status = 1;
		return (ENOTSUP);
	}

	cfmri = strdup(fmri);
	if (cfmri == NULL)
		uu_die(emsg_nomem);

	if (scf_parse_svc_fmri(cfmri, NULL, &svc_name, &inst_name, &pg_name,
	    NULL) != SCF_SUCCESS) {
		free(cfmri);
		uu_warn(gettext("FMRI \"%s\" is invalid.\n"), fmri);
		exit_status = 1;
		return (EINVAL);
	}

	free(cfmri);

	if (svc_name == NULL || pg_name != NULL) {
		uu_warn(gettext(
		    "FMRI \"%s\" does not designate a service or instance.\n"),
		    fmri);
		exit_status = 1;
		return (ENOTDIR);
	}

	if (inst_name != NULL) {
		if (scf_handle_decode_fmri(h, fmri, NULL, NULL, inst, NULL,
		    NULL, SCF_DECODE_FMRI_EXACT) == 0)
			return (0);

		if (scf_error() != SCF_ERROR_NOT_FOUND)
			scfdie();

		uu_warn(gettext("No such instance \"%s\".\n"), fmri);
		exit_status = 1;

		return (ENOENT);
	}

	if ((svc = scf_service_create(h)) == NULL ||
	    (inst2 = scf_instance_create(h)) == NULL ||
	    (iter = scf_iter_create(h)) == NULL)
		scfdie();

	if (scf_handle_decode_fmri(h, fmri, NULL, svc, NULL, NULL, NULL,
	    SCF_DECODE_FMRI_EXACT) != SCF_SUCCESS) {
		if (scf_error() != SCF_ERROR_NOT_FOUND)
			scfdie();

		uu_warn(emsg_no_service, fmri);
		exit_status = 1;

		ret = ENOENT;
		goto out;
	}

	/* If the service has only one child, use it. */
	if (scf_iter_service_instances(iter, svc) != SCF_SUCCESS)
		scfdie();

	ret = scf_iter_next_instance(iter, inst);
	if (ret < 0)
		scfdie();
	if (ret != 1) {
		uu_warn(gettext("Service \"%s\" has no instances.\n"),
		    fmri);
		exit_status = 1;
		ret = ENOENT;
		goto out;
	}

	ret = scf_iter_next_instance(iter, inst2);
	if (ret < 0)
		scfdie();

	if (ret != 0) {
		ret = E2BIG;
		goto out;
	}

	ret = 0;

out:
	scf_iter_destroy(iter);
	scf_instance_destroy(inst2);
	scf_service_destroy(svc);
	return (ret);
}

/*
 * Same as get_inst_mult(), but on E2BIG prints a warning and returns ENOENT.
 */
static int
get_inst(const char *fmri, scf_instance_t *inst)
{
	int r;

	r = get_inst_mult(fmri, inst);
	if (r != E2BIG)
		return (r);

	uu_warn(gettext("operation on service %s is ambiguous; "
	    "instance specification needed.\n"), fmri);
	return (ENOENT);
}

static char *
inst_get_fmri(const scf_instance_t *inst)
{
	ssize_t sz;

	sz = scf_instance_to_fmri(inst, scratch_fmri, max_scf_fmri_sz);
	if (sz < 0)
		scfdie();
	if (sz >= max_scf_fmri_sz)
		uu_die(gettext("scf_instance_to_fmri() returned unexpectedly "
		    "long value.\n"));

	return (scratch_fmri);
}

static ssize_t
dep_get_astring(const char *fmri, const char *pgname,
    const scf_propertygroup_t *pg, const char *propname, scf_property_t *prop,
    scf_value_t *v, char *buf, size_t bufsz)
{
	ssize_t sz;

	sz = get_astring_prop(pg, propname, prop, v, buf, bufsz);
	if (sz >= 0)
		return (sz);

	switch (-sz) {
	case ENOENT:
		uu_warn(gettext("\"%s\" is misconfigured (\"%s\" dependency "
		    "lacks \"%s\" property.)\n"), fmri, pgname, propname);
		return (-1);

	case E2BIG:
		uu_warn(gettext("\"%s\" is misconfigured (\"%s/%s\" property "
		    "is not single-valued.)\n"), fmri, pgname, propname);
		return (-1);

	case EINVAL:
		uu_warn(gettext("\"%s\" is misconfigured (\"%s/%s\" property "
		    "is not of astring type.)\n"), fmri, pgname, propname);
		return (-1);

	default:
		assert(0);
		abort();
		/* NOTREACHED */
	}
}

static boolean_t
multiple_instances(scf_iter_t *iter, scf_value_t *v, char *buf)
{
	int count = 0, r;
	boolean_t ret;
	scf_instance_t *inst;

	inst = scf_instance_create(h);
	if (inst == NULL)
		scfdie();

	for (;;) {
		r = scf_iter_next_value(iter, v);
		if (r == 0) {
			ret = B_FALSE;
			goto out;
		}
		if (r != 1)
			scfdie();

		if (scf_value_get_astring(v, buf, max_scf_fmri_sz) < 0)
			scfdie();

		switch (get_inst_mult(buf, inst)) {
		case 0:
			++count;
			if (count > 1) {
				ret = B_TRUE;
				goto out;
			}
			break;

		case ENOTSUP:
		case EINVAL:
		case ENOTDIR:
		case ENOENT:
			continue;

		case E2BIG:
			ret = B_TRUE;
			goto out;

		default:
			assert(0);
			abort();
		}
	}

out:
	scf_instance_destroy(inst);
	return (ret);
}

/*
 * Enable the service or instance identified by fmri and its dependencies,
 * recursively.  Specifically, call get_inst(fmri), enable the result, and
 * recurse on its restarter and the dependencies.  To avoid duplication of
 * effort or looping around a dependency cycle, each FMRI is entered into the
 * "visited" hash table.  While recursing, the hash table entry is marked
 * "active", so that if we come upon it again, we know we've hit a cycle.
 * exclude_all and optional_all dependencies are ignored.  require_any
 * dependencies are followed only if they comprise a single service; otherwise
 * the user is warned.
 *
 * fmri must point to a writable max_scf_fmri_sz buffer.  Returns EINVAL if fmri
 * is invalid, E2BIG if fmri identifies a service with multiple instances, ELOOP
 * on cycle detection, or 0 on success.
 */
static int
enable_fmri_rec(char *fmri, enable_data_t *ed)
{
	scf_instance_t *inst;
	scf_snapshot_t *snap;
	scf_propertygroup_t *pg;
	scf_property_t *prop;
	scf_value_t *v;
	scf_iter_t *pg_iter, *val_iter;
	scf_type_t ty;
	char *buf, *pgname;
	ssize_t name_sz, len, sz;
	int ret;
	struct ht_elt *he;

	len = scf_canonify_fmri(fmri, fmri, max_scf_fmri_sz);
	if (len < 0) {
		assert(scf_error() == SCF_ERROR_INVALID_ARGUMENT);
		return (EINVAL);
	}
	assert(len < max_scf_fmri_sz);

	switch (visited_find_or_add(fmri, &he)) {
	case 0:
		he->active = B_TRUE;
		break;

	case 1:
		return (he->active ? ELOOP : 0);

	case -1:
		uu_die(emsg_nomem);

	default:
		assert(0);
		abort();
	}

	inst = scf_instance_create(h);
	if (inst == NULL)
		scfdie();

	switch (get_inst_mult(fmri, inst)) {
	case 0:
		break;

	case E2BIG:
		he->active = B_FALSE;
		return (E2BIG);

	default:
		he->active = B_FALSE;
		return (0);
	}

	set_inst_enabled(fmri, inst, ed);

	if ((snap = scf_snapshot_create(h)) == NULL ||
	    (pg = scf_pg_create(h)) == NULL ||
	    (prop = scf_property_create(h)) == NULL ||
	    (v = scf_value_create(h)) == NULL ||
	    (pg_iter = scf_iter_create(h)) == NULL ||
	    (val_iter = scf_iter_create(h)) == NULL)
		scfdie();

	buf = malloc(max_scf_fmri_sz);
	if (buf == NULL)
		uu_die(emsg_nomem);

	name_sz = scf_limit(SCF_LIMIT_MAX_NAME_LENGTH);
	if (name_sz < 0)
		scfdie();
	++name_sz;
	pgname = malloc(name_sz);
	if (pgname == NULL)
		uu_die(emsg_nomem);

	if (scf_instance_get_snapshot(inst, "running", snap) != 0) {
		if (scf_error() != SCF_ERROR_NOT_FOUND)
			scfdie();

		scf_snapshot_destroy(snap);
		snap = NULL;
	}

	/* Enable restarter */
	if (scf_instance_get_pg_composed(inst, snap, SCF_PG_GENERAL, pg) != 0) {
		if (scf_error() != SCF_ERROR_NOT_FOUND)
			scfdie();

		uu_warn(gettext("\"%s\" is misconfigured (lacks \"%s\" "
		    "property group).\n"), fmri, SCF_PG_GENERAL);
		ret = 0;
		goto out;
	}

	sz = get_astring_prop(pg, SCF_PROPERTY_RESTARTER, prop, v, buf,
	    max_scf_fmri_sz);
	if (sz > max_scf_fmri_sz) {
		uu_warn(gettext("\"%s\" is misconfigured (the value of "
		    "\"%s/%s\" is too long).\n"), fmri, SCF_PG_GENERAL,
		    SCF_PROPERTY_RESTARTER);
		ret = 0;
		goto out;
	} else if (sz >= 0) {
		switch (enable_fmri_rec(buf, ed)) {
		case 0:
			break;

		case EINVAL:
			uu_warn(gettext("Restarter FMRI for \"%s\" is "
			    "invalid.\n"), fmri);
			break;

		case E2BIG:
			uu_warn(gettext("Restarter FMRI for \"%s\" identifies "
			    "a service with multiple instances.\n"), fmri);
			break;

		case ELOOP:
			ret = ELOOP;
			goto out;

		default:
			assert(0);
			abort();
		}
	} else if (sz < 0) {
		switch (-sz) {
		case ENOENT:
			break;

		case E2BIG:
			uu_warn(gettext("\"%s\" is misconfigured (\"%s/%s\" "
			    "property is not single-valued).\n"), fmri,
			    SCF_PG_GENERAL, SCF_PROPERTY_RESTARTER);
			ret = 0;
			goto out;

		case EINVAL:
			uu_warn(gettext("\"%s\" is misconfigured (\"%s/%s\" "
			    "property is not of astring type).\n"), fmri,
			    SCF_PG_GENERAL, SCF_PROPERTY_RESTARTER);
			ret = 0;
			goto out;

		default:
			assert(0);
			abort();
		}
	}

	if (scf_iter_instance_pgs_typed_composed(pg_iter, inst, snap,
	    SCF_GROUP_DEPENDENCY) == -1)
		scfdie();

	while (scf_iter_next_pg(pg_iter, pg) > 0) {
		len = scf_pg_get_name(pg, pgname, name_sz);
		if (len < 0)
			scfdie();
		assert(len < name_sz);

		if (dep_get_astring(fmri, pgname, pg, SCF_PROPERTY_TYPE, prop,
		    v, buf, max_scf_fmri_sz) < 0)
			continue;

		if (strcmp(buf, "service") != 0)
			continue;

		if (dep_get_astring(fmri, pgname, pg, SCF_PROPERTY_GROUPING,
		    prop, v, buf, max_scf_fmri_sz) < 0)
			continue;

		if (strcmp(buf, SCF_DEP_EXCLUDE_ALL) == 0 ||
		    strcmp(buf, SCF_DEP_OPTIONAL_ALL) == 0)
			continue;

		if (strcmp(buf, SCF_DEP_REQUIRE_ALL) != 0 &&
		    strcmp(buf, SCF_DEP_REQUIRE_ANY) != 0) {
			uu_warn(gettext("Dependency \"%s\" of \"%s\" has "
			    "unknown type \"%s\".\n"), pgname, fmri, buf);
			continue;
		}

		if (scf_pg_get_property(pg, SCF_PROPERTY_ENTITIES, prop) ==
		    -1) {
			if (scf_error() != SCF_ERROR_NOT_FOUND)
				scfdie();

			uu_warn(gettext("\"%s\" is misconfigured (\"%s\" "
			    "dependency lacks \"%s\" property.)\n"), fmri,
			    pgname, SCF_PROPERTY_ENTITIES);
			continue;
		}

		if (scf_property_type(prop, &ty) != SCF_SUCCESS)
			scfdie();

		if (ty != SCF_TYPE_FMRI) {
			uu_warn(gettext("\"%s\" is misconfigured (property "
			    "\"%s/%s\" is not of fmri type).\n"), fmri, pgname,
			    SCF_PROPERTY_ENTITIES);
			continue;
		}

		if (scf_iter_property_values(val_iter, prop) == -1)
			scfdie();

		if (strcmp(buf, SCF_DEP_REQUIRE_ANY) == 0) {
			if (multiple_instances(val_iter, v, buf)) {
				(void) printf(gettext("%s requires one of:\n"),
				    fmri);

				if (scf_iter_property_values(val_iter, prop) !=
				    0)
					scfdie();

				for (;;) {
					int r;

					r = scf_iter_next_value(val_iter, v);
					if (r == 0)
						break;
					if (r != 1)
						scfdie();

					if (scf_value_get_astring(v, buf,
					    max_scf_fmri_sz) < 0)
						scfdie();

					(void) fputs("  ", stdout);
					(void) puts(buf);
				}

				continue;
			}

			/*
			 * Since there's only one instance, we can enable it.
			 * Reset val_iter and continue.
			 */
			if (scf_iter_property_values(val_iter, prop) != 0)
				scfdie();
		}

		for (;;) {
			ret = scf_iter_next_value(val_iter, v);
			if (ret == 0)
				break;
			if (ret != 1)
				scfdie();

			if (scf_value_get_astring(v, buf, max_scf_fmri_sz) ==
			    -1)
				scfdie();

			switch (enable_fmri_rec(buf, ed)) {
			case 0:
				break;

			case EINVAL:
				uu_warn(gettext("\"%s\" dependency of \"%s\" "
				    "has invalid FMRI \"%s\".\n"), pgname,
				    fmri, buf);
				break;

			case E2BIG:
				uu_warn(gettext("%s depends on %s, which has "
				    "multiple instances.\n"), fmri, buf);
				break;

			case ELOOP:
				ret = ELOOP;
				goto out;

			default:
				assert(0);
				abort();
			}
		}
	}

	ret = 0;

out:
	he->active = B_FALSE;

	free(buf);
	free(pgname);

	(void) scf_value_destroy(v);
	scf_property_destroy(prop);
	scf_pg_destroy(pg);
	scf_snapshot_destroy(snap);
	scf_iter_destroy(pg_iter);
	scf_iter_destroy(val_iter);

	return (ret);
}

/*
 * fmri here is only used for verbose messages.
 */
static void
set_inst_action(const char *fmri, const scf_instance_t *inst,
    const char *action)
{
	scf_transaction_t *tx;
	scf_transaction_entry_t *ent;
	scf_propertygroup_t *pg;
	scf_property_t *prop;
	scf_value_t *v;
	int ret;
	int64_t t;
	hrtime_t timestamp;

	const char * const scf_pg_restarter_actions = SCF_PG_RESTARTER_ACTIONS;

	if ((pg = scf_pg_create(h)) == NULL ||
	    (prop = scf_property_create(h)) == NULL ||
	    (v = scf_value_create(h)) == NULL ||
	    (tx = scf_transaction_create(h)) == NULL ||
	    (ent = scf_entry_create(h)) == NULL)
		scfdie();

	if (restarter_setup(fmri, inst)) {
		exit_status = 1;
		goto out;
	}

	if (scf_instance_get_pg(inst, scf_pg_restarter_actions, pg) == -1) {
		if (scf_error() != SCF_ERROR_NOT_FOUND)
			scfdie();

		/* Try creating the restarter_actions property group. */
		if (scf_instance_add_pg(inst, scf_pg_restarter_actions,
		    SCF_PG_RESTARTER_ACTIONS_TYPE,
		    SCF_PG_RESTARTER_ACTIONS_FLAGS, pg) == -1) {
			switch (scf_error()) {
			case SCF_ERROR_EXISTS:
				/* Someone must have added it. */
				break;

			case SCF_ERROR_PERMISSION_DENIED:
				if (!verbose)
					uu_warn(emsg_permission_denied, fmri);
				else
					uu_warn(emsg_create_pg_perm_denied,
					    fmri, scf_pg_restarter_actions);
				goto out;

			default:
				scfdie();
			}
		}
	}

	/*
	 * If we lose the transaction race and need to retry, there are 2
	 * potential other winners:
	 *	- another process setting actions
	 *	- the restarter marking the action complete
	 * Therefore, re-read the property every time through the loop before
	 * making any decisions based on their values.
	 */
	do {
		timestamp = gethrtime();

		if (scf_transaction_start(tx, pg) == -1) {
			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
				scfdie();

			if (!verbose)
				uu_warn(emsg_permission_denied, fmri);
			else
				uu_warn(emsg_pg_perm_denied, fmri,
				    scf_pg_restarter_actions);
			goto out;
		}

		if (scf_pg_get_property(pg, action, prop) == -1) {
			if (scf_error() != SCF_ERROR_NOT_FOUND)
				scfdie();
			if (scf_transaction_property_new(tx, ent,
			    action, SCF_TYPE_INTEGER) == -1)
				scfdie();
			goto action_set;
		} else {
			if (scf_transaction_property_change_type(tx, ent,
			    action, SCF_TYPE_INTEGER) == -1)
				scfdie();
		}

		if (scf_property_get_value(prop, v) == -1) {
			switch (scf_error()) {
			case SCF_ERROR_CONSTRAINT_VIOLATED:
			case SCF_ERROR_NOT_FOUND:
				/* Misconfigured, so set anyway. */
				goto action_set;

			default:
				scfdie();
			}
		} else {
			if (scf_value_get_integer(v, &t) == -1) {
				assert(scf_error() == SCF_ERROR_TYPE_MISMATCH);
				goto action_set;
			}
			if (t > timestamp)
				break;
		}

action_set:
		scf_value_set_integer(v, timestamp);
		if (scf_entry_add_value(ent, v) == -1)
			scfdie();

		ret = scf_transaction_commit(tx);
		if (ret == -1) {
			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
				scfdie();

			if (!verbose)
				uu_warn(emsg_permission_denied, fmri);
			else
				uu_warn(emsg_prop_perm_denied, fmri,
				    scf_pg_restarter_actions, action);
			scf_transaction_reset(tx);
			goto out;
		}

		scf_transaction_reset(tx);

		if (ret == 0) {
			if (scf_pg_update(pg) == -1)
				scfdie();
		}
	} while (ret == 0);

	if (verbose)
		(void) printf(gettext("Action %s set for %s.\n"), action, fmri);

out:
	scf_value_destroy(v);
	scf_entry_destroy(ent);
	scf_transaction_destroy(tx);
	scf_property_destroy(prop);
	scf_pg_destroy(pg);
}

/*
 * Get the state of inst.  state should point to a buffer of
 * MAX_SCF_STATE_STRING_SZ bytes.  Returns 0 on success or -1 if
 *   no restarter property group
 *   no state property
 *   state property is misconfigured (wrong type, not single-valued)
 *   state value is too long
 * In these cases, fmri is used to print a warning.
 *
 * If pgp is non-NULL, a successful call to inst_get_state will store
 * the SCF_PG_RESTARTER property group in *pgp, and the caller will be
 * responsible for calling scf_pg_destroy on the property group.
 */
int
inst_get_state(scf_instance_t *inst, char *state, const char *fmri,
    scf_propertygroup_t **pgp)
{
	scf_propertygroup_t *pg;
	scf_property_t *prop;
	scf_value_t *val;
	int ret = -1;
	ssize_t szret;

	if ((pg = scf_pg_create(h)) == NULL ||
	    (prop = scf_property_create(h)) == NULL ||
	    (val = scf_value_create(h)) == NULL)
		scfdie();

	if (scf_instance_get_pg(inst, SCF_PG_RESTARTER, pg) != SCF_SUCCESS) {
		if (scf_error() != SCF_ERROR_NOT_FOUND)
			scfdie();

		uu_warn(gettext("%s is misconfigured (lacks \"%s\" property "
		    "group).\n"), fmri ? fmri : inst_get_fmri(inst),
		    SCF_PG_RESTARTER);
		goto out;
	}

	szret = get_astring_prop(pg, SCF_PROPERTY_STATE, prop, val, state,
	    MAX_SCF_STATE_STRING_SZ);
	if (szret < 0) {
		switch (-szret) {
		case ENOENT:
			uu_warn(gettext("%s is misconfigured (\"%s\" property "
			    "group lacks \"%s\" property).\n"),
			    fmri ? fmri : inst_get_fmri(inst), SCF_PG_RESTARTER,
			    SCF_PROPERTY_STATE);
			goto out;

		case E2BIG:
			uu_warn(gettext("%s is misconfigured (\"%s/%s\" "
			    "property is not single-valued).\n"),
			    fmri ? fmri : inst_get_fmri(inst), SCF_PG_RESTARTER,
			    SCF_PROPERTY_STATE);
			goto out;

		case EINVAL:
			uu_warn(gettext("%s is misconfigured (\"%s/%s\" "
			    "property is not of type astring).\n"),
			    fmri ? fmri : inst_get_fmri(inst), SCF_PG_RESTARTER,
			    SCF_PROPERTY_STATE);
			goto out;

		default:
			assert(0);
			abort();
		}
	}
	if (szret >= MAX_SCF_STATE_STRING_SZ) {
		uu_warn(gettext("%s is misconfigured (\"%s/%s\" property value "
		    "is too long).\n"), fmri ? fmri : inst_get_fmri(inst),
		    SCF_PG_RESTARTER, SCF_PROPERTY_STATE);
		goto out;
	}

	ret = 0;
	if (pgp)
		*pgp = pg;

out:
	(void) scf_value_destroy(val);
	scf_property_destroy(prop);
	if (ret || pgp == NULL)
		scf_pg_destroy(pg);
	return (ret);
}

static void
set_astring_prop(const char *fmri, const char *pgname, const char *pgtype,
    uint32_t pgflags, const char *propname, const char *str)
{
	scf_instance_t *inst;
	scf_propertygroup_t *pg;
	scf_property_t *prop;
	scf_value_t *val;
	scf_transaction_t *tx;
	scf_transaction_entry_t *txent;
	int ret;

	inst = scf_instance_create(h);
	if (inst == NULL)
		scfdie();

	if (get_inst(fmri, inst) != 0)
		return;

	if ((pg = scf_pg_create(h)) == NULL ||
	    (prop = scf_property_create(h)) == NULL ||
	    (val = scf_value_create(h)) == NULL ||
	    (tx = scf_transaction_create(h)) == NULL ||
	    (txent = scf_entry_create(h)) == NULL)
		scfdie();

	if (scf_instance_get_pg(inst, pgname, pg) != SCF_SUCCESS) {
		if (scf_error() != SCF_ERROR_NOT_FOUND)
			scfdie();

		if (scf_instance_add_pg(inst, pgname, pgtype, pgflags, pg) !=
		    SCF_SUCCESS) {
			switch (scf_error()) {
			case SCF_ERROR_EXISTS:
				if (scf_instance_get_pg(inst, pgname, pg) !=
				    SCF_SUCCESS) {
					if (scf_error() != SCF_ERROR_NOT_FOUND)
						scfdie();

					uu_warn(gettext("Repository write "
					    "contention.\n"));
					goto out;
				}
				break;

			case SCF_ERROR_PERMISSION_DENIED:
				if (!verbose)
					uu_warn(emsg_permission_denied, fmri);
				else
					uu_warn(emsg_create_pg_perm_denied,
					    fmri, pgname);
				goto out;

			default:
				scfdie();
			}
		}
	}

	do {
		if (scf_transaction_start(tx, pg) != SCF_SUCCESS) {
			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
				scfdie();

			if (!verbose)
				uu_warn(emsg_permission_denied, fmri);
			else
				uu_warn(emsg_pg_perm_denied, fmri, pgname);
			goto out;
		}

		if (scf_transaction_property_change_type(tx, txent, propname,
		    SCF_TYPE_ASTRING) != 0) {
			if (scf_error() != SCF_ERROR_NOT_FOUND)
				scfdie();

			if (scf_transaction_property_new(tx, txent, propname,
			    SCF_TYPE_ASTRING) != 0)
				scfdie();
		}

		if (scf_value_set_astring(val, str) != SCF_SUCCESS)
			scfdie();

		if (scf_entry_add_value(txent, val) != SCF_SUCCESS)
			scfdie();

		ret = scf_transaction_commit(tx);
		if (ret == -1) {
			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
				scfdie();

			if (!verbose)
				uu_warn(emsg_permission_denied, fmri);
			else
				uu_warn(emsg_prop_perm_denied, fmri, pgname,
				    propname);
			goto out;
		}

		if (ret == 0) {
			scf_transaction_reset(tx);

			if (scf_pg_update(pg) == -1)
				scfdie();
		}
	} while (ret == 0);

out:
	scf_transaction_destroy(tx);
	scf_entry_destroy(txent);
	scf_value_destroy(val);
	scf_property_destroy(prop);
	scf_pg_destroy(pg);
	scf_instance_destroy(inst);
}


static int
set_fmri_enabled(void *data, scf_walkinfo_t *wip)
{
	enable_data_t *ed = data;

	assert(wip->inst != NULL);
	assert(wip->pg == NULL);

	if (svcsearch) {
		char state[MAX_SCF_STATE_STRING_SZ];

		if (inst_get_state(wip->inst, state, wip->fmri, NULL) != 0)
			return (0);
		if (strcmp(state, svcstate) != 0)
			return (0);
	}

	if (ed->ed_flags & SET_RECURSIVE) {
		char *fmri_buf = malloc(max_scf_fmri_sz);
		if (fmri_buf == NULL)
			uu_die(emsg_nomem);

		visited = calloc(HT_BUCKETS, sizeof (*visited));
		if (visited == NULL)
			uu_die(emsg_nomem);

		/* scf_walk_fmri() guarantees that fmri isn't too long */
		assert(strlen(wip->fmri) <= max_scf_fmri_sz);
		(void) strlcpy(fmri_buf, wip->fmri, max_scf_fmri_sz);

		switch (enable_fmri_rec(fmri_buf, ed)) {
		case E2BIG:
			uu_warn(gettext("operation on service %s is ambiguous; "
			    "instance specification needed.\n"), fmri_buf);
			break;

		case ELOOP:
			uu_warn(gettext("%s: Dependency cycle detected.\n"),
			    fmri_buf);
		}

		free(visited);
		free(fmri_buf);

	} else {
		set_inst_enabled(wip->fmri, wip->inst, ed);
	}

	return (0);
}

/* ARGSUSED */
static int
wait_fmri_enabled(void *data, scf_walkinfo_t *wip)
{
	scf_propertygroup_t *pg = NULL;
	char state[MAX_SCF_STATE_STRING_SZ];

	assert(wip->inst != NULL);
	assert(wip->pg == NULL);

	do {
		if (pg)
			scf_pg_destroy(pg);
		if (inst_get_state(wip->inst, state, wip->fmri, &pg) != 0) {
			exit_status = EXIT_SVC_FAILURE;
			return (0);
		}

		if (strcmp(state, SCF_STATE_STRING_ONLINE) == 0 ||
		    strcmp(state, SCF_STATE_STRING_DEGRADED) == 0) {
			/*
			 * We're done.
			 */
			goto out;
		}

		if (strcmp(state, SCF_STATE_STRING_MAINT) == 0) {
			/*
			 * The service is ill.
			 */
			uu_warn(gettext("Instance \"%s\" is in maintenance"
			    " state.\n"), wip->fmri);
			exit_status = EXIT_SVC_FAILURE;
			goto out;
		}

		if (!is_enabled(wip->inst)) {
			/*
			 * Someone stepped in and disabled the service.
			 */
			uu_warn(gettext("Instance \"%s\" has been disabled"
			    " by another entity.\n"), wip->fmri);
			exit_status = EXIT_SVC_FAILURE;
			goto out;
		}

		if (!has_potential(wip->inst, B_FALSE)) {
			/*
			 * Our dependencies aren't met.  We'll never
			 * amount to anything.
			 */
			uu_warn(gettext("Instance \"%s\" has unsatisfied"
			    " dependencies.\n"), wip->fmri);
			/*
			 * EXIT_SVC_FAILURE takes precedence over
			 * EXIT_DEP_FAILURE
			 */
			if (exit_status == 0)
				exit_status = EXIT_DEP_FAILURE;
			goto out;
		}
	} while (_scf_pg_wait(pg, WAIT_INTERVAL) >= 0);
	scfdie();
	/* NOTREACHED */

out:
	scf_pg_destroy(pg);
	return (0);
}

/* ARGSUSED */
static int
wait_fmri_disabled(void *data, scf_walkinfo_t *wip)
{
	scf_propertygroup_t *pg = NULL;
	char state[MAX_SCF_STATE_STRING_SZ];

	assert(wip->inst != NULL);
	assert(wip->pg == NULL);

	do {
		if (pg)
			scf_pg_destroy(pg);
		if (inst_get_state(wip->inst, state, wip->fmri, &pg) != 0) {
			exit_status = EXIT_SVC_FAILURE;
			return (0);
		}

		if (strcmp(state, SCF_STATE_STRING_DISABLED) == 0) {
			/*
			 * We're done.
			 */
			goto out;
		}

		if (is_enabled(wip->inst)) {
			/*
			 * Someone stepped in and enabled the service.
			 */
			uu_warn(gettext("Instance \"%s\" has been enabled"
			    " by another entity.\n"), wip->fmri);
			exit_status = EXIT_SVC_FAILURE;
			goto out;
		}

		if (!has_potential(wip->inst, B_TRUE)) {
			/*
			 * Our restarter is hopeless.
			 */
			uu_warn(gettext("Restarter for instance \"%s\" is"
			    " unavailable.\n"), wip->fmri);
			/*
			 * EXIT_SVC_FAILURE takes precedence over
			 * EXIT_DEP_FAILURE
			 */
			if (exit_status == 0)
				exit_status = EXIT_DEP_FAILURE;
			goto out;
		}

	} while (_scf_pg_wait(pg, WAIT_INTERVAL) >= 0);
	scfdie();
	/* NOTREACHED */

out:
	scf_pg_destroy(pg);
	return (0);
}

/* ARGSUSED */
static int
clear_instance(void *data, scf_walkinfo_t *wip)
{
	char state[MAX_SCF_STATE_STRING_SZ];

	assert(wip->inst != NULL);
	assert(wip->pg == NULL);

	if (inst_get_state(wip->inst, state, wip->fmri, NULL) != 0)
		return (0);

	if (svcsearch && strcmp(state, svcstate) != 0)
		return (0);

	if (strcmp(state, SCF_STATE_STRING_MAINT) == 0) {
		set_inst_action(wip->fmri, wip->inst, SCF_PROPERTY_MAINT_OFF);
	} else if (strcmp(state, SCF_STATE_STRING_DEGRADED) ==
	    0) {
		set_inst_action(wip->fmri, wip->inst, SCF_PROPERTY_RESTORE);
	} else {
		uu_warn(gettext("Instance \"%s\" is not in a "
		    "maintenance or degraded state.\n"), wip->fmri);

		exit_status = 1;
	}

	return (0);
}

static int
set_fmri_action(void *action, scf_walkinfo_t *wip)
{
	assert(wip->inst != NULL && wip->pg == NULL);

	if (svcsearch) {
		char state[MAX_SCF_STATE_STRING_SZ];

		if (inst_get_state(wip->inst, state, wip->fmri, NULL) != 0)
			return (0);
		if (strcmp(state, svcstate) != 0)
			return (0);
	}

	set_inst_action(wip->fmri, wip->inst, action);

	return (0);
}

/*
 * Flags to control 'mark' action.
 */
#define	MARK_IMMEDIATE	0x1
#define	MARK_TEMPORARY	0x2

static int
force_degraded(void *data, scf_walkinfo_t *wip)
{
	int flags = (int)data;
	char state[MAX_SCF_STATE_STRING_SZ];

	if (inst_get_state(wip->inst, state, wip->fmri, NULL) != 0) {
		exit_status = 1;
		return (0);
	}

	if (svcsearch && strcmp(state, svcstate) != 0)
		return (0);

	if (strcmp(state, SCF_STATE_STRING_ONLINE) != 0) {
		uu_warn(gettext("Instance \"%s\" is not online.\n"), wip->fmri);
		exit_status = 1;
		return (0);
	}

	set_inst_action(wip->fmri, wip->inst, (flags & MARK_IMMEDIATE) ?
	    SCF_PROPERTY_DEGRADE_IMMEDIATE : SCF_PROPERTY_DEGRADED);

	return (0);
}

static int
force_maintenance(void *data, scf_walkinfo_t *wip)
{
	int flags = (int)data;
	const char *prop;

	if (svcsearch) {
		char state[MAX_SCF_STATE_STRING_SZ];

		if (inst_get_state(wip->inst, state, wip->fmri, NULL) != 0)
			return (0);
		if (strcmp(state, svcstate) != 0)
			return (0);
	}

	if (flags & MARK_IMMEDIATE) {
		prop = (flags & MARK_TEMPORARY) ?
		    SCF_PROPERTY_MAINT_ON_IMMTEMP :
		    SCF_PROPERTY_MAINT_ON_IMMEDIATE;
	} else {
		prop = (flags & MARK_TEMPORARY) ?
		    SCF_PROPERTY_MAINT_ON_TEMPORARY :
		    SCF_PROPERTY_MAINT_ON;
	}

	set_inst_action(wip->fmri, wip->inst, prop);

	return (0);
}

static void
set_milestone(const char *fmri, boolean_t temporary)
{
	scf_instance_t *inst;
	scf_propertygroup_t *pg;

	if (temporary) {
		set_astring_prop(SCF_SERVICE_STARTD, SCF_PG_OPTIONS_OVR,
		    SCF_PG_OPTIONS_OVR_TYPE, SCF_PG_OPTIONS_OVR_FLAGS,
		    SCF_PROPERTY_MILESTONE, fmri);
		return;
	}

	if ((inst = scf_instance_create(h)) == NULL ||
	    (pg = scf_pg_create(h)) == NULL)
		scfdie();

	if (get_inst(SCF_SERVICE_STARTD, inst) != 0) {
		scf_instance_destroy(inst);
		return;
	}

	/*
	 * Set the persistent milestone before deleting the override so we don't
	 * glitch.
	 */
	set_astring_prop(SCF_SERVICE_STARTD, SCF_PG_OPTIONS,
	    SCF_PG_OPTIONS_TYPE, SCF_PG_OPTIONS_FLAGS, SCF_PROPERTY_MILESTONE,
	    fmri);

	if (delete_prop(SCF_SERVICE_STARTD, inst, SCF_PG_OPTIONS_OVR,
	    SCF_PROPERTY_MILESTONE) != 0)
		exit_status = 1;

	scf_pg_destroy(pg);
	scf_instance_destroy(inst);
}

static char const *milestones[] = {
	SCF_MILESTONE_SINGLE_USER,
	SCF_MILESTONE_MULTI_USER,
	SCF_MILESTONE_MULTI_USER_SERVER,
	NULL
};

static void
usage_milestone(void)
{
	const char **ms;

	(void) fprintf(stderr, gettext(
	"Usage: svcadm milestone [-d] <milestone>\n\n"
	"\t-d\tmake the specified milestone the default for system boot\n\n"
	"\tMilestones can be specified using an FMRI or abbreviation.\n"
	"\tThe major milestones are as follows:\n\n"
	"\tall\n"
	"\tnone\n"));

	for (ms = milestones; *ms != NULL; ms++)
		(void) fprintf(stderr, "\t%s\n", *ms);

	exit(UU_EXIT_USAGE);
}

static const char *
validate_milestone(const char *milestone)
{
	const char **ms;
	const char *tmp;
	size_t len;

	if (strcmp(milestone, "all") == 0)
		return (milestone);

	if (strcmp(milestone, "none") == 0)
		return (milestone);

	/*
	 * Determine if this is a full or partial milestone
	 */
	for (ms = milestones; *ms != NULL; ms++) {
		if ((tmp = strstr(*ms, milestone)) != NULL) {
			len = strlen(milestone);

			/*
			 * The beginning of the string must align with the start
			 * of a milestone fmri, or on the boundary between
			 * elements.  The end of the string must align with the
			 * end of the milestone, or at the instance boundary.
			 */
			if ((tmp == *ms || tmp[-1] == '/') &&
			    (tmp[len] == '\0' || tmp[len] == ':'))
				return (*ms);
		}
	}

	(void) fprintf(stderr,
	    gettext("\"%s\" is not a valid major milestone.\n"), milestone);

	usage_milestone();
	/* NOTREACHED */
}

/*PRINTFLIKE1*/
static void
pr_warn(const char *format, ...)
{
	const char *pname = uu_getpname();
	va_list alist;

	va_start(alist, format);

	if (pname != NULL)
		(void) fprintf(stderr, "%s", pname);

	if (g_zonename != NULL)
		(void) fprintf(stderr, " (%s)", g_zonename);

	(void) fprintf(stderr, ": ");

	(void) vfprintf(stderr, format, alist);

	if (strrchr(format, '\n') == NULL)
		(void) fprintf(stderr, ": %s\n", strerror(errno));

	va_end(alist);
}

/*ARGSUSED*/
static void
quiet(const char *fmt, ...)
{
	/* Do nothing */
}

int
main(int argc, char *argv[])
{
	int o;
	int err;
	int sw_back;
	boolean_t do_zones = B_FALSE;
	boolean_t do_a_zone = B_FALSE;
	char zonename[ZONENAME_MAX];
	uint_t nzents = 0, zent = 0;
	zoneid_t *zids = NULL;
	int orig_optind, orig_argc;
	char **orig_argv;

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

	(void) uu_setpname(argv[0]);

	if (argc < 2)
		usage();

	max_scf_fmri_sz = scf_limit(SCF_LIMIT_MAX_FMRI_LENGTH);
	if (max_scf_fmri_sz < 0)
		scfdie();
	++max_scf_fmri_sz;

	scratch_fmri = malloc(max_scf_fmri_sz);
	if (scratch_fmri == NULL)
		uu_die(emsg_nomem);

	while ((o = getopt(argc, argv, "S:vZz:")) != -1) {
		switch (o) {
		case 'S':
			(void) strlcpy(svcstate, optarg, sizeof (svcstate));
			svcsearch = B_TRUE;
			break;

		case 'v':
			verbose = 1;
			break;

		case 'z':
			if (getzoneid() != GLOBAL_ZONEID)
				uu_die(gettext("svcadm -z may only be used "
				    "from the global zone\n"));
			if (do_zones)
				usage();

			(void) strlcpy(zonename, optarg, sizeof (zonename));
			do_a_zone = B_TRUE;
			break;

		case 'Z':
			if (getzoneid() != GLOBAL_ZONEID)
				uu_die(gettext("svcadm -Z may only be used "
				    "from the global zone\n"));
			if (do_a_zone)
				usage();

			do_zones = B_TRUE;
			break;

		default:
			usage();
		}
	}

	while (do_zones) {
		uint_t found;

		if (zone_list(NULL, &nzents) != 0)
			uu_die(gettext("could not get number of zones"));

		if ((zids = malloc(nzents * sizeof (zoneid_t))) == NULL) {
			uu_die(gettext("could not allocate array for "
			    "%d zone IDs"), nzents);
		}

		found = nzents;

		if (zone_list(zids, &found) != 0)
			uu_die(gettext("could not get zone list"));

		/*
		 * If the number of zones has not changed between our calls to
		 * zone_list(), we're done -- otherwise, we must free our array
		 * of zone IDs and take another lap.
		 */
		if (found == nzents)
			break;

		free(zids);
	}

	emsg_permission_denied = gettext("%s: Permission denied.\n");
	emsg_nomem = gettext("Out of memory.\n");
	emsg_create_pg_perm_denied = gettext("%s: Couldn't create \"%s\" "
	    "property group (permission denied).\n");
	emsg_pg_perm_denied = gettext("%s: Couldn't modify \"%s\" property "
	    "group (permission denied).\n");
	emsg_prop_perm_denied = gettext("%s: Couldn't modify \"%s/%s\" "
	    "property (permission denied).\n");
	emsg_no_service = gettext("No such service \"%s\".\n");

	orig_optind = optind;
	orig_argc = argc;
	orig_argv = argv;

again:
	h = scf_handle_create(SCF_VERSION);
	if (h == NULL)
		scfdie();

	if (do_zones) {
		zone_status_t status;

		if (zone_getattr(zids[zent], ZONE_ATTR_STATUS, &status,
		    sizeof (status)) < 0 || status != ZONE_IS_RUNNING) {
			/*
			 * If this zone is not running or we cannot
			 * get its status, we do not want to attempt
			 * to bind an SCF handle to it, lest we
			 * accidentally interfere with a zone that
			 * is not yet running by looking up a door
			 * to its svc.configd (which could potentially
			 * block a mount with an EBUSY).
			 */
			zent++;
			goto nextzone;
		}

		if (getzonenamebyid(zids[zent++], zonename,
		    sizeof (zonename)) < 0) {
			uu_warn(gettext("could not get name for "
			    "zone %d; ignoring"), zids[zent - 1]);
			goto nextzone;
		}

		g_zonename = zonename;
	}

	if (do_a_zone || do_zones) {
		scf_value_t *zone;

		if ((zone = scf_value_create(h)) == NULL)
			scfdie();

		if (scf_value_set_astring(zone, zonename) != SCF_SUCCESS)
			scfdie();

		if (scf_handle_decorate(h, "zone", zone) != SCF_SUCCESS) {
			if (do_a_zone) {
				uu_die(gettext("invalid zone '%s'\n"), optarg);
			} else {
				scf_value_destroy(zone);
				goto nextzone;
			}
		}

		scf_value_destroy(zone);
	}

	if (scf_handle_bind(h) == -1) {
		if (do_zones)
			goto nextzone;

		uu_die(gettext("Couldn't bind to configuration repository: "
		    "%s.\n"), scf_strerror(scf_error()));
	}

	optind = orig_optind;
	argc = orig_argc;
	argv = orig_argv;

	if (optind >= argc)
		usage();

	if (strcmp(argv[optind], "enable") == 0) {
		enable_data_t ed = {
			.ed_flags = SET_ENABLED,
			.ed_comment = ""
		};
		int wait = 0;
		int error = 0;

		++optind;

		while ((o = getopt(argc, argv, "rst")) != -1) {
			if (o == 'r')
				ed.ed_flags |= SET_RECURSIVE;
			else if (o == 't')
				ed.ed_flags |= SET_TEMPORARY;
			else if (o == 's')
				wait = 1;
			else if (o == '?')
				usage();
			else {
				assert(0);
				abort();
			}
		}
		argc -= optind;
		argv += optind;

		if (argc == 0 && !svcsearch)
			usage();

		if (argc > 0 && svcsearch)
			usage();

		/*
		 * We want to continue with -s processing if we had
		 * invalid options, but not if an enable failed.  We
		 * squelch output the second time we walk fmris; we saw
		 * the errors the first time.
		 */
		if ((err = scf_walk_fmri(h, argc, argv, WALK_FLAGS,
		    set_fmri_enabled, &ed, &error, pr_warn)) != 0) {

			pr_warn(gettext("failed to iterate over "
			    "instances: %s\n"), scf_strerror(err));
			exit_status = UU_EXIT_FATAL;

		} else if (wait && exit_status == 0 &&
		    (err = scf_walk_fmri(h, argc, argv, WALK_FLAGS,
		    wait_fmri_enabled, NULL, &error, quiet)) != 0) {

			pr_warn(gettext("failed to iterate over "
			    "instances: %s\n"), scf_strerror(err));
			exit_status = UU_EXIT_FATAL;
		}

		if (error > 0)
			exit_status = error;

	} else if (strcmp(argv[optind], "disable") == 0) {
		enable_data_t ed = {
			.ed_flags = 0,
			.ed_comment = ""
		};
		int wait = 0;
		int error = 0;

		++optind;

		while ((o = getopt(argc, argv, "c:st")) != -1) {
			if (o == 'c') {
				if (strlcpy(ed.ed_comment, optarg,
				    sizeof (ed.ed_comment)) >=
				    sizeof (ed.ed_comment)) {
					uu_die(gettext("disable -c comment "
					    "too long.\n"));
				}
			} else if (o == 't')
				ed.ed_flags |= SET_TEMPORARY;
			else if (o == 's')
				wait = 1;
			else if (o == '?')
				usage();
			else {
				assert(0);
				abort();
			}
		}
		argc -= optind;
		argv += optind;

		if (argc == 0 && !svcsearch)
			usage();

		if (argc > 0 && svcsearch)
			usage();

		/*
		 * We want to continue with -s processing if we had
		 * invalid options, but not if a disable failed.  We
		 * squelch output the second time we walk fmris; we saw
		 * the errors the first time.
		 */
		if ((err = scf_walk_fmri(h, argc, argv, WALK_FLAGS,
		    set_fmri_enabled, &ed, &exit_status,
		    pr_warn)) != 0) {

			pr_warn(gettext("failed to iterate over "
			    "instances: %s\n"), scf_strerror(err));
			exit_status = UU_EXIT_FATAL;

		} else if (wait && exit_status == 0 &&
		    (err = scf_walk_fmri(h, argc, argv, WALK_FLAGS,
		    wait_fmri_disabled, NULL, &error, quiet)) != 0) {

			pr_warn(gettext("failed to iterate over "
			    "instances: %s\n"), scf_strerror(err));
			exit_status = UU_EXIT_FATAL;
		}

		if (error > 0)
			exit_status = error;

	} else if (strcmp(argv[optind], "restart") == 0) {
		boolean_t do_dump = B_FALSE;

		++optind;

		while ((o = getopt(argc, argv, "d")) != -1) {
			if (o == 'd')
				do_dump = B_TRUE;
			else if (o == '?')
				usage();
			else {
				assert(0);
				abort();
			}
		}
		argc -= optind;
		argv += optind;

		if (argc == 0 && !svcsearch)
			usage();

		if (argc > 0 && svcsearch)
			usage();

		if (do_dump) {
			if ((err = scf_walk_fmri(h, argc, argv, WALK_FLAGS,
			    set_fmri_action, (void *)SCF_PROPERTY_DODUMP,
			    &exit_status, pr_warn)) != 0) {
				pr_warn(gettext("failed to iterate over "
				    "instances: %s\n"), scf_strerror(err));
				exit_status = UU_EXIT_FATAL;
			}
		}

		if ((err = scf_walk_fmri(h, argc, argv, WALK_FLAGS,
		    set_fmri_action, (void *)SCF_PROPERTY_RESTART, &exit_status,
		    pr_warn)) != 0) {
			pr_warn(gettext("failed to iterate over "
			    "instances: %s\n"), scf_strerror(err));
			exit_status = UU_EXIT_FATAL;
		}

	} else if (strcmp(argv[optind], "refresh") == 0) {
		++optind;
		argc -= optind;
		argv += optind;

		if (argc == 0 && !svcsearch)
			usage();

		if (argc > 0 && svcsearch)
			usage();

		if ((err = scf_walk_fmri(h, argc, argv, WALK_FLAGS,
		    set_fmri_action, (void *)SCF_PROPERTY_REFRESH, &exit_status,
		    pr_warn)) != 0) {
			pr_warn(gettext("failed to iterate over "
			    "instances: %s\n"), scf_strerror(scf_error()));
			exit_status = UU_EXIT_FATAL;
		}

	} else if (strcmp(argv[optind], "mark") == 0) {
		int flags = 0;
		scf_walk_callback callback;

		++optind;

		while ((o = getopt(argc, argv, "It")) != -1) {
			if (o == 'I')
				flags |= MARK_IMMEDIATE;
			else if (o == 't')
				flags |= MARK_TEMPORARY;
			else if (o == '?')
				usage();
			else {
				assert(0);
				abort();
			}
		}

		if (argc - optind < 2)
			usage();

		if (strcmp(argv[optind], "degraded") == 0) {
			if (flags & MARK_TEMPORARY)
				uu_xdie(UU_EXIT_USAGE, gettext("-t may not be "
				    "used with degraded.\n"));
			callback = force_degraded;

		} else if (strcmp(argv[optind], "maintenance") == 0) {
			callback = force_maintenance;
		} else {
			usage();
		}

		optind++;
		argc -= optind;
		argv += optind;

		if (argc == 0 && !svcsearch)
			usage();

		if (argc > 0 && svcsearch)
			usage();

		if ((err = scf_walk_fmri(h, argc, argv, WALK_FLAGS, callback,
		    NULL, &exit_status, pr_warn)) != 0) {
			pr_warn(gettext("failed to iterate over "
			    "instances: %s\n"),
			    scf_strerror(err));
			exit_status = UU_EXIT_FATAL;
		}

	} else if (strcmp(argv[optind], "clear") == 0) {
		++optind;
		argc -= optind;
		argv += optind;

		if (argc == 0 && !svcsearch)
			usage();

		if (svcsearch) {
			if (argc > 0)
				usage();
			if (strcmp(svcstate, SCF_STATE_STRING_MAINT) != 0 &&
			    strcmp(svcstate, SCF_STATE_STRING_DEGRADED) != 0)
				uu_die(gettext("State must be '%s' or '%s'\n"),
				    SCF_STATE_STRING_MAINT,
				    SCF_STATE_STRING_DEGRADED);
		}

		if ((err = scf_walk_fmri(h, argc, argv, WALK_FLAGS,
		    clear_instance, NULL, &exit_status, pr_warn)) != 0) {
			pr_warn(gettext("failed to iterate over "
			    "instances: %s\n"), scf_strerror(err));
			exit_status = UU_EXIT_FATAL;
		}

	} else if (strcmp(argv[optind], "milestone") == 0) {
		boolean_t temporary = B_TRUE;
		const char *milestone;

		++optind;

		while ((o = getopt(argc, argv, "d")) != -1) {
			if (o == 'd')
				temporary = B_FALSE;
			else if (o == '?')
				usage_milestone();
			else {
				assert(0);
				abort();
			}
		}

		if (optind >= argc)
			usage_milestone();

		milestone = validate_milestone(argv[optind]);

		set_milestone(milestone, temporary);
	} else if (strcmp(argv[optind], "_smf_backup") == 0) {
		const char *reason = NULL;

		++optind;

		if (optind != argc - 1)
			usage();

		if ((err = _scf_request_backup(h, argv[optind])) !=
		    SCF_SUCCESS) {
			switch (scf_error()) {
			case SCF_ERROR_NOT_BOUND:
			case SCF_ERROR_CONNECTION_BROKEN:
			case SCF_ERROR_BACKEND_READONLY:
				scfdie();
				break;

			case SCF_ERROR_PERMISSION_DENIED:
			case SCF_ERROR_INVALID_ARGUMENT:
				reason = scf_strerror(scf_error());
				break;

			case SCF_ERROR_INTERNAL:
				reason =
				    "unknown error (see console for details)";
				break;
			}

			pr_warn("failed to backup repository: %s\n", reason);
			exit_status = UU_EXIT_FATAL;
		}
	} else if (strcmp(argv[optind], "_smf_repository_switch") == 0) {
		const char *reason = NULL;

		++optind;

		/*
		 * Check argument and setup scf_switch structure
		 */
		if (optind != argc - 1)
			exit(1);

		if (strcmp(argv[optind], "fast") == 0) {
			sw_back = 0;
		} else if (strcmp(argv[optind], "perm") == 0) {
			sw_back = 1;
		} else {
			exit(UU_EXIT_USAGE);
		}

		/*
		 * Call into switch primitive
		 */
		if ((err = _scf_repository_switch(h, sw_back)) !=
		    SCF_SUCCESS) {
			/*
			 * Retrieve per thread SCF error code
			 */
			switch (scf_error()) {
			case SCF_ERROR_NOT_BOUND:
				abort();
				/* NOTREACHED */

			case SCF_ERROR_CONNECTION_BROKEN:
			case SCF_ERROR_BACKEND_READONLY:
				scfdie();
				/* NOTREACHED */

			case SCF_ERROR_PERMISSION_DENIED:
			case SCF_ERROR_INVALID_ARGUMENT:
				reason = scf_strerror(scf_error());
				break;

			case SCF_ERROR_INTERNAL:
				reason = "File operation error: (see console)";
				break;

			default:
				abort();
				/* NOTREACHED */
			}

			pr_warn("failed to switch repository: %s\n", reason);
			exit_status = UU_EXIT_FATAL;
		}
	} else {
		usage();
	}

	if (scf_handle_unbind(h) == -1)
		scfdie();
nextzone:
	scf_handle_destroy(h);
	if (do_zones && zent < nzents)
		goto again;

	return (exit_status);
}