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

/*
 * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
 * Copyright 2024 Oxide Computer Company
 */

#include <libintl.h>
#include <librestart.h>
#include <librestart_priv.h>
#include <libscf.h>
#include <libscf_priv.h>

#include <assert.h>
#include <ctype.h>
#include <dlfcn.h>
#include <errno.h>
#include <exec_attr.h>
#include <grp.h>
#include <libsysevent.h>
#include <libuutil.h>
#include <limits.h>
#include <link.h>
#include <malloc.h>
#include <pool.h>
#include <priv.h>
#include <project.h>
#include <pthread.h>
#include <pwd.h>
#include <secdb.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <sys/corectl.h>
#include <sys/machelf.h>
#include <sys/secflags.h>
#include <sys/task.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <ucontext.h>

#define	min(a, b)		((a) > (b) ? (b) : (a))

#define	MKW_TRUE	":true"
#define	MKW_KILL	":kill"
#define	MKW_KILL_PROC	":kill_process"

#define	ALLOCFAIL	((char *)"Allocation failure.")
#define	RCBROKEN	((char *)"Repository connection broken.")

#define	MAX_COMMIT_RETRIES		10
#define	MAX_COMMIT_RETRY_INT		(5 * 1000000)	/* 5 seconds */
#define	INITIAL_COMMIT_RETRY_INT	(10000)		/* 1/100th second */

/*
 * bad_fail() catches bugs in this and lower layers by reporting supposedly
 * impossible function failures.  The NDEBUG case keeps the strings out of the
 * library but still calls abort() so we can root-cause from the coredump.
 */
#ifndef NDEBUG
#define	bad_fail(func, err)	{					\
	(void) fprintf(stderr,						\
	    "At %s:%d, %s() failed with unexpected error %d.  Aborting.\n", \
	    __FILE__, __LINE__, (func), (err));				\
	abort();							\
}
#else
#define	bad_fail(func, err)	abort()
#endif

struct restarter_event_handle {
	char				*reh_restarter_name;
	char				*reh_delegate_channel_name;
	evchan_t			*reh_delegate_channel;
	char				*reh_delegate_subscriber_id;
	char				*reh_master_channel_name;
	evchan_t			*reh_master_channel;
	char				*reh_master_subscriber_id;
	int				(*reh_handler)(restarter_event_t *);
};

struct restarter_event {
	sysevent_t			*re_sysevent;
	restarter_event_type_t		re_type;
	char				*re_instance_name;
	restarter_event_handle_t	*re_event_handle;
	restarter_instance_state_t	re_state;
	restarter_instance_state_t	re_next_state;
};

/*
 * Long reasons must all parse/read correctly in the following contexts:
 *
 * "A service instance transitioned state: %s."
 * "A service failed: %s."
 * "Reason: %s."
 * "The service transitioned state (%s) and ..."
 *
 * With the exception of restart_str_none they must also fit the following
 * moulds:
 *
 * "An instance transitioned because %s, and ..."
 * "An instance transitioned to <new-state> because %s, and ..."
 *
 * Note that whoever is rendering the long message must provide the
 * terminal punctuation - don't include it here.  Similarly, do not
 * provide an initial capital letter in reason-long.
 *
 * The long reason strings are Volatile - within the grammatical constraints
 * above we may improve them as need be.  The intention is that a consumer
 * may blindly render the string along the lines of the above examples,
 * but has no other guarantees as to the exact wording.  Long reasons
 * are localized.
 *
 * We define revisions of the set of short reason strings in use.  Within
 * a given revision, all short reasons are Committed.  Consumers must check
 * the revision in use before relying on the semantics of the short reason
 * codes - if the version exceeds that which they are familiar with they should
 * fail gracefully.  Having checked for version compatability, a consumer
 * is assured that
 *
 *	"short_reason_A iff semantic_A", provided:
 *
 *		. the restarter uses this short reason code at all,
 *		. the short reason is not "none" (which a restarter could
 *		  specifiy for any transition semantics)
 *
 * To split/refine such a Committed semantic_A into further cases,
 * we are required to bump the revision number.  This should be an
 * infrequent occurence.  If you bump the revision number you may
 * need to make corresponding changes in any source that calls
 * restarter_str_version (e.g., FMA event generation).
 *
 * To add additional reasons to the set you must also bump the version
 * number.
 */

/*
 * The following describes revision 0 of the set of transition reasons.
 * Read the preceding block comment before making any changes.
 */
static const struct restarter_state_transition_reason restarter_str[] = {
	/*
	 * Any transition for which the restarter has not provided a reason.
	 */
	{
	    restarter_str_none,
	    "none",
	    "the restarter gave no reason"
	},

	/*
	 * A transition to maintenance state due to a
	 * 'svcadm mark maintenance <fmri>'.  *Not* used if the libscf
	 * interface smf_maintain_instance(3SCF) is used to request maintenance.
	 */
	{
	    restarter_str_administrative_request,
	    "administrative_request",
	    "maintenance was requested by an administrator"
	},

	/*
	 * A transition to maintenance state if a repository inconsistency
	 * exists when the service/instance state is first read by startd
	 * into the graph engine (this can also happen during startd restart).
	 */
	{
	    restarter_str_bad_repo_state,
	    "bad_repo_state",
	    "an SMF repository inconsistecy exists"
	},

	/*
	 * A transition 'maintenance -> uninitialized' resulting always
	 * from 'svcadm clear <fmri>'.  *Not* used if the libscf interface
	 * smf_restore_instance(3SCF) is used.
	 */
	{
	    restarter_str_clear_request,
	    "clear_request",
	    "maintenance clear was requested by an administrator"
	},

	/*
	 * A transition 'online -> offline' due to a process core dump.
	 */
	{
	    restarter_str_ct_ev_core,
	    "ct_ev_core",
	    "a process dumped core"
	},

	/*
	 * A transition 'online -> offline' due to an empty process contract,
	 * i.e., the last process in a contract type service has exited.
	 */
	{
	    restarter_str_ct_ev_exit,
	    "ct_ev_exit",
	    "all processes in the service have exited"
	},

	/*
	 * A transition 'online -> offline' due to a hardware error.
	 */
	{
	    restarter_str_ct_ev_hwerr,
	    "ct_ev_hwerr",
	    "a process was killed due to uncorrectable hardware error"
	},

	/*
	 * A transition 'online -> offline' due to a process in the service
	 * having received a fatal signal originating from outside the
	 * service process contract.
	 */
	{
	    restarter_str_ct_ev_signal,
	    "ct_ev_signal",
	    "a process received a fatal signal from outside the service"
	},

	/*
	 * A transition 'offline -> online' when all dependencies for the
	 * service have been met.
	 */
	{
	    restarter_str_dependencies_satisfied,
	    "dependencies_satisfied",
	    "all dependencies have been satisfied"
	},

	/*
	 * A transition 'online -> offline' because some dependency for the
	 * service is no-longer met.
	 */
	{
	    restarter_str_dependency_activity,
	    "dependency_activity",
	    "a dependency activity required a stop"
	},

	/*
	 * A transition to maintenance state due to a cycle in the
	 * service dependencies.
	 */
	{
	    restarter_str_dependency_cycle,
	    "dependency_cycle",
	    "a dependency cycle exists"
	},

	/*
	 * A transition 'online -> offline -> disabled' due to a
	 * 'svcadm disable [-t] <fmri>' or smf_disable_instance(3SCF) call.
	 */
	{
	    restarter_str_disable_request,
	    "disable_request",
	    "a disable was requested"
	},

	/*
	 * A transition 'disabled -> offline' due to a
	 * 'svcadm enable [-t] <fmri>' or smf_enable_instance(3SCF) call.
	 */
	{
	    restarter_str_enable_request,
	    "enable_request",
	    "an enable was requested"
	},

	/*
	 * A transition to maintenance state when a method fails
	 * repeatedly for a retryable reason.
	 */
	{
	    restarter_str_fault_threshold_reached,
	    "fault_threshold_reached",
	    "a method is failing in a retryable manner but too often"
	},

	/*
	 * A transition to uninitialized state when startd reads the service
	 * configuration and inserts it into the graph engine.
	 */
	{
	    restarter_str_insert_in_graph,
	    "insert_in_graph",
	    "the instance was inserted in the graph"
	},

	/*
	 * A transition to maintenance state due to an invalid dependency
	 * declared for the service.
	 */
	{
	    restarter_str_invalid_dependency,
	    "invalid_dependency",
	    "a service has an invalid dependency"
	},

	/*
	 * A transition to maintenance state because the service-declared
	 * restarter is invalid.
	 */
	{
	    restarter_str_invalid_restarter,
	    "invalid_restarter",
	    "the service restarter is invalid"
	},

	/*
	 * A transition to maintenance state because a restarter method
	 * exited with one of SMF_EXIT_ERR_CONFIG, SMF_EXIT_ERR_NOSMF,
	 * SMF_EXIT_ERR_PERM, or SMF_EXIT_ERR_FATAL.
	 */
	{
	    restarter_str_method_failed,
	    "method_failed",
	    "a start, stop or refresh method failed"
	},

	/*
	 * A transition 'uninitialized -> {disabled|offline}' after
	 * "insert_in_graph" to match the state configured in the
	 * repository.
	 */
	{
	    restarter_str_per_configuration,
	    "per_configuration",
	    "the SMF repository configuration specifies this state"
	},

	/*
	 * Refresh requested - no state change.
	 */
	{
	    restarter_str_refresh,
	    NULL,
	    "a refresh was requested (no change of state)"
	},

	/*
	 * A transition 'online -> offline -> online' due to a
	 * 'svcadm restart <fmri> or equivlaent libscf API call.
	 * Both the 'online -> offline' and 'offline -> online' transtions
	 * specify this reason.
	 */
	{
	    restarter_str_restart_request,
	    "restart_request",
	    "a restart was requested"
	},

	/*
	 * A transition to maintenance state because the start method is
	 * being executed successfully but too frequently.
	 */
	{
	    restarter_str_restarting_too_quickly,
	    "restarting_too_quickly",
	    "the instance is restarting too quickly"
	},

	/*
	 * A transition to maintenance state due a service requesting
	 * 'svcadm mark maintenance <fmri>' or equivalent libscf API call.
	 * A command line 'svcadm mark maintenance <fmri>' does not produce
	 * this reason - it produces administrative_request instead.
	 */
	{
	    restarter_str_service_request,
	    "service_request",
	    "maintenance was requested by another service"
	},

	/*
	 * An instanced inserted into the graph at its existing state
	 * during a startd restart - no state change.
	 */
	{
	    restarter_str_startd_restart,
	    NULL,
	    "the instance was inserted in the graph due to startd restart"
	}
};

uint32_t
restarter_str_version(void)
{
	return (RESTARTER_STRING_VERSION);
}

const char *
restarter_get_str_short(restarter_str_t key)
{
	int i;
	for (i = 0; i < sizeof (restarter_str) /
	    sizeof (struct restarter_state_transition_reason); i++)
		if (key == restarter_str[i].str_key)
			return (restarter_str[i].str_short);
	return (NULL);
}

const char *
restarter_get_str_long(restarter_str_t key)
{
	int i;
	for (i = 0; i < sizeof (restarter_str) /
	    sizeof (struct restarter_state_transition_reason); i++)
		if (key == restarter_str[i].str_key)
			return (dgettext(TEXT_DOMAIN,
			    restarter_str[i].str_long));
	return (NULL);
}

/*
 * A static no memory error message mc_error_t structure
 * to be used in cases when memory errors are to be returned
 * This avoids the need to attempt to allocate memory for the
 * message, therefore getting into a cycle of no memory failures.
 */
mc_error_t mc_nomem_err = {
	0, ENOMEM, sizeof ("Out of memory") - 1, "Out of memory"
};

static const char * const allocfail = "Allocation failure.\n";
static const char * const rcbroken = "Repository connection broken.\n";

static int method_context_safety = 0;	/* Can safely call pools/projects. */

int ndebug = 1;

/* PRINTFLIKE3 */
static mc_error_t *
mc_error_create(mc_error_t *e, int type, const char *format, ...)
{
	mc_error_t	*le;
	va_list		args;
	int		size;

	/*
	 * If the type is ENOMEM and format is NULL, then
	 * go ahead and return the default nomem error.
	 * Otherwise, attempt to allocate the memory and if
	 * that fails then there is no reason to continue.
	 */
	if (type == ENOMEM && format == NULL)
		return (&mc_nomem_err);

	if (e == NULL && (le = malloc(sizeof (mc_error_t))) == NULL)
		return (&mc_nomem_err);
	else
		le = e;

	le->type = type;
	le->destroy = 1;
	va_start(args, format);
	size = vsnprintf(NULL, 0, format, args) + 1;
	if (size >= RESTARTER_ERRMSGSZ) {
		if ((le = realloc(e, sizeof (mc_error_t) +
		    (size - RESTARTER_ERRMSGSZ))) == NULL) {
			size = RESTARTER_ERRMSGSZ - 1;
			le = e;
		}
	}

	le->size = size;
	(void) vsnprintf(le->msg, le->size, format, args);
	va_end(args);

	return (le);
}

void
restarter_mc_error_destroy(mc_error_t *mc_err)
{
	if (mc_err == NULL)
		return;

	/*
	 * If the error messages was allocated then free.
	 */
	if (mc_err->destroy) {
		free(mc_err);
	}
}

static void
free_restarter_event_handle(struct restarter_event_handle *h)
{
	if (h == NULL)
		return;

	/*
	 * Just free the memory -- don't unbind the sysevent handle,
	 * as otherwise events may be lost if this is just a restarter
	 * restart.
	 */

	if (h->reh_restarter_name != NULL)
		free(h->reh_restarter_name);
	if (h->reh_delegate_channel_name != NULL)
		free(h->reh_delegate_channel_name);
	if (h->reh_delegate_subscriber_id != NULL)
		free(h->reh_delegate_subscriber_id);
	if (h->reh_master_channel_name != NULL)
		free(h->reh_master_channel_name);
	if (h->reh_master_subscriber_id != NULL)
		free(h->reh_master_subscriber_id);

	free(h);
}

char *
_restarter_get_channel_name(const char *fmri, int type)
{
	char *name;
	char *chan_name = malloc(MAX_CHNAME_LEN);
	char prefix_name[3];
	int i;

	if (chan_name == NULL)
		return (NULL);

	if (type == RESTARTER_CHANNEL_DELEGATE)
		(void) strcpy(prefix_name, "d_");
	else if (type == RESTARTER_CHANNEL_MASTER)
		(void) strcpy(prefix_name, "m_");
	else {
		free(chan_name);
		return (NULL);
	}

	/*
	 * Create a unique name
	 *
	 * Use the entire name, using a replacement of the /
	 * characters to get a better name.
	 *
	 * Remove the svc:/ from the beginning as this really
	 * isn't going to provide any uniqueness...
	 *
	 * An fmri name greater than MAX_CHNAME_LEN is going
	 * to be rejected as too long for the chan_name below
	 * in the snprintf call.
	 */
	if ((name = strdup(strchr(fmri, '/') + 1)) == NULL) {
		free(chan_name);
		return (NULL);
	}
	i = 0;
	while (name[i]) {
		if (name[i] == '/') {
			name[i] = '_';
		}

		i++;
	}

	/*
	 * Should check for [a-z],[A-Z],[0-9],.,_,-,:
	 */

	if (snprintf(chan_name, MAX_CHNAME_LEN, "com.sun:scf:%s%s",
	    prefix_name, name) > MAX_CHNAME_LEN) {
		free(chan_name);
		chan_name = NULL;
	}

	free(name);
	return (chan_name);
}

int
cb(sysevent_t *syse, void *cookie)
{
	restarter_event_handle_t *h = (restarter_event_handle_t *)cookie;
	restarter_event_t *e;
	nvlist_t *attr_list = NULL;
	int ret = 0;

	e = uu_zalloc(sizeof (restarter_event_t));
	if (e == NULL)
		uu_die(allocfail);
	e->re_event_handle = h;
	e->re_sysevent = syse;

	if (sysevent_get_attr_list(syse, &attr_list) != 0)
		uu_die(allocfail);

	if ((nvlist_lookup_uint32(attr_list, RESTARTER_NAME_TYPE,
	    &(e->re_type)) != 0) ||
	    (nvlist_lookup_string(attr_list,
	    RESTARTER_NAME_INSTANCE, &(e->re_instance_name)) != 0)) {
		uu_warn("%s: Can't decode nvlist for event %p\n",
		    h->reh_restarter_name, (void *)syse);

		ret = 0;
	} else {
		ret = h->reh_handler(e);
	}

	uu_free(e);
	nvlist_free(attr_list);
	return (ret);
}

/*
 * restarter_bind_handle(uint32_t, char *, int (*)(restarter_event_t *), int,
 *     restarter_event_handle_t **)
 *
 * Bind to a delegated restarter event channel.
 * Each delegated restarter gets its own channel for resource management.
 *
 * Returns 0 on success or
 *   ENOTSUP	version mismatch
 *   EINVAL	restarter_name or event_handle is NULL
 *   ENOMEM	out of memory, too many channels, or too many subscriptions
 *   EBUSY	sysevent_evc_bind() could not establish binding
 *   EFAULT	internal sysevent_evc_bind()/sysevent_evc_subscribe() error
 *   EMFILE	out of file descriptors
 *   EPERM	insufficient privilege for sysevent_evc_bind()
 *   EEXIST	already subscribed
 */
int
restarter_bind_handle(uint32_t version, const char *restarter_name,
    int (*event_handler)(restarter_event_t *), int flags,
    restarter_event_handle_t **rehp)
{
	restarter_event_handle_t *h;
	size_t sz;
	int err;

	if (version != RESTARTER_EVENT_VERSION)
		return (ENOTSUP);

	if (restarter_name == NULL || event_handler == NULL)
		return (EINVAL);

	if (flags & RESTARTER_FLAG_DEBUG)
		ndebug++;

	if ((h = uu_zalloc(sizeof (restarter_event_handle_t))) == NULL)
		return (ENOMEM);

	h->reh_delegate_subscriber_id = malloc(MAX_SUBID_LEN);
	h->reh_master_subscriber_id = malloc(MAX_SUBID_LEN);
	h->reh_restarter_name = strdup(restarter_name);
	if (h->reh_delegate_subscriber_id == NULL ||
	    h->reh_master_subscriber_id == NULL ||
	    h->reh_restarter_name == NULL) {
		free_restarter_event_handle(h);
		return (ENOMEM);
	}

	sz = strlcpy(h->reh_delegate_subscriber_id, "del", MAX_SUBID_LEN);
	assert(sz < MAX_SUBID_LEN);
	sz = strlcpy(h->reh_master_subscriber_id, "master", MAX_SUBID_LEN);
	assert(sz < MAX_SUBID_LEN);

	h->reh_delegate_channel_name =
	    _restarter_get_channel_name(restarter_name,
	    RESTARTER_CHANNEL_DELEGATE);
	h->reh_master_channel_name =
	    _restarter_get_channel_name(restarter_name,
	    RESTARTER_CHANNEL_MASTER);

	if (h->reh_delegate_channel_name == NULL ||
	    h->reh_master_channel_name == NULL) {
		free_restarter_event_handle(h);
		return (ENOMEM);
	}

	if (sysevent_evc_bind(h->reh_delegate_channel_name,
	    &h->reh_delegate_channel, EVCH_CREAT|EVCH_HOLD_PEND) != 0) {
		err = errno;
		assert(err != EINVAL);
		assert(err != ENOENT);
		free_restarter_event_handle(h);
		return (err);
	}

	if (sysevent_evc_bind(h->reh_master_channel_name,
	    &h->reh_master_channel, EVCH_CREAT|EVCH_HOLD_PEND) != 0) {
		err = errno;
		assert(err != EINVAL);
		assert(err != ENOENT);
		free_restarter_event_handle(h);
		return (err);
	}

	h->reh_handler = event_handler;

	assert(strlen(restarter_name) <= MAX_CLASS_LEN - 1);
	assert(strlen(h->reh_delegate_subscriber_id) <= MAX_SUBID_LEN - 1);
	assert(strlen(h->reh_master_subscriber_id) <= MAX_SUBID_LEN - 1);

	if (sysevent_evc_subscribe(h->reh_delegate_channel,
	    h->reh_delegate_subscriber_id, EC_ALL, cb, h, EVCH_SUB_KEEP) != 0) {
		err = errno;
		assert(err != EINVAL);
		free_restarter_event_handle(h);
		return (err);
	}

	*rehp = h;
	return (0);
}

restarter_event_handle_t *
restarter_event_get_handle(restarter_event_t *e)
{
	assert(e != NULL && e->re_event_handle != NULL);
	return (e->re_event_handle);
}

restarter_event_type_t
restarter_event_get_type(restarter_event_t *e)
{
	assert(e != NULL);
	return (e->re_type);
}

ssize_t
restarter_event_get_instance(restarter_event_t *e, char *inst, size_t sz)
{
	assert(e != NULL && inst != NULL);
	return ((ssize_t)strlcpy(inst, e->re_instance_name, sz));
}

int
restarter_event_get_current_states(restarter_event_t *e,
    restarter_instance_state_t *state, restarter_instance_state_t *next_state)
{
	if (e == NULL)
		return (-1);
	*state = e->re_state;
	*next_state = e->re_next_state;
	return (0);
}

/*
 * restarter_event_publish_retry() is a wrapper around sysevent_evc_publish().
 * In case, the event cannot be sent at the first attempt (sysevent_evc_publish
 * returned EAGAIN - sysevent queue full), this function retries a few time
 * and return ENOSPC if it reaches the retry limit.
 *
 * The arguments to this function map the arguments of sysevent_evc_publish().
 *
 * On success, return 0. On error, return
 *
 *   EFAULT - internal sysevent_evc_publish() error
 *   ENOMEM - internal sysevent_evc_publish() error
 *   EBADF - scp is invalid (sysevent_evc_publish() returned EINVAL)
 *   ENOSPC - sysevent queue full (sysevent_evc_publish() returned EAGAIN)
 */
int
restarter_event_publish_retry(evchan_t *scp, const char *class,
    const char *subclass, const char *vendor, const char *pub_name,
    nvlist_t *attr_list, uint32_t flags)
{
	int retries, ret;
	useconds_t retry_int = INITIAL_COMMIT_RETRY_INT;

	for (retries = 0; retries < MAX_COMMIT_RETRIES; retries++) {
		ret = sysevent_evc_publish(scp, class, subclass, vendor,
		    pub_name, attr_list, flags);
		if (ret == 0)
			break;

		switch (ret) {
		case EAGAIN:
			/* Queue is full */
			(void) usleep(retry_int);

			retry_int = min(retry_int * 2, MAX_COMMIT_RETRY_INT);
			break;

		case EINVAL:
			ret = EBADF;
			/* FALLTHROUGH */

		case EFAULT:
		case ENOMEM:
			return (ret);

		case EOVERFLOW:
		default:
			/* internal error - abort */
			bad_fail("sysevent_evc_publish", ret);
		}
	}

	if (retries == MAX_COMMIT_RETRIES)
		ret = ENOSPC;

	return (ret);
}

/*
 * Commit the state, next state, and auxiliary state into the repository.
 * Let the graph engine know about the state change and error.  On success,
 * return 0. On error, return
 *   EPROTO - librestart compiled against different libscf
 *   ENOMEM - out of memory
 *	    - repository server out of resources
 *   ENOTACTIVE - repository server not running
 *   ECONNABORTED - repository connection established, but then broken
 *		  - unknown libscf error
 *   ENOENT - inst does not exist in the repository
 *   EPERM - insufficient permissions
 *   EACCESS - backend access denied
 *   EROFS - backend is readonly
 *   EFAULT - internal sysevent_evc_publish() error
 *   EBADF - h is invalid (sysevent_evc_publish() returned EINVAL)
 *   ENOSPC - sysevent queue full (sysevent_evc_publish() returned EAGAIN)
 */
int
restarter_set_states(restarter_event_handle_t *h, const char *inst,
    restarter_instance_state_t cur_state,
    restarter_instance_state_t new_cur_state,
    restarter_instance_state_t next_state,
    restarter_instance_state_t new_next_state, restarter_error_t e,
    restarter_str_t aux)
{
	nvlist_t *attr;
	scf_handle_t *scf_h;
	instance_data_t id;
	int ret = 0;
	const char *p = restarter_get_str_short(aux);

	assert(h->reh_master_channel != NULL);
	assert(h->reh_master_channel_name != NULL);
	assert(h->reh_master_subscriber_id != NULL);

	if ((scf_h = scf_handle_create(SCF_VERSION)) == NULL) {
		switch (scf_error()) {
		case SCF_ERROR_VERSION_MISMATCH:
			return (EPROTO);

		case SCF_ERROR_NO_MEMORY:
			return (ENOMEM);

		default:
			bad_fail("scf_handle_create", scf_error());
		}
	}

	if (scf_handle_bind(scf_h) == -1) {
		scf_handle_destroy(scf_h);
		switch (scf_error()) {
		case SCF_ERROR_NO_SERVER:
			return (ENOTACTIVE);

		case SCF_ERROR_NO_RESOURCES:
			return (ENOMEM);

		case SCF_ERROR_INVALID_ARGUMENT:
		case SCF_ERROR_IN_USE:
		default:
			bad_fail("scf_handle_bind", scf_error());
		}
	}

	if (nvlist_alloc(&attr, NV_UNIQUE_NAME, 0) != 0 ||
	    nvlist_add_int32(attr, RESTARTER_NAME_STATE, new_cur_state) != 0 ||
	    nvlist_add_int32(attr, RESTARTER_NAME_NEXT_STATE, new_next_state)
	    != 0 ||
	    nvlist_add_int32(attr, RESTARTER_NAME_ERROR, e) != 0 ||
	    nvlist_add_string(attr, RESTARTER_NAME_INSTANCE, inst) != 0 ||
	    nvlist_add_int32(attr, RESTARTER_NAME_REASON, aux) != 0) {
		ret = ENOMEM;
	} else {
		id.i_fmri = inst;
		id.i_state = cur_state;
		id.i_next_state = next_state;

		ret = _restarter_commit_states(scf_h, &id, new_cur_state,
		    new_next_state, p);

		if (ret == 0) {
			ret = restarter_event_publish_retry(
			    h->reh_master_channel, "master", "state_change",
			    "com.sun", "librestart", attr, EVCH_NOSLEEP);
		}
	}

	nvlist_free(attr);
	(void) scf_handle_unbind(scf_h);
	scf_handle_destroy(scf_h);

	return (ret);
}

restarter_instance_state_t
restarter_string_to_state(char *string)
{
	assert(string != NULL);

	if (strcmp(string, SCF_STATE_STRING_NONE) == 0)
		return (RESTARTER_STATE_NONE);
	else if (strcmp(string, SCF_STATE_STRING_UNINIT) == 0)
		return (RESTARTER_STATE_UNINIT);
	else if (strcmp(string, SCF_STATE_STRING_MAINT) == 0)
		return (RESTARTER_STATE_MAINT);
	else if (strcmp(string, SCF_STATE_STRING_OFFLINE) == 0)
		return (RESTARTER_STATE_OFFLINE);
	else if (strcmp(string, SCF_STATE_STRING_DISABLED) == 0)
		return (RESTARTER_STATE_DISABLED);
	else if (strcmp(string, SCF_STATE_STRING_ONLINE) == 0)
		return (RESTARTER_STATE_ONLINE);
	else if (strcmp(string, SCF_STATE_STRING_DEGRADED) == 0)
		return (RESTARTER_STATE_DEGRADED);
	else {
		return (RESTARTER_STATE_NONE);
	}
}

ssize_t
restarter_state_to_string(restarter_instance_state_t state, char *string,
    size_t len)
{
	assert(string != NULL);

	if (state == RESTARTER_STATE_NONE)
		return ((ssize_t)strlcpy(string, SCF_STATE_STRING_NONE, len));
	else if (state == RESTARTER_STATE_UNINIT)
		return ((ssize_t)strlcpy(string, SCF_STATE_STRING_UNINIT, len));
	else if (state == RESTARTER_STATE_MAINT)
		return ((ssize_t)strlcpy(string, SCF_STATE_STRING_MAINT, len));
	else if (state == RESTARTER_STATE_OFFLINE)
		return ((ssize_t)strlcpy(string, SCF_STATE_STRING_OFFLINE,
		    len));
	else if (state == RESTARTER_STATE_DISABLED)
		return ((ssize_t)strlcpy(string, SCF_STATE_STRING_DISABLED,
		    len));
	else if (state == RESTARTER_STATE_ONLINE)
		return ((ssize_t)strlcpy(string, SCF_STATE_STRING_ONLINE, len));
	else if (state == RESTARTER_STATE_DEGRADED)
		return ((ssize_t)strlcpy(string, SCF_STATE_STRING_DEGRADED,
		    len));
	else
		return ((ssize_t)strlcpy(string, "unknown", len));
}

/*
 * Sets pg to the name property group of s_inst.  If it doesn't exist, it is
 * added.
 *
 * Fails with
 *   ECONNABORTED - repository disconnection or unknown libscf error
 *   EBADF - inst is not set
 *   ECANCELED - inst is deleted
 *   EPERM - permission is denied
 *   EACCES - backend denied access
 *   EROFS - backend readonly
 */
static int
instance_get_or_add_pg(scf_instance_t *inst, const char *name,
    const char *type, uint32_t flags, scf_propertygroup_t *pg)
{
again:
	if (scf_instance_get_pg(inst, name, pg) == 0)
		return (0);

	switch (scf_error()) {
	case SCF_ERROR_CONNECTION_BROKEN:
	default:
		return (ECONNABORTED);

	case SCF_ERROR_NOT_SET:
		return (EBADF);

	case SCF_ERROR_DELETED:
		return (ECANCELED);

	case SCF_ERROR_NOT_FOUND:
		break;

	case SCF_ERROR_HANDLE_MISMATCH:
	case SCF_ERROR_INVALID_ARGUMENT:
		bad_fail("scf_instance_get_pg", scf_error());
	}

	if (scf_instance_add_pg(inst, name, type, flags, pg) == 0)
		return (0);

	switch (scf_error()) {
	case SCF_ERROR_CONNECTION_BROKEN:
	default:
		return (ECONNABORTED);

	case SCF_ERROR_DELETED:
		return (ECANCELED);

	case SCF_ERROR_EXISTS:
		goto again;

	case SCF_ERROR_PERMISSION_DENIED:
		return (EPERM);

	case SCF_ERROR_BACKEND_ACCESS:
		return (EACCES);

	case SCF_ERROR_BACKEND_READONLY:
		return (EROFS);

	case SCF_ERROR_HANDLE_MISMATCH:
	case SCF_ERROR_INVALID_ARGUMENT:
	case SCF_ERROR_NOT_SET:			/* should be caught above */
		bad_fail("scf_instance_add_pg", scf_error());
	}

	return (0);
}

/*
 * Fails with
 *   ECONNABORTED
 *   ECANCELED - pg was deleted
 */
static int
tx_set_value(scf_transaction_t *tx, scf_transaction_entry_t *ent,
    const char *pname, scf_type_t ty, scf_value_t *val)
{
	int r;

	for (;;) {
		if (scf_transaction_property_change_type(tx, ent, pname,
		    ty) == 0)
			break;

		switch (scf_error()) {
		case SCF_ERROR_CONNECTION_BROKEN:
		default:
			return (ECONNABORTED);

		case SCF_ERROR_DELETED:
			return (ECANCELED);

		case SCF_ERROR_NOT_FOUND:
			break;

		case SCF_ERROR_HANDLE_MISMATCH:
		case SCF_ERROR_INVALID_ARGUMENT:
		case SCF_ERROR_IN_USE:
		case SCF_ERROR_NOT_SET:
			bad_fail("scf_transaction_property_change_type",
			    scf_error());
		}

		if (scf_transaction_property_new(tx, ent, pname, ty) == 0)
			break;

		switch (scf_error()) {
		case SCF_ERROR_CONNECTION_BROKEN:
		default:
			return (ECONNABORTED);

		case SCF_ERROR_DELETED:
			return (ECANCELED);

		case SCF_ERROR_EXISTS:
			break;

		case SCF_ERROR_HANDLE_MISMATCH:
		case SCF_ERROR_INVALID_ARGUMENT:
		case SCF_ERROR_IN_USE:
		case SCF_ERROR_NOT_SET:
			bad_fail("scf_transaction_property_new", scf_error());
		}
	}

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

	return (0);
}

/*
 * Commit new_state, new_next_state, and aux to the repository for id.  If
 * successful, also set id's state and next-state as given, and return 0.
 * Fails with
 *   ENOMEM - out of memory
 *   ECONNABORTED - repository connection broken
 *		  - unknown libscf error
 *   EINVAL - id->i_fmri is invalid or not an instance FMRI
 *   ENOENT - id->i_fmri does not exist
 *   EPERM - insufficient permissions
 *   EACCES - backend access denied
 *   EROFS - backend is readonly
 */
int
_restarter_commit_states(scf_handle_t *h, instance_data_t *id,
    restarter_instance_state_t new_state,
    restarter_instance_state_t new_state_next, const char *aux)
{
	char str_state[MAX_SCF_STATE_STRING_SZ];
	char str_new_state[MAX_SCF_STATE_STRING_SZ];
	char str_state_next[MAX_SCF_STATE_STRING_SZ];
	char str_new_state_next[MAX_SCF_STATE_STRING_SZ];
	int ret = 0, r;
	struct timeval now;
	ssize_t sz;

	scf_transaction_t *t = NULL;
	scf_transaction_entry_t *t_state = NULL, *t_state_next = NULL;
	scf_transaction_entry_t *t_stime = NULL, *t_aux = NULL;
	scf_value_t *v_state = NULL, *v_state_next = NULL, *v_stime = NULL;
	scf_value_t *v_aux = NULL;
	scf_instance_t *s_inst = NULL;
	scf_propertygroup_t *pg = NULL;

	assert(new_state != RESTARTER_STATE_NONE);

	if ((s_inst = scf_instance_create(h)) == NULL ||
	    (pg = scf_pg_create(h)) == NULL ||
	    (t = scf_transaction_create(h)) == NULL ||
	    (t_state = scf_entry_create(h)) == NULL ||
	    (t_state_next = scf_entry_create(h)) == NULL ||
	    (t_stime = scf_entry_create(h)) == NULL ||
	    (t_aux = scf_entry_create(h)) == NULL ||
	    (v_state = scf_value_create(h)) == NULL ||
	    (v_state_next = scf_value_create(h)) == NULL ||
	    (v_stime = scf_value_create(h)) == NULL ||
	    (v_aux = scf_value_create(h)) == NULL) {
		ret = ENOMEM;
		goto out;
	}

	sz = restarter_state_to_string(new_state, str_new_state,
	    sizeof (str_new_state));
	assert(sz < sizeof (str_new_state));
	sz = restarter_state_to_string(new_state_next, str_new_state_next,
	    sizeof (str_new_state_next));
	assert(sz < sizeof (str_new_state_next));
	sz = restarter_state_to_string(id->i_state, str_state,
	    sizeof (str_state));
	assert(sz < sizeof (str_state));
	sz = restarter_state_to_string(id->i_next_state, str_state_next,
	    sizeof (str_state_next));
	assert(sz < sizeof (str_state_next));

	ret = gettimeofday(&now, NULL);
	assert(ret != -1);

	if (scf_handle_decode_fmri(h, id->i_fmri, NULL, NULL, s_inst,
	    NULL, NULL, SCF_DECODE_FMRI_EXACT) == -1) {
		switch (scf_error()) {
		case SCF_ERROR_CONNECTION_BROKEN:
		default:
			ret = ECONNABORTED;
			break;

		case SCF_ERROR_INVALID_ARGUMENT:
		case SCF_ERROR_CONSTRAINT_VIOLATED:
			ret = EINVAL;
			break;

		case SCF_ERROR_NOT_FOUND:
			ret = ENOENT;
			break;

		case SCF_ERROR_HANDLE_MISMATCH:
			bad_fail("scf_handle_decode_fmri", scf_error());
		}
		goto out;
	}


	if (scf_value_set_astring(v_state, str_new_state) != 0 ||
	    scf_value_set_astring(v_state_next, str_new_state_next) != 0)
		bad_fail("scf_value_set_astring", scf_error());

	if (aux) {
		if (scf_value_set_astring(v_aux, aux) != 0)
			bad_fail("scf_value_set_astring", scf_error());
	}

	if (scf_value_set_time(v_stime, now.tv_sec, now.tv_usec * 1000) != 0)
		bad_fail("scf_value_set_time", scf_error());

add_pg:
	switch (r = instance_get_or_add_pg(s_inst, SCF_PG_RESTARTER,
	    SCF_PG_RESTARTER_TYPE, SCF_PG_RESTARTER_FLAGS, pg)) {
	case 0:
		break;

	case ECONNABORTED:
	case EPERM:
	case EACCES:
	case EROFS:
		ret = r;
		goto out;

	case ECANCELED:
		ret = ENOENT;
		goto out;

	case EBADF:
	default:
		bad_fail("instance_get_or_add_pg", r);
	}

	for (;;) {
		if (scf_transaction_start(t, pg) != 0) {
			switch (scf_error()) {
			case SCF_ERROR_CONNECTION_BROKEN:
			default:
				ret = ECONNABORTED;
				goto out;

			case SCF_ERROR_NOT_SET:
				goto add_pg;

			case SCF_ERROR_PERMISSION_DENIED:
				ret = EPERM;
				goto out;

			case SCF_ERROR_BACKEND_ACCESS:
				ret = EACCES;
				goto out;

			case SCF_ERROR_BACKEND_READONLY:
				ret = EROFS;
				goto out;

			case SCF_ERROR_HANDLE_MISMATCH:
			case SCF_ERROR_IN_USE:
				bad_fail("scf_transaction_start", scf_error());
			}
		}

		if ((r = tx_set_value(t, t_state, SCF_PROPERTY_STATE,
		    SCF_TYPE_ASTRING, v_state)) != 0 ||
		    (r = tx_set_value(t, t_state_next, SCF_PROPERTY_NEXT_STATE,
		    SCF_TYPE_ASTRING, v_state_next)) != 0 ||
		    (r = tx_set_value(t, t_stime, SCF_PROPERTY_STATE_TIMESTAMP,
		    SCF_TYPE_TIME, v_stime)) != 0) {
			switch (r) {
			case ECONNABORTED:
				ret = ECONNABORTED;
				goto out;

			case ECANCELED:
				scf_transaction_reset(t);
				goto add_pg;

			default:
				bad_fail("tx_set_value", r);
			}
		}

		if (aux) {
			if ((r = tx_set_value(t, t_aux, SCF_PROPERTY_AUX_STATE,
			    SCF_TYPE_ASTRING, v_aux)) != 0) {
				switch (r) {
				case ECONNABORTED:
					ret = ECONNABORTED;
					goto out;

				case ECANCELED:
					scf_transaction_reset(t);
					goto add_pg;

				default:
					bad_fail("tx_set_value", r);
				}
			}
		}

		ret = scf_transaction_commit(t);
		if (ret == 1)
			break;
		if (ret == -1) {
			switch (scf_error()) {
			case SCF_ERROR_CONNECTION_BROKEN:
			default:
				ret = ECONNABORTED;
				goto out;

			case SCF_ERROR_PERMISSION_DENIED:
				ret = EPERM;
				goto out;

			case SCF_ERROR_BACKEND_ACCESS:
				ret = EACCES;
				goto out;

			case SCF_ERROR_BACKEND_READONLY:
				ret = EROFS;
				goto out;

			case SCF_ERROR_NOT_SET:
				bad_fail("scf_transaction_commit", scf_error());
			}
		}

		scf_transaction_reset(t);
		if (scf_pg_update(pg) == -1) {
			switch (scf_error()) {
			case SCF_ERROR_CONNECTION_BROKEN:
			default:
				ret = ECONNABORTED;
				goto out;

			case SCF_ERROR_NOT_SET:
				goto add_pg;
			}
		}
	}

	id->i_state = new_state;
	id->i_next_state = new_state_next;
	ret = 0;

out:
	scf_transaction_destroy(t);
	scf_entry_destroy(t_state);
	scf_entry_destroy(t_state_next);
	scf_entry_destroy(t_stime);
	scf_entry_destroy(t_aux);
	scf_value_destroy(v_state);
	scf_value_destroy(v_state_next);
	scf_value_destroy(v_stime);
	scf_value_destroy(v_aux);
	scf_pg_destroy(pg);
	scf_instance_destroy(s_inst);

	return (ret);
}

/*
 * Fails with
 *   EINVAL - type is invalid
 *   ENOMEM
 *   ECONNABORTED - repository connection broken
 *   EBADF - s_inst is not set
 *   ECANCELED - s_inst is deleted
 *   EPERM - permission denied
 *   EACCES - backend access denied
 *   EROFS - backend readonly
 */
int
restarter_remove_contract(scf_instance_t *s_inst, ctid_t contract_id,
    restarter_contract_type_t type)
{
	scf_handle_t *h;
	scf_transaction_t *t = NULL;
	scf_transaction_entry_t *t_cid = NULL;
	scf_propertygroup_t *pg = NULL;
	scf_property_t *prop = NULL;
	scf_value_t *val;
	scf_iter_t *iter = NULL;
	const char *pname;
	int ret = 0, primary;
	uint64_t c;

	switch (type) {
	case RESTARTER_CONTRACT_PRIMARY:
		primary = 1;
		break;
	case RESTARTER_CONTRACT_TRANSIENT:
		primary = 0;
		break;
	default:
		return (EINVAL);
	}

	h = scf_instance_handle(s_inst);

	pg = scf_pg_create(h);
	prop = scf_property_create(h);
	iter = scf_iter_create(h);
	t = scf_transaction_create(h);

	if (pg == NULL || prop == NULL || iter == NULL || t == NULL) {
		ret = ENOMEM;
		goto remove_contract_cleanup;
	}

add:
	scf_transaction_destroy_children(t);
	ret = instance_get_or_add_pg(s_inst, SCF_PG_RESTARTER,
	    SCF_PG_RESTARTER_TYPE, SCF_PG_RESTARTER_FLAGS, pg);
	if (ret != 0)
		goto remove_contract_cleanup;

	pname = primary? SCF_PROPERTY_CONTRACT :
	    SCF_PROPERTY_TRANSIENT_CONTRACT;

	for (;;) {
		if (scf_transaction_start(t, pg) != 0) {
			switch (scf_error()) {
			case SCF_ERROR_CONNECTION_BROKEN:
			default:
				ret = ECONNABORTED;
				goto remove_contract_cleanup;

			case SCF_ERROR_DELETED:
				goto add;

			case SCF_ERROR_PERMISSION_DENIED:
				ret = EPERM;
				goto remove_contract_cleanup;

			case SCF_ERROR_BACKEND_ACCESS:
				ret = EACCES;
				goto remove_contract_cleanup;

			case SCF_ERROR_BACKEND_READONLY:
				ret = EROFS;
				goto remove_contract_cleanup;

			case SCF_ERROR_HANDLE_MISMATCH:
			case SCF_ERROR_IN_USE:
			case SCF_ERROR_NOT_SET:
				bad_fail("scf_transaction_start", scf_error());
			}
		}

		t_cid = scf_entry_create(h);

		if (scf_pg_get_property(pg, pname, prop) == 0) {
replace:
			if (scf_transaction_property_change_type(t, t_cid,
			    pname, SCF_TYPE_COUNT) != 0) {
				switch (scf_error()) {
				case SCF_ERROR_CONNECTION_BROKEN:
				default:
					ret = ECONNABORTED;
					goto remove_contract_cleanup;

				case SCF_ERROR_DELETED:
					scf_entry_destroy(t_cid);
					goto add;

				case SCF_ERROR_NOT_FOUND:
					goto new;

				case SCF_ERROR_HANDLE_MISMATCH:
				case SCF_ERROR_INVALID_ARGUMENT:
				case SCF_ERROR_IN_USE:
				case SCF_ERROR_NOT_SET:
					bad_fail(
					"scf_transaction_property_changetype",
					    scf_error());
				}
			}

			if (scf_property_is_type(prop, SCF_TYPE_COUNT) == 0) {
				if (scf_iter_property_values(iter, prop) != 0) {
					switch (scf_error()) {
					case SCF_ERROR_CONNECTION_BROKEN:
					default:
						ret = ECONNABORTED;
						goto remove_contract_cleanup;

					case SCF_ERROR_NOT_SET:
					case SCF_ERROR_HANDLE_MISMATCH:
						bad_fail(
						    "scf_iter_property_values",
						    scf_error());
					}
				}

next_val:
				val = scf_value_create(h);
				if (val == NULL) {
					assert(scf_error() ==
					    SCF_ERROR_NO_MEMORY);
					ret = ENOMEM;
					goto remove_contract_cleanup;
				}

				ret = scf_iter_next_value(iter, val);
				if (ret == -1) {
					switch (scf_error()) {
					case SCF_ERROR_CONNECTION_BROKEN:
						ret = ECONNABORTED;
						goto remove_contract_cleanup;

					case SCF_ERROR_DELETED:
						scf_value_destroy(val);
						goto add;

					case SCF_ERROR_HANDLE_MISMATCH:
					case SCF_ERROR_INVALID_ARGUMENT:
					case SCF_ERROR_PERMISSION_DENIED:
					default:
						bad_fail("scf_iter_next_value",
						    scf_error());
					}
				}

				if (ret == 1) {
					ret = scf_value_get_count(val, &c);
					assert(ret == 0);

					if (c != contract_id) {
						ret = scf_entry_add_value(t_cid,
						    val);
						assert(ret == 0);
					} else {
						scf_value_destroy(val);
					}

					goto next_val;
				}

				scf_value_destroy(val);
			} else {
				switch (scf_error()) {
				case SCF_ERROR_CONNECTION_BROKEN:
				default:
					ret = ECONNABORTED;
					goto remove_contract_cleanup;

				case SCF_ERROR_TYPE_MISMATCH:
					break;

				case SCF_ERROR_INVALID_ARGUMENT:
				case SCF_ERROR_NOT_SET:
					bad_fail("scf_property_is_type",
					    scf_error());
				}
			}
		} else {
			switch (scf_error()) {
			case SCF_ERROR_CONNECTION_BROKEN:
			default:
				ret = ECONNABORTED;
				goto remove_contract_cleanup;

			case SCF_ERROR_DELETED:
				scf_entry_destroy(t_cid);
				goto add;

			case SCF_ERROR_NOT_FOUND:
				break;

			case SCF_ERROR_HANDLE_MISMATCH:
			case SCF_ERROR_INVALID_ARGUMENT:
			case SCF_ERROR_NOT_SET:
				bad_fail("scf_pg_get_property", scf_error());
			}

new:
			if (scf_transaction_property_new(t, t_cid, pname,
			    SCF_TYPE_COUNT) != 0) {
				switch (scf_error()) {
				case SCF_ERROR_CONNECTION_BROKEN:
				default:
					ret = ECONNABORTED;
					goto remove_contract_cleanup;

				case SCF_ERROR_DELETED:
					scf_entry_destroy(t_cid);
					goto add;

				case SCF_ERROR_EXISTS:
					goto replace;

				case SCF_ERROR_HANDLE_MISMATCH:
				case SCF_ERROR_INVALID_ARGUMENT:
				case SCF_ERROR_NOT_SET:
					bad_fail("scf_transaction_property_new",
					    scf_error());
				}
			}
		}

		ret = scf_transaction_commit(t);
		if (ret == -1) {
			switch (scf_error()) {
			case SCF_ERROR_CONNECTION_BROKEN:
			default:
				ret = ECONNABORTED;
				goto remove_contract_cleanup;

			case SCF_ERROR_DELETED:
				goto add;

			case SCF_ERROR_PERMISSION_DENIED:
				ret = EPERM;
				goto remove_contract_cleanup;

			case SCF_ERROR_BACKEND_ACCESS:
				ret = EACCES;
				goto remove_contract_cleanup;

			case SCF_ERROR_BACKEND_READONLY:
				ret = EROFS;
				goto remove_contract_cleanup;

			case SCF_ERROR_NOT_SET:
				bad_fail("scf_transaction_commit", scf_error());
			}
		}
		if (ret == 1) {
			ret = 0;
			break;
		}

		scf_transaction_destroy_children(t);
		if (scf_pg_update(pg) == -1) {
			switch (scf_error()) {
			case SCF_ERROR_CONNECTION_BROKEN:
			default:
				ret = ECONNABORTED;
				goto remove_contract_cleanup;

			case SCF_ERROR_DELETED:
				goto add;

			case SCF_ERROR_NOT_SET:
				bad_fail("scf_pg_update", scf_error());
			}
		}
	}

remove_contract_cleanup:
	scf_transaction_destroy_children(t);
	scf_transaction_destroy(t);
	scf_iter_destroy(iter);
	scf_property_destroy(prop);
	scf_pg_destroy(pg);

	return (ret);
}

/*
 * Fails with
 *   EINVAL - type is invalid
 *   ENOMEM
 *   ECONNABORTED - repository disconnection
 *   EBADF - s_inst is not set
 *   ECANCELED - s_inst is deleted
 *   EPERM
 *   EACCES
 *   EROFS
 */
int
restarter_store_contract(scf_instance_t *s_inst, ctid_t contract_id,
    restarter_contract_type_t type)
{
	scf_handle_t *h;
	scf_transaction_t *t = NULL;
	scf_transaction_entry_t *t_cid = NULL;
	scf_value_t *val;
	scf_propertygroup_t *pg = NULL;
	scf_property_t *prop = NULL;
	scf_iter_t *iter = NULL;
	const char *pname;
	int ret = 0, primary;

	if (type == RESTARTER_CONTRACT_PRIMARY)
		primary = 1;
	else if (type == RESTARTER_CONTRACT_TRANSIENT)
		primary = 0;
	else
		return (EINVAL);

	h = scf_instance_handle(s_inst);

	pg = scf_pg_create(h);
	prop = scf_property_create(h);
	iter = scf_iter_create(h);
	t = scf_transaction_create(h);

	if (pg == NULL || prop == NULL || iter == NULL || t == NULL) {
		ret = ENOMEM;
		goto out;
	}

add:
	scf_transaction_destroy_children(t);
	ret = instance_get_or_add_pg(s_inst, SCF_PG_RESTARTER,
	    SCF_PG_RESTARTER_TYPE, SCF_PG_RESTARTER_FLAGS, pg);
	if (ret != 0)
		goto out;

	pname = primary ? SCF_PROPERTY_CONTRACT :
	    SCF_PROPERTY_TRANSIENT_CONTRACT;

	for (;;) {
		if (scf_transaction_start(t, pg) != 0) {
			switch (scf_error()) {
			case SCF_ERROR_CONNECTION_BROKEN:
			default:
				ret = ECONNABORTED;
				goto out;

			case SCF_ERROR_DELETED:
				goto add;

			case SCF_ERROR_PERMISSION_DENIED:
				ret = EPERM;
				goto out;

			case SCF_ERROR_BACKEND_ACCESS:
				ret = EACCES;
				goto out;

			case SCF_ERROR_BACKEND_READONLY:
				ret = EROFS;
				goto out;

			case SCF_ERROR_HANDLE_MISMATCH:
			case SCF_ERROR_IN_USE:
			case SCF_ERROR_NOT_SET:
				bad_fail("scf_transaction_start", scf_error());
			}
		}

		t_cid = scf_entry_create(h);
		if (t_cid == NULL) {
			ret = ENOMEM;
			goto out;
		}

		if (scf_pg_get_property(pg, pname, prop) == 0) {
replace:
			if (scf_transaction_property_change_type(t, t_cid,
			    pname, SCF_TYPE_COUNT) != 0) {
				switch (scf_error()) {
				case SCF_ERROR_CONNECTION_BROKEN:
				default:
					ret = ECONNABORTED;
					goto out;

				case SCF_ERROR_DELETED:
					scf_entry_destroy(t_cid);
					goto add;

				case SCF_ERROR_NOT_FOUND:
					goto new;

				case SCF_ERROR_HANDLE_MISMATCH:
				case SCF_ERROR_INVALID_ARGUMENT:
				case SCF_ERROR_IN_USE:
				case SCF_ERROR_NOT_SET:
					bad_fail(
					"scf_transaction_propert_change_type",
					    scf_error());
				}
			}

			if (scf_property_is_type(prop, SCF_TYPE_COUNT) == 0) {
				if (scf_iter_property_values(iter, prop) != 0) {
					switch (scf_error()) {
					case SCF_ERROR_CONNECTION_BROKEN:
					default:
						ret = ECONNABORTED;
						goto out;

					case SCF_ERROR_NOT_SET:
					case SCF_ERROR_HANDLE_MISMATCH:
						bad_fail(
						    "scf_iter_property_values",
						    scf_error());
					}
				}

next_val:
				val = scf_value_create(h);
				if (val == NULL) {
					assert(scf_error() ==
					    SCF_ERROR_NO_MEMORY);
					ret = ENOMEM;
					goto out;
				}

				ret = scf_iter_next_value(iter, val);
				if (ret == -1) {
					switch (scf_error()) {
					case SCF_ERROR_CONNECTION_BROKEN:
					default:
						ret = ECONNABORTED;
						goto out;

					case SCF_ERROR_DELETED:
						scf_value_destroy(val);
						goto add;

					case SCF_ERROR_HANDLE_MISMATCH:
					case SCF_ERROR_INVALID_ARGUMENT:
					case SCF_ERROR_PERMISSION_DENIED:
						bad_fail(
						    "scf_iter_next_value",
						    scf_error());
					}
				}

				if (ret == 1) {
					ret = scf_entry_add_value(t_cid, val);
					assert(ret == 0);

					goto next_val;
				}

				scf_value_destroy(val);
			} else {
				switch (scf_error()) {
				case SCF_ERROR_CONNECTION_BROKEN:
				default:
					ret = ECONNABORTED;
					goto out;

				case SCF_ERROR_TYPE_MISMATCH:
					break;

				case SCF_ERROR_INVALID_ARGUMENT:
				case SCF_ERROR_NOT_SET:
					bad_fail("scf_property_is_type",
					    scf_error());
				}
			}
		} else {
			switch (scf_error()) {
			case SCF_ERROR_CONNECTION_BROKEN:
			default:
				ret = ECONNABORTED;
				goto out;

			case SCF_ERROR_DELETED:
				scf_entry_destroy(t_cid);
				goto add;

			case SCF_ERROR_NOT_FOUND:
				break;

			case SCF_ERROR_HANDLE_MISMATCH:
			case SCF_ERROR_INVALID_ARGUMENT:
			case SCF_ERROR_NOT_SET:
				bad_fail("scf_pg_get_property", scf_error());
			}

new:
			if (scf_transaction_property_new(t, t_cid, pname,
			    SCF_TYPE_COUNT) != 0) {
				switch (scf_error()) {
				case SCF_ERROR_CONNECTION_BROKEN:
				default:
					ret = ECONNABORTED;
					goto out;

				case SCF_ERROR_DELETED:
					scf_entry_destroy(t_cid);
					goto add;

				case SCF_ERROR_EXISTS:
					goto replace;

				case SCF_ERROR_HANDLE_MISMATCH:
				case SCF_ERROR_INVALID_ARGUMENT:
				case SCF_ERROR_NOT_SET:
					bad_fail("scf_transaction_property_new",
					    scf_error());
				}
			}
		}

		val = scf_value_create(h);
		if (val == NULL) {
			assert(scf_error() == SCF_ERROR_NO_MEMORY);
			ret = ENOMEM;
			goto out;
		}

		scf_value_set_count(val, contract_id);
		ret = scf_entry_add_value(t_cid, val);
		assert(ret == 0);

		ret = scf_transaction_commit(t);
		if (ret == -1) {
			switch (scf_error()) {
			case SCF_ERROR_CONNECTION_BROKEN:
			default:
				ret = ECONNABORTED;
				goto out;

			case SCF_ERROR_DELETED:
				goto add;

			case SCF_ERROR_PERMISSION_DENIED:
				ret = EPERM;
				goto out;

			case SCF_ERROR_BACKEND_ACCESS:
				ret = EACCES;
				goto out;

			case SCF_ERROR_BACKEND_READONLY:
				ret = EROFS;
				goto out;

			case SCF_ERROR_NOT_SET:
				bad_fail("scf_transaction_commit", scf_error());
			}
		}
		if (ret == 1) {
			ret = 0;
			break;
		}

		scf_transaction_destroy_children(t);
		if (scf_pg_update(pg) == -1) {
			switch (scf_error()) {
			case SCF_ERROR_CONNECTION_BROKEN:
			default:
				ret = ECONNABORTED;
				goto out;

			case SCF_ERROR_DELETED:
				goto add;

			case SCF_ERROR_NOT_SET:
				bad_fail("scf_pg_update", scf_error());
			}
		}
	}

out:
	scf_transaction_destroy_children(t);
	scf_transaction_destroy(t);
	scf_iter_destroy(iter);
	scf_property_destroy(prop);
	scf_pg_destroy(pg);

	return (ret);
}

int
restarter_rm_libs_loadable()
{
	void *libhndl;

	if (method_context_safety)
		return (1);

	if ((libhndl = dlopen("libpool.so", RTLD_LAZY | RTLD_LOCAL)) == NULL)
		return (0);

	(void) dlclose(libhndl);

	if ((libhndl = dlopen("libproject.so", RTLD_LAZY | RTLD_LOCAL)) == NULL)
		return (0);

	(void) dlclose(libhndl);

	method_context_safety = 1;

	return (1);
}

static int
get_astring_val(scf_propertygroup_t *pg, const char *name, char *buf,
    size_t bufsz, scf_property_t *prop, scf_value_t *val)
{
	ssize_t szret;

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

	if (scf_pg_get_property(pg, name, prop) != SCF_SUCCESS) {
		if (scf_error() == SCF_ERROR_CONNECTION_BROKEN)
			uu_die(rcbroken);
		return (-1);
	}

	if (scf_property_get_value(prop, val) != SCF_SUCCESS) {
		if (scf_error() == SCF_ERROR_CONNECTION_BROKEN)
			uu_die(rcbroken);
		return (-1);
	}

	szret = scf_value_get_astring(val, buf, bufsz);

	return (szret >= 0 ? 0 : -1);
}

static int
get_boolean_val(scf_propertygroup_t *pg, const char *name, uint8_t *b,
    scf_property_t *prop, scf_value_t *val)
{
	if (scf_pg_get_property(pg, name, prop) != SCF_SUCCESS) {
		if (scf_error() == SCF_ERROR_CONNECTION_BROKEN)
			uu_die(rcbroken);
		return (-1);
	}

	if (scf_property_get_value(prop, val) != SCF_SUCCESS) {
		if (scf_error() == SCF_ERROR_CONNECTION_BROKEN)
			uu_die(rcbroken);
		return (-1);
	}

	if (scf_value_get_boolean(val, b))
		return (-1);

	return (0);
}

/*
 * Try to load mcp->pwd, if it isn't already.
 * Fails with
 *   ENOMEM - malloc() failed
 *   ENOENT - no entry found
 *   EIO - I/O error
 *   EMFILE - process out of file descriptors
 *   ENFILE - system out of file handles
 */
static int
lookup_pwd(struct method_context *mcp)
{
	struct passwd *pwdp;

	if (mcp->pwbuf != NULL && mcp->pwd.pw_uid == mcp->uid)
		return (0);

	if (mcp->pwbuf == NULL) {
		mcp->pwbufsz = sysconf(_SC_GETPW_R_SIZE_MAX);
		assert(mcp->pwbufsz >= 0);
		mcp->pwbuf = malloc(mcp->pwbufsz);
		if (mcp->pwbuf == NULL)
			return (ENOMEM);
	}

	do {
		errno = 0;
		pwdp = getpwuid_r(mcp->uid, &mcp->pwd, mcp->pwbuf,
		    mcp->pwbufsz);
	} while (pwdp == NULL && errno == EINTR);
	if (pwdp != NULL)
		return (0);

	free(mcp->pwbuf);
	mcp->pwbuf = NULL;

	switch (errno) {
	case 0:
	default:
		/*
		 * Until bug 5065780 is fixed, getpwuid_r() can fail with
		 * ENOENT, particularly on the miniroot.  Since the
		 * documentation is inaccurate, we'll return ENOENT for unknown
		 * errors.
		 */
		return (ENOENT);

	case EIO:
	case EMFILE:
	case ENFILE:
		return (errno);

	case ERANGE:
		bad_fail("getpwuid_r", errno);
		/* NOTREACHED */
	}
}

/*
 * Get the user id for str.  Returns 0 on success or
 *   ERANGE	the uid is too big
 *   EINVAL	the string starts with a digit, but is not a valid uid
 *   ENOMEM	out of memory
 *   ENOENT	no passwd entry for str
 *   EIO	an I/O error has occurred
 *   EMFILE/ENFILE  out of file descriptors
 */
int
get_uid(const char *str, struct method_context *ci, uid_t *uidp)
{
	if (isdigit(str[0])) {
		uid_t uid;
		char *cp;

		errno = 0;
		uid = strtol(str, &cp, 10);

		if (uid == 0 && errno != 0) {
			assert(errno != EINVAL);
			return (errno);
		}

		for (; *cp != '\0'; ++cp)
			if (*cp != ' ' || *cp != '\t')
				return (EINVAL);

		if (uid > UID_MAX)
			return (EINVAL);

		*uidp = uid;
		return (0);
	} else {
		struct passwd *pwdp;

		if (ci->pwbuf == NULL) {
			ci->pwbufsz = sysconf(_SC_GETPW_R_SIZE_MAX);
			ci->pwbuf = malloc(ci->pwbufsz);
			if (ci->pwbuf == NULL)
				return (ENOMEM);
		}

		do {
			errno = 0;
			pwdp =
			    getpwnam_r(str, &ci->pwd, ci->pwbuf, ci->pwbufsz);
		} while (pwdp == NULL && errno == EINTR);

		if (pwdp != NULL) {
			*uidp = ci->pwd.pw_uid;
			return (0);
		} else {
			free(ci->pwbuf);
			ci->pwbuf = NULL;
			switch (errno) {
			case 0:
				return (ENOENT);

			case ENOENT:
			case EIO:
			case EMFILE:
			case ENFILE:
				return (errno);

			case ERANGE:
			default:
				bad_fail("getpwnam_r", errno);
				/* NOTREACHED */
			}
		}
	}
}

gid_t
get_gid(const char *str)
{
	if (isdigit(str[0])) {
		gid_t gid;
		char *cp;

		errno = 0;
		gid = strtol(str, &cp, 10);

		if (gid == 0 && errno != 0)
			return ((gid_t)-1);

		for (; *cp != '\0'; ++cp)
			if (*cp != ' ' || *cp != '\t')
				return ((gid_t)-1);

		return (gid);
	} else {
		struct group grp, *ret;
		char *buffer;
		size_t buflen;

		buflen = sysconf(_SC_GETGR_R_SIZE_MAX);
		buffer = malloc(buflen);
		if (buffer == NULL)
			uu_die(allocfail);

		errno = 0;
		ret = getgrnam_r(str, &grp, buffer, buflen);
		free(buffer);

		return (ret == NULL ? (gid_t)-1 : grp.gr_gid);
	}
}

/*
 * Fails with
 *   ENOMEM - out of memory
 *   ENOENT - no passwd entry
 *	      no project entry
 *   EIO - an I/O error occurred
 *   EMFILE - the process is out of file descriptors
 *   ENFILE - the system is out of file handles
 *   ERANGE - the project id is out of range
 *   EINVAL - str is invalid
 *   E2BIG - the project entry was too big
 *   -1 - the name service switch is misconfigured
 */
int
get_projid(const char *str, struct method_context *cip)
{
	int ret;
	void *buf;
	const size_t bufsz = PROJECT_BUFSZ;
	struct project proj, *pp;

	if (strcmp(str, ":default") == 0) {
		if (cip->uid == 0) {
			/* Don't change project for root services */
			cip->project = NULL;
			return (0);
		}

		switch (ret = lookup_pwd(cip)) {
		case 0:
			break;

		case ENOMEM:
		case ENOENT:
		case EIO:
		case EMFILE:
		case ENFILE:
			return (ret);

		default:
			bad_fail("lookup_pwd", ret);
		}

		buf = malloc(bufsz);
		if (buf == NULL)
			return (ENOMEM);

		do {
			errno = 0;
			pp = getdefaultproj(cip->pwd.pw_name, &proj, buf,
			    bufsz);
		} while (pp == NULL && errno == EINTR);

		/* to be continued ... */
	} else {
		projid_t projid;
		char *cp;

		if (!isdigit(str[0])) {
			cip->project = strdup(str);
			return (cip->project != NULL ? 0 : ENOMEM);
		}

		errno = 0;
		projid = strtol(str, &cp, 10);

		if (projid == 0 && errno != 0) {
			assert(errno == ERANGE);
			return (errno);
		}

		for (; *cp != '\0'; ++cp)
			if (*cp != ' ' || *cp != '\t')
				return (EINVAL);

		if (projid > MAXPROJID)
			return (ERANGE);

		buf = malloc(bufsz);
		if (buf == NULL)
			return (ENOMEM);

		do {
			errno = 0;
			pp = getprojbyid(projid, &proj, buf, bufsz);
		} while (pp == NULL && errno == EINTR);
	}

	if (pp) {
		cip->project = strdup(pp->pj_name);
		free(buf);
		return (cip->project != NULL ? 0 : ENOMEM);
	}

	free(buf);

	switch (errno) {
	case 0:
		return (ENOENT);

	case EIO:
	case EMFILE:
	case ENFILE:
		return (errno);

	case ERANGE:
		return (E2BIG);

	default:
		return (-1);
	}
}

/*
 * Parse the supp_groups property value and populate ci->groups.  Returns
 * EINVAL (get_gid() failed for one of the components), E2BIG (the property has
 * more than NGROUPS_MAX-1 groups), or 0 on success.
 */
int
get_groups(char *str, struct method_context *ci)
{
	char *cp, *end, *next;
	uint_t i;

	const char * const whitespace = " \t";
	const char * const illegal = ", \t";

	if (str[0] == '\0') {
		ci->ngroups = 0;
		return (0);
	}

	for (cp = str, i = 0; *cp != '\0'; ) {
		/* skip whitespace */
		cp += strspn(cp, whitespace);

		/* find the end */
		end = cp + strcspn(cp, illegal);

		/* skip whitespace after end */
		next = end + strspn(end, whitespace);

		/* if there's a comma, it separates the fields */
		if (*next == ',')
			++next;

		*end = '\0';

		if ((ci->groups[i] = get_gid(cp)) == (gid_t)-1) {
			ci->ngroups = 0;
			return (EINVAL);
		}

		++i;
		if (i > NGROUPS_MAX - 1) {
			ci->ngroups = 0;
			return (E2BIG);
		}

		cp = next;
	}

	ci->ngroups = i;
	return (0);
}


/*
 * Return an error message structure containing the error message
 * with context, and the error so the caller can make a decision
 * on what to do next.
 *
 * Because get_ids uses the mc_error_create() function which can
 * reallocate the merr, this function must return the merr pointer
 * in case it was reallocated.
 */
static mc_error_t *
get_profile(scf_propertygroup_t *methpg, scf_propertygroup_t *instpg,
    scf_property_t *prop, scf_value_t *val, const char *cmdline,
    struct method_context *ci, mc_error_t *merr)
{
	char *buf = ci->vbuf;
	ssize_t buf_sz = ci->vbuf_sz;
	char cmd[PATH_MAX];
	char *cp, *value;
	const char *cmdp;
	execattr_t *eap;
	mc_error_t *err = merr;
	int r;

	if (!(get_astring_val(methpg, SCF_PROPERTY_PROFILE, buf, buf_sz, prop,
	    val) == 0 || get_astring_val(instpg, SCF_PROPERTY_PROFILE, buf,
	    buf_sz, prop, val) == 0))
		return (mc_error_create(merr, scf_error(),
		    "Method context requires a profile, but the  \"%s\" "
		    "property could not be read. scf_error is %s",
		    SCF_PROPERTY_PROFILE, scf_strerror(scf_error())));

	/* Extract the command from the command line. */
	cp = strpbrk(cmdline, " \t");

	if (cp == NULL) {
		cmdp = cmdline;
	} else {
		(void) strncpy(cmd, cmdline, cp - cmdline);
		cmd[cp - cmdline] = '\0';
		cmdp = cmd;
	}

	/* Require that cmdp[0] == '/'? */

	eap = getexecprof(buf, KV_COMMAND, cmdp, GET_ONE);
	if (eap == NULL)
		return (mc_error_create(merr, ENOENT,
		    "Could not find the execution profile \"%s\", "
		    "command %s.", buf, cmdp));

	/* Based on pfexec.c */

	/* Get the euid first so we don't override ci->pwd for the uid. */
	if ((value = kva_match(eap->attr, EXECATTR_EUID_KW)) != NULL) {
		if ((r = get_uid(value, ci, &ci->euid)) != 0) {
			ci->euid = (uid_t)-1;
			err = mc_error_create(merr, r,
			    "Could not interpret profile euid value \"%s\", "
			    "from the execution profile \"%s\", error %d.",
			    value, buf, r);
			goto out;
		}
	}

	if ((value = kva_match(eap->attr, EXECATTR_UID_KW)) != NULL) {
		if ((r = get_uid(value, ci, &ci->uid)) != 0) {
			ci->euid = ci->uid = (uid_t)-1;
			err = mc_error_create(merr, r,
			    "Could not interpret profile uid value \"%s\", "
			    "from the execution profile \"%s\", error %d.",
			    value, buf, r);
			goto out;
		}
		ci->euid = ci->uid;
	}

	if ((value = kva_match(eap->attr, EXECATTR_GID_KW)) != NULL) {
		ci->egid = ci->gid = get_gid(value);
		if (ci->gid == (gid_t)-1) {
			err = mc_error_create(merr, EINVAL,
			    "Could not interpret profile gid value \"%s\", "
			    "from the execution profile \"%s\".", value, buf);
			goto out;
		}
	}

	if ((value = kva_match(eap->attr, EXECATTR_EGID_KW)) != NULL) {
		ci->egid = get_gid(value);
		if (ci->egid == (gid_t)-1) {
			err = mc_error_create(merr, EINVAL,
			    "Could not interpret profile egid value \"%s\", "
			    "from the execution profile \"%s\".", value, buf);
			goto out;
		}
	}

	if ((value = kva_match(eap->attr, EXECATTR_LPRIV_KW)) != NULL) {
		ci->lpriv_set = priv_str_to_set(value, ",", NULL);
		if (ci->lpriv_set == NULL) {
			if (errno != EINVAL)
				err = mc_error_create(merr, ENOMEM,
				    ALLOCFAIL);
			else
				err = mc_error_create(merr, EINVAL,
				    "Could not interpret profile "
				    "limitprivs value \"%s\", from "
				    "the execution profile \"%s\".",
				    value, buf);
			goto out;
		}
	}

	if ((value = kva_match(eap->attr, EXECATTR_IPRIV_KW)) != NULL) {
		ci->priv_set = priv_str_to_set(value, ",", NULL);
		if (ci->priv_set == NULL) {
			if (errno != EINVAL)
				err = mc_error_create(merr, ENOMEM,
				    ALLOCFAIL);
			else
				err = mc_error_create(merr, EINVAL,
				    "Could not interpret profile privs value "
				    "\"%s\", from the execution profile "
				    "\"%s\".", value, buf);
			goto out;
		}
	}

out:
	free_execattr(eap);

	return (err);
}

/*
 * Return an error message structure containing the error message
 * with context, and the error so the caller can make a decision
 * on what to do next.
 *
 * Because get_ids uses the mc_error_create() function which can
 * reallocate the merr, this function must return the merr pointer
 * in case it was reallocated.
 */
static mc_error_t *
get_ids(scf_propertygroup_t *methpg, scf_propertygroup_t *instpg,
    scf_property_t *prop, scf_value_t *val, struct method_context *ci,
    mc_error_t *merr)
{
	char *vbuf = ci->vbuf;
	ssize_t vbuf_sz = ci->vbuf_sz;
	int r;

	/*
	 * This should never happen because the caller should fall through
	 * another path of just setting the ids to defaults, instead of
	 * attempting to get the ids here.
	 */
	if (methpg == NULL && instpg == NULL)
		return (mc_error_create(merr, ENOENT,
		    "No property groups to get ids from."));

	if (!(get_astring_val(methpg, SCF_PROPERTY_USER,
	    vbuf, vbuf_sz, prop, val) == 0 || get_astring_val(instpg,
	    SCF_PROPERTY_USER, vbuf, vbuf_sz, prop,
	    val) == 0))
		return (mc_error_create(merr, ENOENT,
		    "Could not get \"%s\" property.", SCF_PROPERTY_USER));

	if ((r = get_uid(vbuf, ci, &ci->uid)) != 0) {
		ci->uid = (uid_t)-1;
		return (mc_error_create(merr, r,
		    "Could not interpret \"%s\" property value \"%s\", "
		    "error %d.", SCF_PROPERTY_USER, vbuf, r));
	}

	if (!(get_astring_val(methpg, SCF_PROPERTY_GROUP, vbuf, vbuf_sz, prop,
	    val) == 0 || get_astring_val(instpg, SCF_PROPERTY_GROUP, vbuf,
	    vbuf_sz, prop, val) == 0)) {
		if (scf_error() == SCF_ERROR_NOT_FOUND) {
			(void) strcpy(vbuf, ":default");
		} else {
			return (mc_error_create(merr, ENOENT,
			    "Could not get \"%s\" property.",
			    SCF_PROPERTY_GROUP));
		}
	}

	if (strcmp(vbuf, ":default") != 0) {
		ci->gid = get_gid(vbuf);
		if (ci->gid == (gid_t)-1) {
			return (mc_error_create(merr, ENOENT,
			    "Could not interpret \"%s\" property value \"%s\".",
			    SCF_PROPERTY_GROUP, vbuf));
		}
	} else {
		switch (r = lookup_pwd(ci)) {
		case 0:
			ci->gid = ci->pwd.pw_gid;
			break;

		case ENOENT:
			ci->gid = (gid_t)-1;
			return (mc_error_create(merr, ENOENT,
			    "No passwd entry for uid \"%d\".", ci->uid));

		case ENOMEM:
			return (mc_error_create(merr, ENOMEM,
			    "Out of memory."));

		case EIO:
		case EMFILE:
		case ENFILE:
			return (mc_error_create(merr, ENFILE,
			    "getpwuid_r() failed, error %d.", r));

		default:
			bad_fail("lookup_pwd", r);
		}
	}

	if (!(get_astring_val(methpg, SCF_PROPERTY_SUPP_GROUPS, vbuf, vbuf_sz,
	    prop, val) == 0 || get_astring_val(instpg,
	    SCF_PROPERTY_SUPP_GROUPS, vbuf, vbuf_sz, prop, val) == 0)) {
		if (scf_error() == SCF_ERROR_NOT_FOUND) {
			(void) strcpy(vbuf, ":default");
		} else {
			return (mc_error_create(merr, ENOENT,
			    "Could not get supplemental groups (\"%s\") "
			    "property.", SCF_PROPERTY_SUPP_GROUPS));
		}
	}

	if (strcmp(vbuf, ":default") != 0) {
		switch (r = get_groups(vbuf, ci)) {
		case 0:
			break;

		case EINVAL:
			return (mc_error_create(merr, EINVAL,
			    "Could not interpret supplemental groups (\"%s\") "
			    "property value \"%s\".", SCF_PROPERTY_SUPP_GROUPS,
			    vbuf));

		case E2BIG:
			return (mc_error_create(merr, E2BIG,
			    "Too many supplemental groups values in \"%s\".",
			    vbuf));

		default:
			bad_fail("get_groups", r);
		}
	} else {
		ci->ngroups = -1;
	}

	if (!(get_astring_val(methpg, SCF_PROPERTY_PRIVILEGES, vbuf, vbuf_sz,
	    prop, val) == 0 || get_astring_val(instpg, SCF_PROPERTY_PRIVILEGES,
	    vbuf, vbuf_sz, prop, val) == 0)) {
		if (scf_error() == SCF_ERROR_NOT_FOUND) {
			(void) strcpy(vbuf, ":default");
		} else {
			return (mc_error_create(merr, ENOENT,
			    "Could not get \"%s\" property.",
			    SCF_PROPERTY_PRIVILEGES));
		}
	}

	/*
	 * For default privs, we need to keep priv_set == NULL, as
	 * we use this test elsewhere.
	 */
	if (strcmp(vbuf, ":default") != 0) {
		ci->priv_set = priv_str_to_set(vbuf, ",", NULL);
		if (ci->priv_set == NULL) {
			if (errno != EINVAL) {
				return (mc_error_create(merr, ENOMEM,
				    ALLOCFAIL));
			} else {
				return (mc_error_create(merr, EINVAL,
				    "Could not interpret \"%s\" "
				    "property value \"%s\".",
				    SCF_PROPERTY_PRIVILEGES, vbuf));
			}
		}
	}

	if (!(get_astring_val(methpg, SCF_PROPERTY_LIMIT_PRIVILEGES, vbuf,
	    vbuf_sz, prop, val) == 0 || get_astring_val(instpg,
	    SCF_PROPERTY_LIMIT_PRIVILEGES, vbuf, vbuf_sz, prop, val) == 0)) {
		if (scf_error() == SCF_ERROR_NOT_FOUND) {
			(void) strcpy(vbuf, ":default");
		} else {
			return (mc_error_create(merr, ENOENT,
			    "Could not get \"%s\" property.",
			    SCF_PROPERTY_LIMIT_PRIVILEGES));
		}
	}

	if (strcmp(vbuf, ":default") == 0)
		/*
		 * L must default to all privileges so root NPA services see
		 * iE = all.  "zone" is all privileges available in the current
		 * zone, equivalent to "all" in the global zone.
		 */
		(void) strcpy(vbuf, "zone");

	ci->lpriv_set = priv_str_to_set(vbuf, ",", NULL);
	if (ci->lpriv_set == NULL) {
		if (errno != EINVAL) {
			return (mc_error_create(merr, ENOMEM, ALLOCFAIL));
		} else {
			return (mc_error_create(merr, EINVAL,
			    "Could not interpret \"%s\" property value \"%s\".",
			    SCF_PROPERTY_LIMIT_PRIVILEGES, vbuf));
		}
	}

	return (merr);
}

static int
get_environment(scf_handle_t *h, scf_propertygroup_t *pg,
    struct method_context *mcp, scf_property_t *prop, scf_value_t *val)
{
	scf_iter_t *iter;
	scf_type_t type;
	size_t i = 0;
	int ret;

	if (scf_pg_get_property(pg, SCF_PROPERTY_ENVIRONMENT, prop) != 0) {
		if (scf_error() == SCF_ERROR_NOT_FOUND)
			return (ENOENT);
		return (scf_error());
	}
	if (scf_property_type(prop, &type) != 0)
		return (scf_error());
	if (type != SCF_TYPE_ASTRING)
		return (EINVAL);
	if ((iter = scf_iter_create(h)) == NULL)
		return (scf_error());

	if (scf_iter_property_values(iter, prop) != 0) {
		ret = scf_error();
		scf_iter_destroy(iter);
		return (ret);
	}

	mcp->env_sz = 10;

	if ((mcp->env = uu_zalloc(sizeof (*mcp->env) * mcp->env_sz)) == NULL) {
		ret = ENOMEM;
		goto out;
	}

	while ((ret = scf_iter_next_value(iter, val)) == 1) {
		ret = scf_value_get_as_string(val, mcp->vbuf, mcp->vbuf_sz);
		if (ret == -1) {
			ret = scf_error();
			goto out;
		}

		if ((mcp->env[i] = strdup(mcp->vbuf)) == NULL) {
			ret = ENOMEM;
			goto out;
		}

		if (++i == mcp->env_sz) {
			char **env;
			mcp->env_sz *= 2;
			env = uu_zalloc(sizeof (*mcp->env) * mcp->env_sz);
			if (env == NULL) {
				ret = ENOMEM;
				goto out;
			}
			(void) memcpy(env, mcp->env,
			    sizeof (*mcp->env) * (mcp->env_sz / 2));
			free(mcp->env);
			mcp->env = env;
		}
	}

	if (ret == -1)
		ret = scf_error();

out:
	scf_iter_destroy(iter);
	return (ret);
}

/*
 * Fetch method context information from the repository, allocate and fill
 * a method_context structure, return it in *mcpp, and return NULL.
 *
 * If no method_context is defined, original init context is provided, where
 * the working directory is '/', and uid/gid are 0/0.  But if a method_context
 * is defined at any level the smf_method(7) method_context defaults are used.
 *
 * Return an error message structure containing the error message
 * with context, and the error so the caller can make a decision
 * on what to do next.
 *
 * Error Types :
 *	E2BIG		Too many values or entry is too big
 *	EINVAL		Invalid value
 *	EIO		an I/O error has occured
 *	ENOENT		no entry for value
 *	ENOMEM		out of memory
 *	ENOTSUP		Version mismatch
 *	ERANGE		value is out of range
 *	EMFILE/ENFILE	out of file descriptors
 *
 *	SCF_ERROR_BACKEND_ACCESS
 *	SCF_ERROR_CONNECTION_BROKEN
 *	SCF_ERROR_DELETED
 *	SCF_ERROR_CONSTRAINT_VIOLATED
 *	SCF_ERROR_HANDLE_DESTROYED
 *	SCF_ERROR_INTERNAL
 *	SCF_ERROR_INVALID_ARGUMENT
 *	SCF_ERROR_NO_MEMORY
 *	SCF_ERROR_NO_RESOURCES
 *	SCF_ERROR_NOT_BOUND
 *	SCF_ERROR_NOT_FOUND
 *	SCF_ERROR_NOT_SET
 *	SCF_ERROR_TYPE_MISMATCH
 *
 */
mc_error_t *
restarter_get_method_context(uint_t version, scf_instance_t *inst,
    scf_snapshot_t *snap, const char *mname, const char *cmdline,
    struct method_context **mcpp)
{
	scf_handle_t *h;
	scf_propertygroup_t *methpg = NULL;
	scf_propertygroup_t *instpg = NULL;
	scf_propertygroup_t *pg = NULL;
	scf_property_t *prop = NULL;
	scf_value_t *val = NULL;
	scf_type_t ty;
	uint8_t use_profile;
	int ret = 0;
	mc_error_t *err = NULL;
	struct method_context *cip;
	enum {
		MCF_FOUND =		1 << 0,
		MCF_ENVIRONMENT =	1 << 1,
		MCF_PROFILE =		1 << 2,
		MCF_IDS =		1 << 3,
		MCF_CWD =		1 << 4,
		MCF_SECFLAGS =		1 << 5,
		MCF_COREFILE =		1 << 6,
		MCF_PROJECT =		1 << 7,
		MCF_RESPOOL =		1 << 8,
	} mc_flags = 0;

	if ((err = malloc(sizeof (mc_error_t))) == NULL)
		return (mc_error_create(NULL, ENOMEM, NULL));

	/* Set the type to zero to track if an error occured. */
	err->type = 0;

	if (version != RESTARTER_METHOD_CONTEXT_VERSION)
		return (mc_error_create(err, ENOTSUP,
		    "Invalid client version %d. (Expected %d)",
		    version, RESTARTER_METHOD_CONTEXT_VERSION));

	/* Get the handle before we allocate anything. */
	h = scf_instance_handle(inst);
	if (h == NULL)
		return (mc_error_create(err, scf_error(),
		    scf_strerror(scf_error())));

	cip = malloc(sizeof (*cip));
	if (cip == NULL)
		return (mc_error_create(err, ENOMEM, ALLOCFAIL));

	(void) memset(cip, 0, sizeof (*cip));
	cip->uid = (uid_t)-1;
	cip->euid = (uid_t)-1;
	cip->gid = (gid_t)-1;
	cip->egid = (gid_t)-1;

	cip->vbuf_sz = scf_limit(SCF_LIMIT_MAX_VALUE_LENGTH);
	assert(cip->vbuf_sz >= 0);
	cip->vbuf = malloc(cip->vbuf_sz);
	if (cip->vbuf == NULL) {
		free(cip);
		return (mc_error_create(err, ENOMEM, ALLOCFAIL));
	}

	if ((instpg = scf_pg_create(h)) == NULL ||
	    (methpg = scf_pg_create(h)) == NULL ||
	    (prop = scf_property_create(h)) == NULL ||
	    (val = scf_value_create(h)) == NULL) {
		err = mc_error_create(err, scf_error(),
		    "Failed to create repository object: %s",
		    scf_strerror(scf_error()));
		goto out;
	}

	/*
	 * The method environment, and the credentials/profile data,
	 * may be found either in the pg for the method (methpg),
	 * or in the instance/service SCF_PG_METHOD_CONTEXT pg (named
	 * instpg below).
	 */

	if (scf_instance_get_pg_composed(inst, snap, mname, methpg) !=
	    SCF_SUCCESS) {
		err = mc_error_create(err, scf_error(), "Unable to get the "
		    "\"%s\" method, %s", mname, scf_strerror(scf_error()));
		goto out;
	}

	if (scf_instance_get_pg_composed(inst, snap, SCF_PG_METHOD_CONTEXT,
	    instpg) != SCF_SUCCESS) {
		if (scf_error() != SCF_ERROR_NOT_FOUND) {
			err = mc_error_create(err, scf_error(),
			    "Unable to retrieve the \"%s\" property group, %s",
			    SCF_PG_METHOD_CONTEXT, scf_strerror(scf_error()));
			goto out;
		}
		scf_pg_destroy(instpg);
		instpg = NULL;
	} else {
		/* Found a method_context */
		mc_flags |= MCF_FOUND;
	}

	ret = get_environment(h, methpg, cip, prop, val);
	if (ret == ENOENT && instpg != NULL) {
		ret = get_environment(h, instpg, cip, prop, val);
	}

	switch (ret) {
	case 0:
		mc_flags |= MCF_ENVIRONMENT;
		break;
	case ENOENT:
		break;
	case ENOMEM:
		err = mc_error_create(err, ret, "Out of memory.");
		goto out;
	case EINVAL:
		err = mc_error_create(err, ret, "Invalid method environment.");
		goto out;
	default:
		err = mc_error_create(err, ret,
		    "Get method environment failed: %s", scf_strerror(ret));
		goto out;
	}

	pg = methpg;

	ret = scf_pg_get_property(pg, SCF_PROPERTY_USE_PROFILE, prop);
	if (ret && scf_error() == SCF_ERROR_NOT_FOUND && instpg != NULL) {
		pg = NULL;
		ret = scf_pg_get_property(instpg, SCF_PROPERTY_USE_PROFILE,
		    prop);
	}

	if (ret) {
		switch (scf_error()) {
		case SCF_ERROR_NOT_FOUND:
			/* No profile context: use default credentials */
			cip->uid = 0;
			cip->gid = 0;
			break;

		case SCF_ERROR_CONNECTION_BROKEN:
			err = mc_error_create(err, SCF_ERROR_CONNECTION_BROKEN,
			    RCBROKEN);
			goto out;

		case SCF_ERROR_DELETED:
			err = mc_error_create(err, SCF_ERROR_NOT_FOUND,
			    "Could not find property group \"%s\"",
			    pg == NULL ? SCF_PG_METHOD_CONTEXT : mname);
			goto out;

		case SCF_ERROR_HANDLE_MISMATCH:
		case SCF_ERROR_INVALID_ARGUMENT:
		case SCF_ERROR_NOT_SET:
		default:
			bad_fail("scf_pg_get_property", scf_error());
		}
	} else {
		if (scf_property_type(prop, &ty) != SCF_SUCCESS) {
			ret = scf_error();
			switch (ret) {
			case SCF_ERROR_CONNECTION_BROKEN:
				err = mc_error_create(err,
				    SCF_ERROR_CONNECTION_BROKEN, RCBROKEN);
				break;

			case SCF_ERROR_DELETED:
				err = mc_error_create(err,
				    SCF_ERROR_NOT_FOUND,
				    "Could not find property group \"%s\"",
				    pg == NULL ? SCF_PG_METHOD_CONTEXT : mname);
				break;

			case SCF_ERROR_NOT_SET:
			default:
				bad_fail("scf_property_type", ret);
			}

			goto out;
		}

		if (ty != SCF_TYPE_BOOLEAN) {
			err = mc_error_create(err,
			    SCF_ERROR_TYPE_MISMATCH,
			    "\"%s\" property is not boolean in property group "
			    "\"%s\".", SCF_PROPERTY_USE_PROFILE,
			    pg == NULL ? SCF_PG_METHOD_CONTEXT : mname);
			goto out;
		}

		if (scf_property_get_value(prop, val) != SCF_SUCCESS) {
			ret = scf_error();
			switch (ret) {
			case SCF_ERROR_CONNECTION_BROKEN:
				err = mc_error_create(err,
				    SCF_ERROR_CONNECTION_BROKEN, RCBROKEN);
				break;

			case SCF_ERROR_CONSTRAINT_VIOLATED:
				err = mc_error_create(err,
				    SCF_ERROR_CONSTRAINT_VIOLATED,
				    "\"%s\" property has multiple values.",
				    SCF_PROPERTY_USE_PROFILE);
				break;

			case SCF_ERROR_NOT_FOUND:
				err = mc_error_create(err,
				    SCF_ERROR_NOT_FOUND,
				    "\"%s\" property has no values.",
				    SCF_PROPERTY_USE_PROFILE);
				break;
			default:
				bad_fail("scf_property_get_value", ret);
			}

			goto out;
		}

		ret = scf_value_get_boolean(val, &use_profile);
		assert(ret == SCF_SUCCESS);

		/* get ids & privileges */
		if (use_profile) {
			mc_flags |= MCF_PROFILE;
			err = get_profile(pg, instpg, prop, val, cmdline,
			    cip, err);
		} else {
			mc_flags |= MCF_IDS;
			err = get_ids(pg, instpg, prop, val, cip, err);
		}

		if (err->type != 0)
			goto out;
	}

	/* get working directory */
	if ((methpg != NULL && scf_pg_get_property(methpg,
	    SCF_PROPERTY_WORKING_DIRECTORY, prop) == SCF_SUCCESS) ||
	    (instpg != NULL && scf_pg_get_property(instpg,
	    SCF_PROPERTY_WORKING_DIRECTORY, prop) == SCF_SUCCESS)) {
		if (scf_property_get_value(prop, val) != SCF_SUCCESS) {
			ret = scf_error();
			switch (ret) {
			case SCF_ERROR_CONNECTION_BROKEN:
				err = mc_error_create(err, ret, RCBROKEN);
				break;

			case SCF_ERROR_CONSTRAINT_VIOLATED:
				err = mc_error_create(err, ret,
				    "\"%s\" property has multiple values.",
				    SCF_PROPERTY_WORKING_DIRECTORY);
				break;

			case SCF_ERROR_NOT_FOUND:
				err = mc_error_create(err, ret,
				    "\"%s\" property has no values.",
				    SCF_PROPERTY_WORKING_DIRECTORY);
				break;

			default:
				bad_fail("scf_property_get_value", ret);
			}

			goto out;
		}

		mc_flags |= MCF_CWD;
		ret = scf_value_get_astring(val, cip->vbuf, cip->vbuf_sz);
		assert(ret != -1);
	} else {
		ret = scf_error();
		switch (ret) {
		case SCF_ERROR_NOT_FOUND:
			/* okay if missing. */
			(void) strcpy(cip->vbuf, ":default");
			break;

		case SCF_ERROR_CONNECTION_BROKEN:
			err = mc_error_create(err, ret, RCBROKEN);
			goto out;

		case SCF_ERROR_DELETED:
			err = mc_error_create(err, ret,
			    "Property group could not be found");
			goto out;

		case SCF_ERROR_HANDLE_MISMATCH:
		case SCF_ERROR_INVALID_ARGUMENT:
		case SCF_ERROR_NOT_SET:
		default:
			bad_fail("scf_pg_get_property", ret);
		}
	}

	if (strcmp(cip->vbuf, ":default") == 0 ||
	    strcmp(cip->vbuf, ":home") == 0) {
		switch (ret = lookup_pwd(cip)) {
		case 0:
			break;

		case ENOMEM:
			err = mc_error_create(err, ret, "Out of memory.");
			goto out;

		case ENOENT:
		case EIO:
		case EMFILE:
		case ENFILE:
			err = mc_error_create(err, ret,
			    "Could not get passwd entry.");
			goto out;

		default:
			bad_fail("lookup_pwd", ret);
		}

		cip->working_dir = strdup(cip->pwd.pw_dir);
		if (cip->working_dir == NULL) {
			err = mc_error_create(err, ENOMEM, ALLOCFAIL);
			goto out;
		}
	} else {
		cip->working_dir = strdup(cip->vbuf);
		if (cip->working_dir == NULL) {
			err = mc_error_create(err, ENOMEM, ALLOCFAIL);
			goto out;
		}
	}

	/* get security flags */
	if ((methpg != NULL && scf_pg_get_property(methpg,
	    SCF_PROPERTY_SECFLAGS, prop) == SCF_SUCCESS) ||
	    (instpg != NULL && scf_pg_get_property(instpg,
	    SCF_PROPERTY_SECFLAGS, prop) == SCF_SUCCESS)) {
		if (scf_property_get_value(prop, val) != SCF_SUCCESS) {
			ret = scf_error();
			switch (ret) {
			case SCF_ERROR_CONNECTION_BROKEN:
				err = mc_error_create(err, ret, RCBROKEN);
				break;

			case SCF_ERROR_CONSTRAINT_VIOLATED:
				err = mc_error_create(err, ret,
				    "\"%s\" property has multiple values.",
				    SCF_PROPERTY_SECFLAGS);
				break;

			case SCF_ERROR_NOT_FOUND:
				err = mc_error_create(err, ret,
				    "\"%s\" property has no values.",
				    SCF_PROPERTY_SECFLAGS);
				break;

			default:
				bad_fail("scf_property_get_value", ret);
			}

			(void) strlcpy(cip->vbuf, ":default", cip->vbuf_sz);
		} else {
			ret = scf_value_get_astring(val, cip->vbuf,
			    cip->vbuf_sz);
			assert(ret != -1);
		}
		mc_flags |= MCF_SECFLAGS;
	} else {
		ret = scf_error();
		switch (ret) {
		case SCF_ERROR_NOT_FOUND:
			/* okay if missing. */
			(void) strlcpy(cip->vbuf, ":default", cip->vbuf_sz);
			break;

		case SCF_ERROR_CONNECTION_BROKEN:
			err = mc_error_create(err, ret, RCBROKEN);
			goto out;

		case SCF_ERROR_DELETED:
			err = mc_error_create(err, ret,
			    "Property group could not be found");
			goto out;

		case SCF_ERROR_HANDLE_MISMATCH:
		case SCF_ERROR_INVALID_ARGUMENT:
		case SCF_ERROR_NOT_SET:
		default:
			bad_fail("scf_pg_get_property", ret);
		}
	}


	if (scf_default_secflags(h, &cip->def_secflags) != 0) {
		err = mc_error_create(err, EINVAL, "couldn't fetch "
		    "default security-flags");
		goto out;
	}

	if (strcmp(cip->vbuf, ":default") != 0) {
		if (secflags_parse(NULL, cip->vbuf,
		    &cip->secflag_delta) != 0) {
			err = mc_error_create(err, EINVAL, "couldn't parse "
			    "security flags: %s", cip->vbuf);
			goto out;
		}
	}

	/* get (optional) corefile pattern */
	if ((methpg != NULL && scf_pg_get_property(methpg,
	    SCF_PROPERTY_COREFILE_PATTERN, prop) == SCF_SUCCESS) ||
	    (instpg != NULL && scf_pg_get_property(instpg,
	    SCF_PROPERTY_COREFILE_PATTERN, prop) == SCF_SUCCESS)) {
		if (scf_property_get_value(prop, val) != SCF_SUCCESS) {
			ret = scf_error();
			switch (ret) {
			case SCF_ERROR_CONNECTION_BROKEN:
				err = mc_error_create(err, ret, RCBROKEN);
				break;

			case SCF_ERROR_CONSTRAINT_VIOLATED:
				err = mc_error_create(err, ret,
				    "\"%s\" property has multiple values.",
				    SCF_PROPERTY_COREFILE_PATTERN);
				break;

			case SCF_ERROR_NOT_FOUND:
				err = mc_error_create(err, ret,
				    "\"%s\" property has no values.",
				    SCF_PROPERTY_COREFILE_PATTERN);
				break;

			default:
				bad_fail("scf_property_get_value", ret);
			}

		} else {

			ret = scf_value_get_astring(val, cip->vbuf,
			    cip->vbuf_sz);
			assert(ret != -1);

			cip->corefile_pattern = strdup(cip->vbuf);
			if (cip->corefile_pattern == NULL) {
				err = mc_error_create(err, ENOMEM, ALLOCFAIL);
				goto out;
			}
		}

		mc_flags |= MCF_COREFILE;
	} else {
		ret = scf_error();
		switch (ret) {
		case SCF_ERROR_NOT_FOUND:
			/* okay if missing. */
			break;

		case SCF_ERROR_CONNECTION_BROKEN:
			err = mc_error_create(err, ret, RCBROKEN);
			goto out;

		case SCF_ERROR_DELETED:
			err = mc_error_create(err, ret,
			    "Property group could not be found");
			goto out;

		case SCF_ERROR_HANDLE_MISMATCH:
		case SCF_ERROR_INVALID_ARGUMENT:
		case SCF_ERROR_NOT_SET:
		default:
			bad_fail("scf_pg_get_property", ret);
		}
	}

	if (restarter_rm_libs_loadable()) {
		/* get project */
		if ((methpg != NULL && scf_pg_get_property(methpg,
		    SCF_PROPERTY_PROJECT, prop) == SCF_SUCCESS) ||
		    (instpg != NULL && scf_pg_get_property(instpg,
		    SCF_PROPERTY_PROJECT, prop) == SCF_SUCCESS)) {
			if (scf_property_get_value(prop, val) != SCF_SUCCESS) {
				ret = scf_error();
				switch (ret) {
				case SCF_ERROR_CONNECTION_BROKEN:
					err = mc_error_create(err, ret,
					    RCBROKEN);
					break;

				case SCF_ERROR_CONSTRAINT_VIOLATED:
					err = mc_error_create(err, ret,
					    "\"%s\" property has multiple "
					    "values.", SCF_PROPERTY_PROJECT);
					break;

				case SCF_ERROR_NOT_FOUND:
					err = mc_error_create(err, ret,
					    "\"%s\" property has no values.",
					    SCF_PROPERTY_PROJECT);
					break;

				default:
					bad_fail("scf_property_get_value", ret);
				}

				(void) strcpy(cip->vbuf, ":default");
			} else {
				ret = scf_value_get_astring(val, cip->vbuf,
				    cip->vbuf_sz);
				assert(ret != -1);
			}

			mc_flags |= MCF_PROJECT;
		} else {
			(void) strcpy(cip->vbuf, ":default");
		}

		switch (ret = get_projid(cip->vbuf, cip)) {
		case 0:
			break;

		case ENOMEM:
			err = mc_error_create(err, ret, "Out of memory.");
			goto out;

		case ENOENT:
			err = mc_error_create(err, ret,
			    "Missing passwd or project entry for \"%s\".",
			    cip->vbuf);
			goto out;

		case EIO:
			err = mc_error_create(err, ret, "I/O error.");
			goto out;

		case EMFILE:
		case ENFILE:
			err = mc_error_create(err, ret,
			    "Out of file descriptors.");
			goto out;

		case -1:
			err = mc_error_create(err, ret,
			    "Name service switch is misconfigured.");
			goto out;

		case ERANGE:
		case E2BIG:
			err = mc_error_create(err, ret,
			    "Project ID \"%s\" too big.", cip->vbuf);
			goto out;

		case EINVAL:
			err = mc_error_create(err, ret,
			    "Project ID \"%s\" is invalid.", cip->vbuf);
			goto out;

		default:
			bad_fail("get_projid", ret);
		}

		/* get resource pool */
		if ((methpg != NULL && scf_pg_get_property(methpg,
		    SCF_PROPERTY_RESOURCE_POOL, prop) == SCF_SUCCESS) ||
		    (instpg != NULL && scf_pg_get_property(instpg,
		    SCF_PROPERTY_RESOURCE_POOL, prop) == SCF_SUCCESS)) {
			if (scf_property_get_value(prop, val) != SCF_SUCCESS) {
				ret = scf_error();
				switch (ret) {
				case SCF_ERROR_CONNECTION_BROKEN:
					err = mc_error_create(err, ret,
					    RCBROKEN);
					break;

				case SCF_ERROR_CONSTRAINT_VIOLATED:
					err = mc_error_create(err, ret,
					    "\"%s\" property has multiple "
					    "values.",
					    SCF_PROPERTY_RESOURCE_POOL);
					break;

				case SCF_ERROR_NOT_FOUND:
					err = mc_error_create(err, ret,
					    "\"%s\" property has no "
					    "values.",
					    SCF_PROPERTY_RESOURCE_POOL);
					break;

				default:
					bad_fail("scf_property_get_value", ret);
				}

				(void) strcpy(cip->vbuf, ":default");
			} else {
				ret = scf_value_get_astring(val, cip->vbuf,
				    cip->vbuf_sz);
				assert(ret != -1);
			}

			mc_flags |= MCF_RESPOOL;
		} else {
			ret = scf_error();
			switch (ret) {
			case SCF_ERROR_NOT_FOUND:
				/* okay if missing. */
				(void) strcpy(cip->vbuf, ":default");
				break;

			case SCF_ERROR_CONNECTION_BROKEN:
				err = mc_error_create(err, ret, RCBROKEN);
				goto out;

			case SCF_ERROR_DELETED:
				err = mc_error_create(err, ret,
				    "property group could not be found.");
				goto out;

			case SCF_ERROR_HANDLE_MISMATCH:
			case SCF_ERROR_INVALID_ARGUMENT:
			case SCF_ERROR_NOT_SET:
			default:
				bad_fail("scf_pg_get_property", ret);
			}
		}

		if (strcmp(cip->vbuf, ":default") != 0) {
			cip->resource_pool = strdup(cip->vbuf);
			if (cip->resource_pool == NULL) {
				err = mc_error_create(err, ENOMEM, ALLOCFAIL);
				goto out;
			}
		}
	}

	if ((mc_flags & ~MCF_FOUND) == 0) {
		/*
		 * A method_context was not used for any configurable
		 * elements or attributes, so reset and use the simple
		 * defaults that provide historic init behavior.
		 */
		free(cip->pwbuf);
		free(cip->vbuf);
		free(cip->working_dir);

		(void) memset(cip, 0, sizeof (*cip));
		cip->uid = 0;
		cip->gid = 0;
		cip->euid = (uid_t)-1;
		cip->egid = (gid_t)-1;

		if (scf_default_secflags(h, &cip->def_secflags) != 0) {
			err = mc_error_create(err, EINVAL, "couldn't fetch "
			    "default security-flags");
			goto out;
		}
	} else if ((mc_flags & (MCF_PROFILE | MCF_IDS | MCF_CWD)) == 0) {
		/*
		 * A method context was used to configure some elements, but
		 * not for any of profile/user/group/working_dir.
		 * Reset the directory to '/' for historic init behaviour.
		 */
		free(cip->working_dir);
		cip->working_dir = NULL;
	}

	*mcpp = cip;

out:
	(void) scf_value_destroy(val);
	scf_property_destroy(prop);
	scf_pg_destroy(instpg);
	scf_pg_destroy(methpg);

	if (cip->pwbuf != NULL) {
		free(cip->pwbuf);
		cip->pwbuf = NULL;
	}

	free(cip->vbuf);

	if (err->type != 0) {
		restarter_free_method_context(cip);
	} else {
		restarter_mc_error_destroy(err);
		err = NULL;
	}

	return (err);
}

/*
 * Modify the current process per the given method_context.  On success, returns
 * 0.  Note that the environment is not modified by this function to include the
 * environment variables in cip->env.
 *
 * On failure, sets *fp to NULL or the name of the function which failed,
 * and returns one of the following error codes.  The words in parentheses are
 * the values to which *fp may be set for the error case.
 *   ENOMEM - malloc() failed
 *   EIO - an I/O error occurred (getpwuid_r, chdir)
 *   EMFILE - process is out of file descriptors (getpwuid_r)
 *   ENFILE - system is out of file handles (getpwuid_r)
 *   EINVAL - gid or egid is out of range (setregid)
 *	      ngroups is too big (setgroups)
 *	      project's project id is bad (setproject)
 *	      uid or euid is out of range (setreuid)
 *	      poolname is invalid (pool_set_binding)
 *   EPERM - insufficient privilege (setregid, initgroups, setgroups, setppriv,
 *	         setproject, setreuid, settaskid)
 *   ENOENT - uid has a passwd entry but no shadow entry
 *	      working_dir does not exist (chdir)
 *	      uid has no passwd entry
 *	      the pool could not be found (pool_set_binding)
 *   EFAULT - lpriv_set or priv_set has a bad address (setppriv)
 *	      working_dir has a bad address (chdir)
 *   EACCES - could not access working_dir (chdir)
 *	      in a TASK_FINAL task (setproject, settaskid)
 *	      no resource pool accepting default binding exists (setproject)
 *   ELOOP - too many symbolic links in working_dir (chdir)
 *   ENAMETOOLONG - working_dir is too long (chdir)
 *   ENOLINK - working_dir is on an inaccessible remote machine (chdir)
 *   ENOTDIR - working_dir is not a directory (chdir)
 *   ESRCH - uid is not a user of project (setproject)
 *	     project is invalid (setproject)
 *	     the resource pool specified for project is unknown (setproject)
 *   EBADF - the configuration for the pool is invalid (pool_set_binding)
 *   -1 - core_set_process_path() failed (core_set_process_path)
 *	  a resource control assignment failed (setproject)
 *	  a system error occurred during pool_set_binding (pool_set_binding)
 */
int
restarter_set_method_context(struct method_context *cip, const char **fp)
{
	pid_t mypid = -1;
	int r, ret;

	cip->pwbuf = NULL;
	*fp = NULL;

	if (cip->gid != (gid_t)-1) {
		if (setregid(cip->gid,
		    cip->egid != (gid_t)-1 ? cip->egid : cip->gid) != 0) {
			*fp = "setregid";

			ret = errno;
			assert(ret == EINVAL || ret == EPERM);
			goto out;
		}
	} else {
		if (cip->pwbuf == NULL) {
			switch (ret = lookup_pwd(cip)) {
			case 0:
				break;

			case ENOMEM:
			case ENOENT:
				*fp = NULL;
				goto out;

			case EIO:
			case EMFILE:
			case ENFILE:
				*fp = "getpwuid_r";
				goto out;

			default:
				bad_fail("lookup_pwd", ret);
			}
		}

		if (setregid(cip->pwd.pw_gid,
		    cip->egid != (gid_t)-1 ?
		    cip->egid : cip->pwd.pw_gid) != 0) {
			*fp = "setregid";

			ret = errno;
			assert(ret == EINVAL || ret == EPERM);
			goto out;
		}
	}

	if (cip->ngroups == -1) {
		if (cip->pwbuf == NULL) {
			switch (ret = lookup_pwd(cip)) {
			case 0:
				break;

			case ENOMEM:
			case ENOENT:
				*fp = NULL;
				goto out;

			case EIO:
			case EMFILE:
			case ENFILE:
				*fp = "getpwuid_r";
				goto out;

			default:
				bad_fail("lookup_pwd", ret);
			}
		}

		/* Ok if cip->gid == -1 */
		if (initgroups(cip->pwd.pw_name, cip->gid) != 0) {
			*fp = "initgroups";
			ret = errno;
			assert(ret == EPERM);
			goto out;
		}
	} else if (cip->ngroups > 0 &&
	    setgroups(cip->ngroups, cip->groups) != 0) {
		*fp = "setgroups";

		ret = errno;
		assert(ret == EINVAL || ret == EPERM);
		goto out;
	}

	if (cip->corefile_pattern != NULL) {
		mypid = getpid();

		if (core_set_process_path(cip->corefile_pattern,
		    strlen(cip->corefile_pattern) + 1, mypid) != 0) {
			*fp = "core_set_process_path";
			ret = -1;
			goto out;
		}
	}


	if (psecflags(P_PID, P_MYID, PSF_INHERIT,
	    &cip->def_secflags.ss_default) != 0) {
		*fp = "psecflags (default inherit)";
		ret = errno;
		goto out;
	}

	if (psecflags(P_PID, P_MYID, PSF_LOWER,
	    &cip->def_secflags.ss_lower) != 0) {
		*fp = "psecflags (default lower)";
		ret = errno;
		goto out;
	}

	if (psecflags(P_PID, P_MYID, PSF_UPPER,
	    &cip->def_secflags.ss_upper) != 0) {
		*fp = "psecflags (default upper)";
		ret = errno;
		goto out;
	}

	if (psecflags(P_PID, P_MYID, PSF_INHERIT,
	    &cip->secflag_delta) != 0) {
		*fp = "psecflags (from manifest)";
		ret = errno;
		goto out;
	}

	if (restarter_rm_libs_loadable()) {
		if (cip->project == NULL) {
			if (settaskid(getprojid(), TASK_NORMAL) == -1) {
				switch (errno) {
				case EACCES:
				case EPERM:
					*fp = "settaskid";
					ret = errno;
					goto out;

				case EINVAL:
				default:
					bad_fail("settaskid", errno);
				}
			}
		} else {
			switch (ret = lookup_pwd(cip)) {
			case 0:
				break;

			case ENOMEM:
			case ENOENT:
				*fp = NULL;
				goto out;

			case EIO:
			case EMFILE:
			case ENFILE:
				*fp = "getpwuid_r";
				goto out;

			default:
				bad_fail("lookup_pwd", ret);
			}

			*fp = "setproject";

			switch (setproject(cip->project, cip->pwd.pw_name,
			    TASK_NORMAL)) {
			case 0:
				break;

			case SETPROJ_ERR_TASK:
			case SETPROJ_ERR_POOL:
				ret = errno;
				goto out;

			default:
				ret = -1;
				goto out;
			}
		}

		if (cip->resource_pool != NULL) {
			if (mypid == -1)
				mypid = getpid();

			*fp = "pool_set_binding";

			if (pool_set_binding(cip->resource_pool, P_PID,
			    mypid) != PO_SUCCESS) {
				switch (pool_error()) {
				case POE_INVALID_SEARCH:
					ret = ENOENT;
					break;

				case POE_BADPARAM:
					ret = EINVAL;
					break;

				case POE_INVALID_CONF:
					ret = EBADF;
					break;

				case POE_SYSTEM:
					ret = -1;
					break;

				default:
					bad_fail("pool_set_binding",
					    pool_error());
				}

				goto out;
			}
		}
	}

	/*
	 * Now, we have to assume our ID. If the UID is 0, we want it to be
	 * privilege-aware, otherwise the limit set gets used instead of E/P.
	 * We can do this by setting P as well, which keeps
	 * PA status (see priv_can_clear_PA()).
	 */

	*fp = "setppriv";

	if (cip->lpriv_set != NULL) {
		if (setppriv(PRIV_SET, PRIV_LIMIT, cip->lpriv_set) != 0) {
			ret = errno;
			assert(ret == EFAULT || ret == EPERM);
			goto out;
		}
	}
	if (cip->priv_set != NULL) {
		if (setppriv(PRIV_SET, PRIV_INHERITABLE, cip->priv_set) != 0) {
			ret = errno;
			assert(ret == EFAULT || ret == EPERM);
			goto out;
		}
	}

	/*
	 * If the limit privset is already set, then must be privilege
	 * aware.  Otherwise, don't assume anything, and force privilege
	 * aware status.
	 */

	if (cip->lpriv_set == NULL && cip->priv_set != NULL) {
		ret = setpflags(PRIV_AWARE, 1);
		assert(ret == 0);
	}

	*fp = "setreuid";
	if (setreuid(cip->uid,
	    cip->euid != (uid_t)-1 ? cip->euid : cip->uid) != 0) {
		ret = errno;
		assert(ret == EINVAL || ret == EPERM);
		goto out;
	}

	*fp = "setppriv";
	if (cip->priv_set != NULL) {
		if (setppriv(PRIV_SET, PRIV_PERMITTED, cip->priv_set) != 0) {
			ret = errno;
			assert(ret == EFAULT || ret == EPERM);
			goto out;
		}
	}

	/*
	 * The last thing to do is chdir to the specified working directory.
	 * This should come after the uid switching as only the user might
	 * have access to the specified directory.
	 */
	if (cip->working_dir != NULL) {
		do {
			r = chdir(cip->working_dir);
		} while (r != 0 && errno == EINTR);
		if (r != 0) {
			*fp = "chdir";
			ret = errno;
			goto out;
		}
	}

	ret = 0;
out:
	free(cip->pwbuf);
	cip->pwbuf = NULL;
	return (ret);
}

void
restarter_free_method_context(struct method_context *mcp)
{
	size_t i;

	if (mcp->lpriv_set != NULL)
		priv_freeset(mcp->lpriv_set);
	if (mcp->priv_set != NULL)
		priv_freeset(mcp->priv_set);

	if (mcp->env != NULL) {
		for (i = 0; i < mcp->env_sz; i++)
			free(mcp->env[i]);
		free(mcp->env);
	}

	free(mcp->working_dir);
	free(mcp->corefile_pattern);
	free(mcp->project);
	free(mcp->resource_pool);
	free(mcp);
}

/*
 * Method keyword functions
 */

int
restarter_is_null_method(const char *meth)
{
	return (strcmp(meth, MKW_TRUE) == 0);
}

static int
is_kill_method(const char *method, const char *kill_str,
    size_t kill_str_len)
{
	const char *cp;
	int sig;

	if (strncmp(method, kill_str, kill_str_len) != 0 ||
	    (method[kill_str_len] != '\0' &&
	    !isspace(method[kill_str_len])))
		return (-1);

	cp = method + kill_str_len;
	while (*cp != '\0' && isspace(*cp))
		++cp;

	if (*cp == '\0')
		return (SIGTERM);

	if (*cp != '-')
		return (-1);

	return (str2sig(cp + 1, &sig) == 0 ? sig : -1);
}

int
restarter_is_kill_proc_method(const char *method)
{
	return (is_kill_method(method, MKW_KILL_PROC,
	    sizeof (MKW_KILL_PROC) - 1));
}

int
restarter_is_kill_method(const char *method)
{
	return (is_kill_method(method, MKW_KILL, sizeof (MKW_KILL) - 1));
}

/*
 * Stubs for now.
 */

/* ARGSUSED */
int
restarter_event_get_enabled(restarter_event_t *e)
{
	return (-1);
}

/* ARGSUSED */
uint64_t
restarter_event_get_seq(restarter_event_t *e)
{
	return (-1);
}

/* ARGSUSED */
void
restarter_event_get_time(restarter_event_t *e, hrtime_t *time)
{
}

/*
 * Check for and validate fmri specified in restarter_actions/auxiliary_fmri
 * 0 - Success
 * 1 - Failure
 */
int
restarter_inst_validate_ractions_aux_fmri(scf_instance_t *inst)
{
	scf_handle_t *h;
	scf_propertygroup_t *pg;
	scf_property_t *prop;
	scf_value_t *val;
	char *aux_fmri;
	size_t size = scf_limit(SCF_LIMIT_MAX_VALUE_LENGTH);
	int ret = 1;

	if ((aux_fmri = malloc(size)) == NULL)
		return (1);

	h = scf_instance_handle(inst);

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

	if (instance_get_or_add_pg(inst, SCF_PG_RESTARTER_ACTIONS,
	    SCF_PG_RESTARTER_ACTIONS_TYPE, SCF_PG_RESTARTER_ACTIONS_FLAGS,
	    pg) != SCF_SUCCESS)
		goto out;

	if (get_astring_val(pg, SCF_PROPERTY_AUX_FMRI, aux_fmri, size,
	    prop, val) != SCF_SUCCESS)
		goto out;

	if (scf_parse_fmri(aux_fmri, NULL, NULL, NULL, NULL, NULL,
	    NULL) != SCF_SUCCESS)
		goto out;

	ret = 0;

out:
	free(aux_fmri);
	scf_value_destroy(val);
	scf_property_destroy(prop);
	scf_pg_destroy(pg);
	return (ret);
}

/*
 * Get instance's boolean value in restarter_actions/auxiliary_tty
 * Return -1 on failure
 */
int
restarter_inst_ractions_from_tty(scf_instance_t *inst)
{
	scf_handle_t *h;
	scf_propertygroup_t *pg;
	scf_property_t *prop;
	scf_value_t *val;
	uint8_t	has_tty;
	int ret = -1;

	h = scf_instance_handle(inst);
	pg = scf_pg_create(h);
	prop = scf_property_create(h);
	val = scf_value_create(h);
	if (pg == NULL || prop == NULL || val == NULL)
		goto out;

	if (instance_get_or_add_pg(inst, SCF_PG_RESTARTER_ACTIONS,
	    SCF_PG_RESTARTER_ACTIONS_TYPE, SCF_PG_RESTARTER_ACTIONS_FLAGS,
	    pg) != SCF_SUCCESS)
		goto out;

	if (get_boolean_val(pg, SCF_PROPERTY_AUX_TTY, &has_tty, prop,
	    val) != SCF_SUCCESS)
		goto out;

	ret = has_tty;

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

/*
 * If the instance's dump-on-restart property exists, remove it and return true,
 * otherwise return false.
 */
int
restarter_inst_dump(scf_instance_t *inst)
{
	scf_handle_t *h;
	scf_propertygroup_t *pg;
	scf_property_t *prop;
	scf_value_t *val;
	int ret = 0;

	h = scf_instance_handle(inst);
	pg = scf_pg_create(h);
	prop = scf_property_create(h);
	val = scf_value_create(h);
	if (pg == NULL || prop == NULL || val == NULL)
		goto out;

	if (scf_instance_get_pg(inst, SCF_PG_RESTARTER_ACTIONS, pg) !=
	    SCF_SUCCESS) {
		if (scf_error() == SCF_ERROR_CONNECTION_BROKEN)
			uu_die(rcbroken);
		goto out;
	}

	if (scf_pg_get_property(pg, SCF_PROPERTY_DODUMP, prop) != SCF_SUCCESS) {
		if (scf_error() == SCF_ERROR_CONNECTION_BROKEN)
			uu_die(rcbroken);
		goto out;
	}

	ret = 1;

	if (scf_instance_delete_prop(inst, SCF_PG_RESTARTER_ACTIONS,
	    SCF_PROPERTY_DODUMP) != SCF_SUCCESS) {
		if (scf_error() == SCF_ERROR_CONNECTION_BROKEN)
			uu_die(rcbroken);
		goto out;
	}

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

static int
restarter_inst_set_astring_prop(scf_instance_t *inst, const char *pgname,
    const char *pgtype, uint32_t pgflags, const char *pname, const char *str)
{
	scf_handle_t *h;
	scf_propertygroup_t *pg;
	scf_transaction_t *t;
	scf_transaction_entry_t *e;
	scf_value_t *v;
	int ret = 1, r;

	h = scf_instance_handle(inst);

	pg = scf_pg_create(h);
	t = scf_transaction_create(h);
	e = scf_entry_create(h);
	v = scf_value_create(h);
	if (pg == NULL || t == NULL || e == NULL || v == NULL)
		goto out;

	if (instance_get_or_add_pg(inst, pgname, pgtype, pgflags, pg))
		goto out;

	if (scf_value_set_astring(v, str) != SCF_SUCCESS)
		goto out;

	for (;;) {
		if (scf_transaction_start(t, pg) != 0)
			goto out;

		if (tx_set_value(t, e, pname, SCF_TYPE_ASTRING, v) != 0)
			goto out;

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

		if (r == -1)
			goto out;

		scf_transaction_reset(t);
		if (scf_pg_update(pg) == -1)
			goto out;
	}
	ret = 0;

out:
	scf_transaction_destroy(t);
	scf_entry_destroy(e);
	scf_value_destroy(v);
	scf_pg_destroy(pg);

	return (ret);
}

int
restarter_inst_set_aux_fmri(scf_instance_t *inst)
{
	scf_handle_t *h;
	scf_propertygroup_t *pg;
	scf_property_t *prop;
	scf_value_t *val;
	char *aux_fmri;
	size_t size = scf_limit(SCF_LIMIT_MAX_VALUE_LENGTH);
	int ret = 1;

	if ((aux_fmri = malloc(size)) == NULL)
		return (1);

	h = scf_instance_handle(inst);

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

	/*
	 * Get auxiliary_fmri value from restarter_actions pg
	 */
	if (instance_get_or_add_pg(inst, SCF_PG_RESTARTER_ACTIONS,
	    SCF_PG_RESTARTER_ACTIONS_TYPE, SCF_PG_RESTARTER_ACTIONS_FLAGS,
	    pg) != SCF_SUCCESS)
		goto out;

	if (get_astring_val(pg, SCF_PROPERTY_AUX_FMRI, aux_fmri, size,
	    prop, val) != SCF_SUCCESS)
		goto out;

	/*
	 * Populate restarter/auxiliary_fmri with the obtained fmri.
	 */
	ret = restarter_inst_set_astring_prop(inst, SCF_PG_RESTARTER,
	    SCF_PG_RESTARTER_TYPE, SCF_PG_RESTARTER_FLAGS,
	    SCF_PROPERTY_AUX_FMRI, aux_fmri);

out:
	free(aux_fmri);
	scf_value_destroy(val);
	scf_property_destroy(prop);
	scf_pg_destroy(pg);
	return (ret);
}

int
restarter_inst_reset_aux_fmri(scf_instance_t *inst)
{
	return (scf_instance_delete_prop(inst,
	    SCF_PG_RESTARTER, SCF_PROPERTY_AUX_FMRI));
}

int
restarter_inst_reset_ractions_aux_fmri(scf_instance_t *inst)
{
	return (scf_instance_delete_prop(inst,
	    SCF_PG_RESTARTER_ACTIONS, SCF_PROPERTY_AUX_FMRI));
}