|
root / base / usr / src / cmd / cmd-inet / lib / ipmgmtd
ipmgmtd Plain Text 4197 lines 112.9 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
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#

#
# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2021 Tintri by DDN, Inc. All rights reserved.
#

# Needed for ROOTFS_LIBDIR definition
include		../../../../lib/Makefile.lib

PROG=		ipmgmtd
OBJS=		ipmgmt_main.o ipmgmt_door.o ipmgmt_persist.o ipmgmt_util.o
SRCS=		$(OBJS:.o=.c)
SVCMETHOD=	net-ipmgmt
MANIFEST=	network-ipmgmt.xml
CFGFILES=	ipadm.conf

# Needed for ROOTETC definition
include		../../../Makefile.cmd

ROOTCFGDIR=		$(ROOTETC)/ipadm
ROOTCFGFILES=		$(CFGFILES:%=$(ROOTCFGDIR)/%)
ROOTMANIFESTDIR=	$(ROOTSVCNETWORK)

$(ROOTCFGFILES)	: OWNER= ipadm
$(ROOTCFGFILES)	: GROUP= sys
$(ROOTCFGFILES)	: FILEMODE= 644

ROOTCMDDIR=	$(ROOTFS_LIBDIR)/inet

LDLIBS += -lipadm -lnvpair -lsecdb -lnsl -lumem -lscf

#
# Instrument ipmgmtd with CTF data to ease debugging.
#
CTFCONVERT_HOOK = && $(CTFCONVERT_O)
CTFMERGE_HOOK = && $(CTFMERGE) -L VERSION -o $@ $(OBJS)
$(OBJS) : CFLAGS += $(CTF_FLAGS)

.KEEP_STATE:

.PARALLEL:

all: $(PROG)

$(PROG): $(OBJS)
	$(LINK.c) -o $@ $(OBJS) $(LDLIBS) $(CTFMERGE_HOOK)
	$(POST_PROCESS)

install: $(ROOTCMD) $(ROOTMANIFEST) $(ROOTSVCMETHOD) $(ROOTCFGDIR) \
	$(ROOTCFGFILES)

check:  $(SRCS) $(HEADERS) $(CHKMANIFEST)
	$(CSTYLE) -cpP $(SRCS) $(HEADERS)

$(ROOTCMD): $(PROG)

clean:
	$(RM) $(OBJS)

lint:	lint_SRCS

$(ROOTCFGDIR):
	$(INS.dir)

# Hammerhead: order-only prerequisite so $< is the file, not the directory
$(ROOTCFGDIR)/%: % | $(ROOTCFGDIR)
	$(INS.file)

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

/*
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 2016-2017, Chris Fraire <cfraire@me.com>.
 * Copyright 2021, Tintri by DDN. All rights reserved.
 * Copyright 2022, Oxide Computer Company.
 */

/*
 * Main door handler functions used by ipmgmtd to process the different door
 * call requests, issued by the library libipadm.so.
 */

#include <alloca.h>
#include <pwd.h>
#include <auth_attr.h>
#include <secdb.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <assert.h>
#include <libnvpair.h>
#include "ipmgmt_impl.h"


static void ipmgmt_common_handler(char *, char *, db_wfunc_t *);

/* Handler declaration for each door command */
typedef void ipmgmt_door_handler_t(void *argp);

static ipmgmt_door_handler_t	ipmgmt_getaddr_handler,
				ipmgmt_getprop_handler,
				ipmgmt_getif_handler,
				ipmgmt_initif_handler,
				ipmgmt_aobjop_handler,
				ipmgmt_resetaddr_handler,
				ipmgmt_setif_handler,
				ipmgmt_resetif_handler,
				ipmgmt_resetprop_handler,
				ipmgmt_setaddr_handler,
				ipmgmt_setprop_handler,
				ipmgmt_ipmp_update_handler;

typedef struct ipmgmt_door_info_s {
	uint_t			idi_cmd;
	boolean_t		idi_set;
	ipmgmt_door_handler_t	*idi_handler;
} ipmgmt_door_info_t;

/* maps door commands to door handler functions */
static ipmgmt_door_info_t i_ipmgmt_door_info_tbl[] = {
	{ IPMGMT_CMD_SETPROP,		B_TRUE,  ipmgmt_setprop_handler },
	{ IPMGMT_CMD_SETIF,		B_TRUE,  ipmgmt_setif_handler },
	{ IPMGMT_CMD_SETADDR,		B_TRUE,  ipmgmt_setaddr_handler },
	{ IPMGMT_CMD_GETPROP,		B_FALSE, ipmgmt_getprop_handler },
	{ IPMGMT_CMD_GETIF,		B_FALSE, ipmgmt_getif_handler },
	{ IPMGMT_CMD_GETADDR,		B_FALSE, ipmgmt_getaddr_handler },
	{ IPMGMT_CMD_RESETIF,		B_TRUE,  ipmgmt_resetif_handler },
	{ IPMGMT_CMD_RESETADDR,		B_TRUE,  ipmgmt_resetaddr_handler },
	{ IPMGMT_CMD_RESETPROP,		B_TRUE,  ipmgmt_resetprop_handler },
	{ IPMGMT_CMD_INITIF,		B_TRUE,  ipmgmt_initif_handler },
	{ IPMGMT_CMD_ADDROBJ_LOOKUPADD,	B_TRUE,  ipmgmt_aobjop_handler },
	{ IPMGMT_CMD_ADDROBJ_SETLIFNUM,	B_TRUE,  ipmgmt_aobjop_handler },
	{ IPMGMT_CMD_ADDROBJ_ADD,	B_TRUE,  ipmgmt_aobjop_handler },
	{ IPMGMT_CMD_AOBJNAME2ADDROBJ,	B_FALSE, ipmgmt_aobjop_handler },
	{ IPMGMT_CMD_LIF2ADDROBJ,	B_FALSE, ipmgmt_aobjop_handler },
	{ IPMGMT_CMD_IPMP_UPDATE,	B_FALSE, ipmgmt_ipmp_update_handler},
	{ 0, 0, NULL },
};

/*
 * The main server procedure function that gets invoked for any of the incoming
 * door commands. Inside this function we identify the incoming command and
 * invoke the right door handler function.
 */
/* ARGSUSED */
void
ipmgmt_handler(void *cookie, char *argp, size_t argsz, door_desc_t *dp,
    uint_t n_desc)
{
	ipmgmt_door_info_t	*infop = NULL;
	ipmgmt_retval_t		retval;
	int			i;
	uint_t			err;
	ucred_t			*cred = NULL;

	for (i = 0; i_ipmgmt_door_info_tbl[i].idi_cmd != 0; i++) {
		if (i_ipmgmt_door_info_tbl[i].idi_cmd ==
		    ((ipmgmt_arg_t *)(void *)argp)->ia_cmd) {
			infop = &i_ipmgmt_door_info_tbl[i];
			break;
		}
	}

	if (infop == NULL) {
		ipmgmt_log(LOG_ERR, "Invalid door command specified");
		err = EINVAL;
		goto fail;
	}

	/* check for solaris.network.interface.config authorization */
	if (infop->idi_set) {
		uid_t		uid;
		struct passwd	pwd;
		char		buf[1024];

		if (door_ucred(&cred) != 0) {
			err = errno;
			ipmgmt_log(LOG_ERR, "Could not get user credentials.");
			goto fail;
		}
		uid = ucred_getruid(cred);
		if ((int)uid < 0) {
			err = errno;
			ipmgmt_log(LOG_ERR, "Could not get user id.");
			goto fail;
		}
		if (getpwuid_r(uid, &pwd, buf, sizeof (buf)) ==
		    NULL) {
			err = errno;
			ipmgmt_log(LOG_ERR, "Could not get password entry.");
			goto fail;
		}
		if (chkauthattr(NETWORK_INTERFACE_CONFIG_AUTH,
		    pwd.pw_name) != 1) {
			err = EPERM;
			ipmgmt_log(LOG_ERR, "Not authorized for operation.");
			goto fail;
		}
		ucred_free(cred);
	}

	/* individual handlers take care of calling door_return */
	infop->idi_handler((void *)argp);
	return;
fail:
	ucred_free(cred);
	retval.ir_err = err;
	(void) door_return((char *)&retval, sizeof (retval), NULL, 0);
}

/*
 * Handles the door command IPMGMT_CMD_GETPROP. It retrieves the persisted
 * property value for the given property.
 */
static void
ipmgmt_getprop_handler(void *argp)
{
	ipmgmt_prop_arg_t	*pargp = argp;
	ipmgmt_getprop_rval_t	rval, *rvalp = &rval;

	assert(pargp->ia_cmd == IPMGMT_CMD_GETPROP);

	rvalp->ir_err = ipmgmt_db_walk(ipmgmt_db_getprop, pargp, IPADM_DB_READ);
	if (rvalp->ir_err == 0)
		(void) strlcpy(rvalp->ir_pval, pargp->ia_pval,
		    sizeof (rvalp->ir_pval));
	(void) door_return((char *)rvalp, sizeof (*rvalp), NULL, 0);
}

/*
 * Handles the door command IPMGMT_CMD_SETPROP. It persists the property value
 * for the given property in the DB.
 */
static void
ipmgmt_setprop_handler(void *argp)
{
	ipmgmt_prop_arg_t	*pargp = argp;
	ipmgmt_retval_t		rval;
	ipadm_dbwrite_cbarg_t	cb;
	nvlist_t		*nvl = NULL;
	int			err;

	assert(pargp->ia_cmd == IPMGMT_CMD_SETPROP);

	if ((err = nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0)) != 0)
		goto fail;
	if (pargp->ia_module[0] != '\0' &&
	    (err = nvlist_add_string(nvl, IPADM_NVP_PROTONAME,
	    pargp->ia_module)) != 0) {
		goto fail;
	}
	if (pargp->ia_ifname[0] != '\0' &&
	    (err = nvlist_add_string(nvl, IPADM_NVP_IFNAME,
	    pargp->ia_ifname)) != 0)
		goto fail;
	if (pargp->ia_aobjname[0] != '\0' &&
	    (err = nvlist_add_string(nvl, IPADM_NVP_AOBJNAME,
	    pargp->ia_aobjname)) != 0)
		goto fail;
	if ((err = nvlist_add_string(nvl, pargp->ia_pname,
	    pargp->ia_pval)) != 0)
		goto fail;

	cb.dbw_nvl = nvl;
	cb.dbw_flags = pargp->ia_flags;
	err = ipmgmt_db_walk(ipmgmt_db_update, &cb, IPADM_DB_WRITE);
fail:
	nvlist_free(nvl);
	rval.ir_err = err;
	(void) door_return((char *)&rval, sizeof (rval), NULL, 0);
}

/*
 * Helper function for ipmgmt_setaddr_handler().
 * It converts the nvlist_t, `nvl', to aobjmap node `nodep'.
 */
static int
i_ipmgmt_nvl2aobjnode(nvlist_t *nvl, ipmgmt_aobjmap_t *nodep)
{
	char			*aobjname = NULL, *ifname = NULL;
	int32_t			lnum;
	nvlist_t		*nvladdr;
	sa_family_t		af = AF_UNSPEC;
	ipadm_addr_type_t	addrtype = IPADM_ADDR_NONE;
	int			err = 0;

	/*
	 * Retrieve all the information needed to build '*nodep' from
	 * nvlist_t nvl.
	 */
	if ((err = nvlist_lookup_string(nvl, IPADM_NVP_AOBJNAME,
	    &aobjname)) != 0 ||
	    (err = nvlist_lookup_string(nvl, IPADM_NVP_IFNAME, &ifname)) != 0 ||
	    (err = nvlist_lookup_int32(nvl, IPADM_NVP_LIFNUM, &lnum)) != 0) {
		return (err);
	}
	if (nvlist_exists(nvl, IPADM_NVP_IPV4ADDR)) {
		af = AF_INET;
		addrtype = IPADM_ADDR_STATIC;
	} else if (nvlist_lookup_nvlist(nvl, IPADM_NVP_DHCP, &nvladdr) == 0) {
		char	*reqhost;

		af = AF_INET;
		addrtype = IPADM_ADDR_DHCP;

		/*
		 * ipmgmt_am_reqhost comes through in `nvl' for purposes of
		 * updating the cached representation, but it is persisted as
		 * a stand-alone DB line; so remove it after copying it.
		 */
		if (!nvlist_exists(nvl, IPADM_NVP_REQHOST)) {
			*nodep->ipmgmt_am_reqhost = '\0';
		} else {
			if ((err = nvlist_lookup_string(nvl, IPADM_NVP_REQHOST,
			    &reqhost)) != 0)
				return (err);

			(void) strlcpy(nodep->ipmgmt_am_reqhost, reqhost,
			    sizeof (nodep->ipmgmt_am_reqhost));
			(void) nvlist_remove(nvl, IPADM_NVP_REQHOST,
			    DATA_TYPE_STRING);
		}
	} else if (nvlist_exists(nvl, IPADM_NVP_IPV6ADDR)) {
		af = AF_INET6;
		addrtype = IPADM_ADDR_STATIC;
	} else if (nvlist_lookup_nvlist(nvl, IPADM_NVP_INTFID, &nvladdr) == 0) {
		struct sockaddr_in6		sin6 = {0};
		uint8_t	*addr6;
		uint32_t plen;
		uint_t	n;

		af = AF_INET6;
		addrtype = IPADM_ADDR_IPV6_ADDRCONF;
		if (nvlist_lookup_uint32(nvladdr, IPADM_NVP_PREFIXLEN,
		    &plen) != 0)
			return (EINVAL);
		if (plen != 0) {
			if (nvlist_lookup_uint8_array(nvladdr,
			    IPADM_NVP_IPNUMADDR, &addr6, &n) != 0)
				return (EINVAL);
			bcopy(addr6, &sin6.sin6_addr, n);
		}

		nodep->ipmgmt_am_linklocal = B_TRUE;
		nodep->ipmgmt_am_ifid = sin6;
	}

	/*
	 * populate the non-addrtype-specific `*nodep' with retrieved values.
	 */
	(void) strlcpy(nodep->am_ifname, ifname, sizeof (nodep->am_ifname));
	(void) strlcpy(nodep->am_aobjname, aobjname,
	    sizeof (nodep->am_aobjname));
	nodep->am_lnum = lnum;
	nodep->am_family = af;
	nodep->am_atype = addrtype;
	nodep->am_next = NULL;

	/*
	 * Do not store logical interface number in persistent store as it
	 * takes different value on reboot. So remove it from `nvl'.
	 */
	if (nvlist_exists(nvl, IPADM_NVP_LIFNUM))
		(void) nvlist_remove(nvl, IPADM_NVP_LIFNUM, DATA_TYPE_INT32);

	return (0);
}

/*
 * Handles the door command IPMGMT_CMD_SETADDR. It adds a new address object
 * node to the list `aobjmap' and optionally persists the address
 * information in the DB.
 */
static void
ipmgmt_setaddr_handler(void *argp)
{
	ipmgmt_setaddr_arg_t	*sargp = argp;
	ipmgmt_retval_t		rval;
	ipmgmt_aobjmap_t	node = {0};
	nvlist_t		*nvl = NULL;
	char			*nvlbuf;
	size_t			nvlsize = sargp->ia_nvlsize;
	uint32_t		flags = sargp->ia_flags;
	int			err = 0;

	nvlbuf = (char *)argp + sizeof (ipmgmt_setaddr_arg_t);
	if ((err = nvlist_unpack(nvlbuf, nvlsize, &nvl, 0)) != 0)
		goto ret;
	if (flags & (IPMGMT_ACTIVE|IPMGMT_INIT)) {
		if ((err = i_ipmgmt_nvl2aobjnode(nvl, &node)) != 0)
			goto ret;
		if (flags & IPMGMT_INIT)
			node.am_flags = (IPMGMT_ACTIVE|IPMGMT_PERSIST);
		else
			node.am_flags = flags & ~IPMGMT_PROPS_ONLY;
		if ((err = ipmgmt_aobjmap_op(&node, ADDROBJ_ADD)) != 0)
			goto ret;
	}
	if ((flags & IPMGMT_PERSIST) && !(flags & IPMGMT_PROPS_ONLY)) {
		ipadm_dbwrite_cbarg_t	cb;

		cb.dbw_nvl = nvl;
		cb.dbw_flags = 0;
		err = ipmgmt_db_walk(ipmgmt_db_add, &cb, IPADM_DB_WRITE);
	}
ret:
	nvlist_free(nvl);
	rval.ir_err = err;
	(void) door_return((char *)&rval, sizeof (rval), NULL, 0);
}

/*
 * Handles the door commands that read or modify the `aobjmap' structure.
 *
 * IPMGMT_CMD_ADDROBJ_LOOKUPADD - places a stub address object in `aobjmap'
 *	after ensuring that the namespace is not taken. If required, also
 *	generates an `aobjname' for address object for the library to use.
 * IPMGMT_CMD_ADDROBJ_ADD - add/update address object in `aobjmap'
 * IPMGMT_CMD_LIF2ADDROBJ - given a logical interface, return address object
 *	associated with that logical interface.
 * IPMGMT_CMD_AOBJNAME2ADDROBJ - given an address object name return logical
 *	interface associated with that address object.
 */
static void
ipmgmt_aobjop_handler(void *argp)
{
	ipmgmt_aobjop_arg_t	*largp = argp;
	ipmgmt_retval_t		rval;
	ipmgmt_aobjop_rval_t	aobjrval;
	void			*rvalp;
	size_t			rsize;
	ipmgmt_aobjmap_t	node;
	int			err = 0;
	char			*ifname = largp->ia_ifname;
	char			*aobjname = largp->ia_aobjname;
	int32_t			lnum = largp->ia_lnum;
	sa_family_t		af = largp->ia_family;
	ipadm_addr_type_t	atype = largp->ia_atype;
	ipmgmt_aobjmap_t	*head;

	bzero(&aobjrval, sizeof (aobjrval));
	switch (largp->ia_cmd) {
	case IPMGMT_CMD_ADDROBJ_LOOKUPADD:
		rsize = sizeof (ipmgmt_aobjop_rval_t);
		rvalp = &aobjrval;
		bzero(&node, sizeof (node));
		(void) strlcpy(node.am_aobjname, aobjname,
		    sizeof (node.am_aobjname));
		(void) strlcpy(node.am_ifname, ifname,
		    sizeof (node.am_ifname));
		node.am_family = af;
		node.am_atype = atype;
		if (atype == IPADM_ADDR_IPV6_ADDRCONF) {
			node.ipmgmt_am_linklocal = B_TRUE;
		}
		/* no logical number is associated with this addrobj yet */
		node.am_lnum = -1;
		/* The address object is not persisted yet. */
		node.am_flags = IPMGMT_ACTIVE;
		err = ipmgmt_aobjmap_op(&node, ADDROBJ_LOOKUPADD);
		if (err == 0) {
			aobjrval.ir_lnum = node.am_lnum;
			(void) strlcpy(aobjrval.ir_aobjname, node.am_aobjname,
			    sizeof (aobjrval.ir_aobjname));
		}
		break;
	case IPMGMT_CMD_ADDROBJ_SETLIFNUM:
		rsize = sizeof (ipmgmt_retval_t);
		rvalp = &rval;
		bzero(&node, sizeof (node));
		(void) strlcpy(node.am_aobjname, aobjname,
		    sizeof (node.am_aobjname));
		(void) strlcpy(node.am_ifname, ifname,
		    sizeof (node.am_ifname));
		node.am_family = af;
		node.am_lnum = lnum;
		err = ipmgmt_aobjmap_op(&node, ADDROBJ_SETLIFNUM);
		break;
	case IPMGMT_CMD_ADDROBJ_ADD:
		rsize = sizeof (ipmgmt_retval_t);
		rvalp = &rval;
		if (aobjname[0] == '\0' || ifname[0] == '\0' || lnum == -1 ||
		    af == AF_UNSPEC) {
			err = EINVAL;
			break;
		}
		bzero(&node, sizeof (node));
		(void) strlcpy(node.am_aobjname, aobjname,
		    sizeof (node.am_aobjname));
		(void) strlcpy(node.am_ifname, ifname,
		    sizeof (node.am_ifname));
		node.am_atype = atype;
		node.am_lnum = lnum;
		node.am_family = af;
		/* The address object is not persisted. */
		node.am_flags = IPMGMT_ACTIVE;
		err = ipmgmt_aobjmap_op(&node, ADDROBJ_ADD);
		break;
	case IPMGMT_CMD_AOBJNAME2ADDROBJ:
		rsize = sizeof (ipmgmt_aobjop_rval_t);
		rvalp = &aobjrval;
		bzero(&aobjrval, sizeof (aobjrval));
		if (aobjname[0] == '\0') {
			err = EINVAL;
			break;
		}
		(void) pthread_rwlock_rdlock(&aobjmap.aobjmap_rwlock);
		head = aobjmap.aobjmap_head;
		for (; head; head = head->am_next) {
			if (strcmp(head->am_aobjname, aobjname) != 0)
				continue;
			/*
			 * For an auto-configured interface, return
			 * the lifnum that has the link-local on it.
			 * Other logical interfaces were created for
			 * prefixes and dhcpv6 addresses and do not
			 * have am_ifid set.
			 */
			if (head->am_atype != IPADM_ADDR_IPV6_ADDRCONF ||
			    head->ipmgmt_am_linklocal) {
				break;
			}
		}
		if (head == NULL) {
			err = ENOENT;
			(void) pthread_rwlock_unlock(&aobjmap.aobjmap_rwlock);
			break;
		}
		(void) strlcpy(aobjrval.ir_ifname, head->am_ifname,
		    sizeof (aobjrval.ir_ifname));
		aobjrval.ir_lnum = head->am_lnum;
		aobjrval.ir_family = head->am_family;
		aobjrval.ir_flags = head->am_flags;
		aobjrval.ir_atype = head->am_atype;
		aobjrval.ir_atype_cache = head->am_atype_cache;
		(void) pthread_rwlock_unlock(&aobjmap.aobjmap_rwlock);
		break;
	case IPMGMT_CMD_LIF2ADDROBJ:
		rsize = sizeof (ipmgmt_aobjop_rval_t);
		rvalp = &aobjrval;
		bzero(&aobjrval, sizeof (aobjrval));
		if (ifname[0] == '\0') {
			err = EINVAL;
			break;
		}
		(void) pthread_rwlock_rdlock(&aobjmap.aobjmap_rwlock);
		head = aobjmap.aobjmap_head;
		for (; head; head = head->am_next) {
			if (strcmp(head->am_ifname, ifname) == 0 &&
			    head->am_lnum == lnum &&
			    head->am_family == af) {
				break;
			}
		}
		if (head == NULL) {
			err = ENOENT;
			(void) pthread_rwlock_unlock(&aobjmap.aobjmap_rwlock);
			break;
		}
		(void) strlcpy(aobjrval.ir_aobjname, head->am_aobjname,
		    sizeof (aobjrval.ir_aobjname));
		aobjrval.ir_atype = head->am_atype;
		aobjrval.ir_flags = head->am_flags;
		aobjrval.ir_atype_cache = head->am_atype_cache;
		(void) pthread_rwlock_unlock(&aobjmap.aobjmap_rwlock);
		break;
	default:
		rsize = sizeof (ipmgmt_retval_t);
		rvalp = &rval;
		err = EINVAL;
	}
	((ipmgmt_retval_t *)rvalp)->ir_err = err;
	(void) door_return((char *)rvalp, rsize, NULL, 0);
}

/*
 * Given an interface name and family, deletes all the address objects
 * associated with it.
 */
void
i_ipmgmt_delif_aobjs(char *ifname, sa_family_t af, uint32_t flags)
{
	ipmgmt_aobjmap_t	*head, *next, *prev;
	ipadm_db_op_t		db_op;

	prev = NULL;

	(void) pthread_rwlock_wrlock(&aobjmap.aobjmap_rwlock);
	head = aobjmap.aobjmap_head;
	for (; head; head = next) {
		next = head->am_next;
		if (strcmp(head->am_ifname, ifname) != 0 ||
		    head->am_family != af) {
			prev = head;
			continue;
		}

		if (head->am_flags == (IPMGMT_ACTIVE|IPMGMT_PERSIST) &&
		    flags == IPMGMT_ACTIVE) {
			/*
			 * If the addres is present in both active and
			 * persistent store, and if we are performing
			 * a temporary delete, we update the node to
			 * indicate that the address is only present in
			 * persistent store and we proceed. Otherwise
			 * we always delete the node from aobjmap.
			 */
			head->am_flags &= ~IPMGMT_ACTIVE;
			head->am_lnum = -1;
			db_op = IPADM_DB_WRITE;
		} else {
			db_op = IPADM_DB_DELETE;
			if (prev == NULL)
				aobjmap.aobjmap_head = next;
			else
				prev->am_next = next;
		}
		(void) ipmgmt_persist_aobjmap(head, db_op);
		if (db_op == IPADM_DB_DELETE)
			free(head);
	}
	(void) pthread_rwlock_unlock(&aobjmap.aobjmap_rwlock);
}

/*
 * Handles the door command IPMGMT_CMD_SETIF. It persists the interface
 * information in the DB.
 */
static void
ipmgmt_setif_handler(void *argp)
{
	ipmgmt_retval_t		rval;

	rval.ir_err = ipmgmt_persist_if(argp);
	(void) door_return((char *)&rval, sizeof (rval), NULL, 0);
}

/*
 * Handles the door command IPMGMT_CMD_RESETIF. For the given interface,
 * deletes all the persisted interface configuration. It also deletes, from
 * `aobjmap', all the address objects configured on the given interface.
 */
static void
ipmgmt_resetif_handler(void *argp)
{
	ipmgmt_if_arg_t		*rargp = argp;
	ipmgmt_retval_t		rval;
	ipmgmt_if_cbarg_t	cbarg;
	uint32_t		flags = rargp->ia_flags;
	int			err = 0;

	cbarg.cb_family = rargp->ia_family;
	cbarg.cb_ifname = rargp->ia_ifname;

	cbarg.cb_ipv4exists = B_TRUE;
	cbarg.cb_ipv6exists = B_TRUE;

	if (flags & IPMGMT_PERSIST)
		err = ipmgmt_db_walk(ipmgmt_db_resetif, &cbarg,
		    IPADM_DB_DELETE);

	if (flags & IPMGMT_ACTIVE)
		i_ipmgmt_delif_aobjs(rargp->ia_ifname, rargp->ia_family,
		    flags);

	rval.ir_err = err;
	(void) door_return((char *)&rval, sizeof (rval), NULL, 0);
}

/*
 * Handles the door command IPMGMT_CMD_RESETADDR. For the given addrobj
 * deletes all the persisted addrobj configuration. It also deletes the
 * corresponding node, from `aobjmap'.
 */
static void
ipmgmt_resetaddr_handler(void *argp)
{
	ipmgmt_addr_arg_t	*rargp = argp;
	ipmgmt_retval_t		rval;
	ipmgmt_aobjmap_t	node;
	uint32_t		flags = rargp->ia_flags;
	int			err = 0;
	ipmgmt_resetaddr_cbarg_t cbarg;

	cbarg.cb_aobjname = rargp->ia_aobjname;

	if (flags & IPMGMT_PERSIST)
		err = ipmgmt_db_walk(ipmgmt_db_resetaddr, &cbarg,
		    IPADM_DB_DELETE);

	if (flags & IPMGMT_ACTIVE) {
		bzero(&node, sizeof (node));
		(void) strlcpy(node.am_aobjname, rargp->ia_aobjname,
		    sizeof (node.am_aobjname));

		/*
		 * am_lnum is used only for IPv6 autoconf case, since there
		 * can be multiple nodes with the same aobjname.
		 */
		node.am_lnum = rargp->ia_lnum;
		node.am_flags = flags;
		(void) ipmgmt_aobjmap_op(&node, ADDROBJ_DELETE);
	}

	rval.ir_err = err;
	(void) door_return((char *)&rval, sizeof (rval), NULL, 0);
}

/*
 * Handles the door command IPMGMT_CMD_GETADDR. It retrieves the persisted
 * address for a given `gargp->ia_aobjname'. If it is not defined then it
 * retrieves all the addresses configured on `gargp->ia_ifname'. The
 * "ipadm show-addr addrobj" or "ipadm show-addr <ifname>/\*" will call this
 * handler through library.
 */
static void
ipmgmt_getaddr_handler(void *argp)
{
	ipmgmt_getaddr_arg_t    *gargp = argp;

	ipmgmt_common_handler(gargp->ia_ifname, gargp->ia_aobjname,
	    ipmgmt_db_getaddr);
}

/*
 * Handles the door command IPMGMT_CMD_RESETPROP. It deletes the property line
 * from the DB.
 */
static void
ipmgmt_resetprop_handler(void *argp)
{
	ipmgmt_prop_arg_t	*pargp = argp;
	ipmgmt_retval_t		rval;

	assert(pargp->ia_cmd == IPMGMT_CMD_RESETPROP);

	rval.ir_err = ipmgmt_db_walk(ipmgmt_db_resetprop, pargp,
	    IPADM_DB_DELETE);
	(void) door_return((char *)&rval, sizeof (rval), NULL, 0);
}

/*
 * Handles the door command IPMGMT_CMD_GETIF. It retrieves the names of all
 * persisted interfaces and the IP protocol families (IPv4 or IPv6) they
 * support. Returns the info as a nvlist using door_return() from
 * ipmgmt_common_handler().
 */
static void
ipmgmt_getif_handler(void *argp)
{
	ipmgmt_getif_arg_t  *getif = argp;

	assert(getif->ia_cmd == IPMGMT_CMD_GETIF);

	ipmgmt_common_handler(getif->ia_ifname, NULL,
	    ipmgmt_db_getif);
}

/*
 * Handles the door command IPMGMT_CMD_INITIF. It retrieves all the persisted
 * interface configuration (interface properties and addresses), for all those
 * interfaces that need to be initialized.
 */
static void
ipmgmt_initif_handler(void *argp)
{
	ipmgmt_initif_arg_t	*initif = argp;
	size_t			buflen, nvlsize;
	char			*buf = NULL, *onvlbuf, *invlbuf;
	ipmgmt_get_rval_t	rval, *rvalp = &rval;
	ipmgmt_initif_cbarg_t	cbarg;
	int			err;

	assert(initif->ia_cmd == IPMGMT_CMD_INITIF);

	bzero(&cbarg, sizeof (cbarg));
	invlbuf = (char *)argp + sizeof (ipmgmt_initif_arg_t);
	nvlsize = initif->ia_nvlsize;
	err = nvlist_unpack(invlbuf, nvlsize, &cbarg.cb_invl, 0);
	if (err != 0)
		goto fail;

	cbarg.cb_family = initif->ia_family;
	if (nvlist_alloc(&cbarg.cb_onvl, NV_UNIQUE_NAME, 0) != 0)
		goto fail;

	err = ipmgmt_db_walk(ipmgmt_db_initif, &cbarg, IPADM_DB_READ);
	if (err == ENOENT && cbarg.cb_ocnt > 0) {
		/*
		 * If there is at least one entry in the nvlist,
		 * do not return error.
		 */
		err = 0;
	}
	if (err != 0)
		goto fail;

	if ((err = nvlist_size(cbarg.cb_onvl, &nvlsize, NV_ENCODE_NATIVE)) != 0)
		goto fail;

	if (nvlsize > (UINT32_MAX - sizeof (ipmgmt_get_rval_t)))
		goto fail;

	buflen = nvlsize + sizeof (ipmgmt_get_rval_t);
	/*
	 * We cannot use malloc() here because door_return never returns, and
	 * memory allocated by malloc() would get leaked. Use alloca() instead.
	 */
	buf = alloca(buflen);
	onvlbuf = buf + sizeof (ipmgmt_get_rval_t);
	if ((err = nvlist_pack(cbarg.cb_onvl, &onvlbuf, &nvlsize,
	    NV_ENCODE_NATIVE, 0)) != 0) {
		goto fail;
	}
	nvlist_free(cbarg.cb_invl);
	nvlist_free(cbarg.cb_onvl);
	rvalp = (ipmgmt_get_rval_t *)(void *)buf;
	rvalp->ir_err = 0;
	rvalp->ir_nvlsize = nvlsize;

	(void) door_return(buf, buflen, NULL, 0);
	return;
fail:
	nvlist_free(cbarg.cb_invl);
	nvlist_free(cbarg.cb_onvl);
	rvalp->ir_err = err;
	(void) door_return((char *)rvalp, sizeof (*rvalp), NULL, 0);
}

int
ipmgmt_persist_if(ipmgmt_if_arg_t *sargp)
{
	ipadm_dbwrite_cbarg_t	cb;
	uint32_t	flags = sargp->ia_flags;
	nvlist_t	*nvl = NULL;
	char	strval[IPMGMT_STRSIZE];
	int	err = 0;

	if (!(flags & IPMGMT_PERSIST) || sargp->ia_family == AF_UNSPEC ||
	    sargp->ia_ifname[0] == '\0') {
		err = EINVAL;
		goto ret;
	}
	if ((err = nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0)) != 0)
		goto ret;

	if ((err = nvlist_add_string(nvl, IPADM_NVP_IFNAME,
	    sargp->ia_ifname)) != 0)
		goto ret;

	if ((err = ipmgmt_update_family_nvp(nvl, sargp->ia_family,
	    IPMGMT_APPEND)) != 0)
		goto ret;

	(void) snprintf(strval, IPMGMT_STRSIZE, "%d", sargp->ia_ifclass);
	if ((err = nvlist_add_string(nvl, IPADM_NVP_IFCLASS, strval)) != 0)
		goto ret;

	cb.dbw_nvl = nvl;
	cb.dbw_flags = IPMGMT_APPEND | IPMGMT_UPDATE_IF;
	err = ipmgmt_db_walk(ipmgmt_db_update_if, &cb, IPADM_DB_WRITE);
ret:
	nvlist_free(nvl);
	return (err);
}

/*
 * The helper for ipmgmt_getif_handler and ipmgmt_getaddr_handler
 */
static void
ipmgmt_common_handler(char *if_name, char *aobj_name, db_wfunc_t worker)
{
	size_t			buflen, onvlsize;
	char			*buf, *onvlbuf;
	ipmgmt_get_cbarg_t	cbarg;
	ipmgmt_get_rval_t	rval, *rvalp = &rval;
	int			err = 0;

	cbarg.cb_ifname = if_name;
	cbarg.cb_aobjname = aobj_name;
	cbarg.cb_ocnt = 0;

	if (nvlist_alloc(&cbarg.cb_onvl, NV_UNIQUE_NAME, 0) != 0)
		goto fail;

	err = ipmgmt_db_walk(worker, &cbarg, IPADM_DB_READ);
	if (err == ENOENT && cbarg.cb_ocnt > 0) {
		/*
		 * If there is at least one entry in the nvlist,
		 * do not return error.
		 */
		err = 0;
	}
	if (err != 0)
		goto fail;

	if ((err = nvlist_size(cbarg.cb_onvl, &onvlsize,
	    NV_ENCODE_NATIVE)) != 0)
		goto fail;

	if (onvlsize > (UINT32_MAX - sizeof (ipmgmt_get_rval_t)))
		goto fail;

	buflen = onvlsize + sizeof (ipmgmt_get_rval_t);
	/*
	 * We cannot use malloc() here because door_return never returns, and
	 * memory allocated by malloc() would get leaked. Use alloca() instead.
	 */
	buf = alloca(buflen);
	onvlbuf = buf + sizeof (ipmgmt_get_rval_t);
	if ((err = nvlist_pack(cbarg.cb_onvl, &onvlbuf,
	    &onvlsize, NV_ENCODE_NATIVE, 0)) != 0)
		goto fail;

	nvlist_free(cbarg.cb_onvl);
	rvalp = (ipmgmt_get_rval_t *)(void *)buf;
	rvalp->ir_err = 0;
	rvalp->ir_nvlsize = onvlsize;

	(void) door_return(buf, buflen, NULL, 0);

fail:
	nvlist_free(cbarg.cb_onvl);
	rvalp->ir_err = err;
	(void) door_return((char *)rvalp, sizeof (*rvalp), NULL, 0);
}

/*
 * Handles the door command IPMGMT_CMD_IPMP_UPDATE
 */
static void
ipmgmt_ipmp_update_handler(void *argp)
{
	ipmgmt_ipmp_update_arg_t *uargp = argp;
	ipmgmt_retval_t	rval;
	ipadm_dbwrite_cbarg_t	cb;

	boolean_t	gif_exists;
	char		gifname[LIFNAMSIZ];
	nvlist_t	*nvl = NULL;
	uint32_t	flags = uargp->ia_flags;
	int		err = 0;

	assert(uargp->ia_cmd == IPMGMT_CMD_IPMP_UPDATE);

	gif_exists = ipmgmt_persist_if_exists(uargp->ia_gifname,
	    AF_UNSPEC);

	if (!ipmgmt_persist_if_exists(uargp->ia_mifname, AF_UNSPEC)) {
		err = EINVAL;
		goto ret;
	}

	ipmgmt_get_group_interface(uargp->ia_mifname, gifname, LIFNAMSIZ);

	if (flags & IPMGMT_APPEND) {
		/* Group interface should be available in the DB */
		if (!gif_exists) {
			err = ENOENT;
			goto ret;
		}

		if (gifname[0] != '\0') {
			err = EEXIST;
			goto ret;
		}
	}

	if (flags & IPMGMT_REMOVE) {
		/* We cannot remove something that does not exist */
		if (!gif_exists || gifname[0] == '\0') {
			err = ENOENT;
			goto ret;
		}
		if (strcmp(uargp->ia_gifname, gifname) != 0) {
			err = EINVAL;
			goto ret;
		}
	}

	if (flags & IPMGMT_PERSIST) {
		if ((err = nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0)) != 0)
			goto ret;

		if ((err = nvlist_add_string(nvl, IPADM_NVP_IFNAME,
		    uargp->ia_gifname)) != 0)
			goto ret;

		if ((err = nvlist_add_string(nvl, IPADM_NVP_MIFNAMES,
		    uargp->ia_mifname)) != 0)
			goto ret;

		if ((err = nvlist_add_string(nvl, IPADM_NVP_GIFNAME,
		    uargp->ia_gifname)) != 0)
			goto ret;

		cb.dbw_nvl = nvl;
		cb.dbw_flags = flags | IPMGMT_UPDATE_IF | IPMGMT_UPDATE_IPMP;
		err = ipmgmt_db_walk(ipmgmt_db_update_if, &cb, IPADM_DB_WRITE);
	}
ret:
	nvlist_free(nvl);
	rval.ir_err = err;
	(void) door_return((char *)&rval, sizeof (rval), NULL, 0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 2016, Chris Fraire <cfraire@me.com>.
 * Copyright 2021 Tintri by DDN, Inc. All rights reserved.
 */

#ifndef	_IPMGMT_IMPL_H
#define	_IPMGMT_IMPL_H

#ifdef  __cplusplus
extern "C" {
#endif

#include <net/if.h>
#include <libnvpair.h>
#include <libipadm.h>
#include <ipadm_ipmgmt.h>
#include <syslog.h>
#include <pthread.h>
#include <libscf.h>

#define	IPMGMT_STRSIZE		256
#define	IPMGMTD_FMRI		"svc:/network/ip-interface-management:default"

/* ipmgmt_door.c */
extern void	ipmgmt_handler(void *, char *, size_t, door_desc_t *, uint_t);

/* ipmgmt_util.c */
extern void	ipmgmt_log(int, const char *, ...);
extern int	ipmgmt_cpfile(const char *, const char *, boolean_t);

/* ipmgmt_persist.c */
extern boolean_t ipmgmt_persist_if_exists(const char *, sa_family_t);
extern void ipmgmt_get_group_interface(const char *, char *, size_t);

/*
 * following are the list of DB walker callback functions and the callback
 * arguments for each of the callback functions used by the daemon
 */
/* following functions take 'ipmgmt_prop_arg_t' as the callback argument */
extern db_wfunc_t	ipmgmt_db_getprop, ipmgmt_db_resetprop;

/* following functions take ipadm_dbwrite_cbarg_t as callback argument */
extern db_wfunc_t	ipmgmt_db_add, ipmgmt_db_update, ipmgmt_db_update_if;

typedef struct {
	char	*cb_ifname;
	char	*cb_aobjname;
	nvlist_t	*cb_onvl;
	int	cb_ocnt;
} ipmgmt_get_cbarg_t;
extern db_wfunc_t	ipmgmt_db_getif;
extern db_wfunc_t	ipmgmt_db_getaddr;

typedef struct {
	sa_family_t	cb_family;
	char		*cb_ifname;
	boolean_t	cb_ipv4exists;
	boolean_t	cb_ipv6exists;
} ipmgmt_if_cbarg_t;
extern db_wfunc_t	ipmgmt_db_setif, ipmgmt_db_resetif;

typedef struct {
	char		*cb_aobjname;
} ipmgmt_resetaddr_cbarg_t;
extern db_wfunc_t	ipmgmt_db_resetaddr;

typedef struct {
	sa_family_t	cb_family;
	nvlist_t	*cb_invl;
	nvlist_t	*cb_onvl;
	int		cb_ocnt;
} ipmgmt_initif_cbarg_t;
extern db_wfunc_t	ipmgmt_db_initif;

/*
 * A linked list of address object nodes. Each node in the list tracks
 * following information for the address object identified by `am_aobjname'.
 *	- interface on which the address is created
 *	- logical interface number on which the address is created
 *	- address family
 *	- `am_nextnum' identifies the next number to use to generate user part
 *	  of `aobjname'.
 *	- address type (static, dhcp or addrconf)
 *	- `am_flags' indicates if this addrobj in active and/or persist config
 *	- other, ipadm_addr_type_t-specific values are cached in
 *	  am_addr_cache (see type ipmgmt_addr_cache_u):
 *	  -	ipv6: ipmgmt_am_linklocal (macro)
 *	  -	ipv6: ipmgmt_am_ifid (macro)
 *	  -	dhcp: ipmgmt_am_reqhost (macro)
 */
typedef struct ipmgmt_aobjmap_s {
	struct ipmgmt_aobjmap_s	*am_next;
	char			am_aobjname[IPADM_AOBJSIZ];
	char			am_ifname[LIFNAMSIZ];
	int32_t			am_lnum;
	sa_family_t		am_family;
	ipadm_addr_type_t	am_atype;
	uint32_t		am_nextnum;
	uint32_t		am_flags;
	ipmgmt_addr_type_cache_u	am_atype_cache;
} ipmgmt_aobjmap_t;

#define	ipmgmt_am_linklocal \
    am_atype_cache.ipmgmt_ipv6_cache_s.ipmgmt_linklocal
#define	ipmgmt_am_ifid \
    am_atype_cache.ipmgmt_ipv6_cache_s.ipmgmt_ifid
#define	ipmgmt_am_reqhost \
    am_atype_cache.ipmgmt_dhcp_cache_s.ipmgmt_reqhost

/* linked list of `aobjmap' nodes, protected by RW lock */
typedef struct ipmgmt_aobjmap_list_s {
	ipmgmt_aobjmap_t	*aobjmap_head;
	pthread_rwlock_t	aobjmap_rwlock;
} ipmgmt_aobjmap_list_t;

/* global `aobjmap' defined in ipmgmt_main.c */
extern ipmgmt_aobjmap_list_t aobjmap;

/* operations on the `aobjmap' linked list */
#define	ADDROBJ_ADD		0x00000001
#define	ADDROBJ_DELETE		0x00000002
#define	ADDROBJ_LOOKUPADD	0x00000004
#define	ADDROBJ_SETLIFNUM	0x00000008

/* Permanent data store for ipadm */
#define	IPADM_DB_FILE		"/etc/ipadm/ipadm.conf"
#define	IPADM_FILE_MODE		(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

/*
 * With the initial integration of the daemon (PSARC 2010/080), the version
 * of the ipadm data-store (/etc/ipadm/ipadm.conf) was 0. A subsequent fix
 * needed an upgrade to the data-store and we bumped the version to 1.
 */
#define	IPADM_DB_VERSION	1

/*
 * A temporary file created in SMF volatile filesystem. This file captures the
 * in-memory copy of list `aobjmap' on disk. This is done to recover from
 * daemon reboot (using svcadm) or crashes.
 */
#define	IPADM_TMPFS_DIR		"/etc/svc/volatile/ipadm"
#define	ADDROBJ_MAPPING_DB_FILE	IPADM_TMPFS_DIR"/aobjmap.conf"

/*
 * A temporary copy of the ipadm configuration file might need
 * to be created if write requests are encountered during boottime
 * and the root filesystem is mounted read-only.
 */
#define	IPADM_VOL_DB_FILE	IPADM_TMPFS_DIR"/ipadm.conf"

/* SCF resources required to interact with svc.configd */
typedef struct scf_resources {
	scf_handle_t		*sr_handle;
	scf_instance_t		*sr_inst;
	scf_propertygroup_t	*sr_pg;
	scf_property_t		*sr_prop;
	scf_value_t		*sr_val;
	scf_transaction_t	*sr_tx;
	scf_transaction_entry_t	*sr_ent;
} scf_resources_t;

extern int		ipmgmt_update_family_nvp(nvlist_t *,
			    sa_family_t, uint_t);
extern int		ipmgmt_db_walk(db_wfunc_t *, void *, ipadm_db_op_t);
extern int		ipmgmt_aobjmap_op(ipmgmt_aobjmap_t *, uint32_t);
extern boolean_t	ipmgmt_aobjmap_init(void *, nvlist_t *, char *,
			    size_t, int *);
extern int		ipmgmt_persist_aobjmap(ipmgmt_aobjmap_t *,
			    ipadm_db_op_t);
extern boolean_t	ipmgmt_ngz_firstboot_postinstall();
extern int		ipmgmt_persist_if(ipmgmt_if_arg_t *);
extern void		ipmgmt_init_prop();
extern boolean_t	ipmgmt_db_upgrade(void *, nvlist_t *, char *,
			    size_t, int *);
extern int		ipmgmt_create_scf_resources(const char *,
			    scf_resources_t *);
extern void		ipmgmt_release_scf_resources(scf_resources_t *);
extern boolean_t	ipmgmt_needs_upgrade(scf_resources_t *);
extern void		ipmgmt_update_dbver(scf_resources_t *);

#ifdef  __cplusplus
}
#endif

#endif	/* _IPMGMT_IMPL_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2021 Tintri by DDN, Inc. All rights reserved.
 */

/*
 * The ipmgmtd daemon is started by ip-interface-management SMF service. This
 * daemon is used to manage, mapping of 'address object' to 'interface name' and
 * 'logical interface number', on which the address is created. It also provides
 * a means to update the ipadm persistent data-store.
 *
 * The daemon tracks the <addrobj, lifname> mapping in-memory using a linked
 * list `aobjmap'. Access to this list is synchronized using a readers-writers
 * lock. The active <addrobj, lifname> mapping is kept in
 * /etc/svc/volatile/ipadm/aobjmap.conf cache file, so that the mapping can be
 * recovered when ipmgmtd exits for some reason (e.g., when ipmgmtd is restarted
 * using svcadm or accidentally killed).
 *
 * Today, the persistent configuration of interfaces, addresses and protocol
 * properties is kept in /etc/ipadm/ipadm.conf. The access to the persistent
 * data store is synchronized using reader-writers lock `ipmgmt_dbconf_lock'.
 *
 * The communication between the library, libipadm.so and the daemon, is through
 * doors RPC. The library interacts with the daemon using the commands defined
 * by `ipmgmt_door_cmd_type_t'. Further any 'write' operation would require
 * the `NETWORK_INTERFACE_CONFIG_AUTH' authorization.
 *
 * On reboot, the aforementioned SMF service starts the daemon before any other
 * networking service that configures network IP interfaces is started.
 * Afterwards, the network/physical SMF script instantiates the persisted
 * network interfaces, interface properties and addresses.
 */

#include <errno.h>
#include <fcntl.h>
#include <priv_utils.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <unistd.h>
#include "ipmgmt_impl.h"
#include <zone.h>
#include <libipadm.h>
#include <libdladm.h>
#include <libdllink.h>
#include <net/route.h>
#include <ipadm_ipmgmt.h>
#include <sys/brand.h>

const char		*progname;

/* readers-writers lock for reading/writing daemon data store */
pthread_rwlock_t	ipmgmt_dbconf_lock = PTHREAD_RWLOCK_INITIALIZER;

/* tracks address object to {ifname|logical number|interface id} mapping */
ipmgmt_aobjmap_list_t	aobjmap;

/* used to communicate failure to parent process, which spawned the daemon */
static int		pfds[2];

/* file descriptor to IPMGMT_DOOR */
static int		ipmgmt_door_fd = -1;

static void		ipmgmt_exit(int);
static int		ipmgmt_init();
static int		ipmgmt_init_privileges();
static void		ipmgmt_ngz_persist_if();

static ipadm_handle_t iph;
typedef struct ipmgmt_pif_s {
	struct ipmgmt_pif_s	*pif_next;
	char			pif_ifname[LIFNAMSIZ];
	boolean_t		pif_v4;
	boolean_t		pif_v6;
} ipmgmt_pif_t;

static ipmgmt_pif_t *ngz_pifs;

static int
ipmgmt_db_init()
{
	int		fd, err, scferr;
	scf_resources_t	res;
	boolean_t	upgrade = B_TRUE;

	/*
	 * Check to see if we need to upgrade the data-store. We need to
	 * upgrade, if the version of the data-store does not match with
	 * IPADM_DB_VERSION. Further, if we cannot determine the current
	 * version of the data-store, we always err on the side of caution
	 * and upgrade the data-store to current version.
	 */
	if ((scferr = ipmgmt_create_scf_resources(IPMGMTD_FMRI, &res)) == 0)
		upgrade = ipmgmt_needs_upgrade(&res);
	if (upgrade) {
		err = ipmgmt_db_walk(ipmgmt_db_upgrade, NULL, IPADM_DB_WRITE);
		if (err != 0) {
			ipmgmt_log(LOG_ERR, "could not upgrade the "
			    "ipadm data-store: %s", strerror(err));
			err = 0;
		} else {
			/*
			 * upgrade was success, let's update SCF with the
			 * current data-store version number.
			 */
			if (scferr == 0)
				ipmgmt_update_dbver(&res);
		}
	}
	if (scferr == 0)
		ipmgmt_release_scf_resources(&res);

	/* creates the address object data store, if it doesn't exist */
	if ((fd = open(ADDROBJ_MAPPING_DB_FILE, O_CREAT|O_RDONLY,
	    IPADM_FILE_MODE)) == -1) {
		err = errno;
		ipmgmt_log(LOG_ERR, "could not open %s: %s",
		    ADDROBJ_MAPPING_DB_FILE, strerror(err));
		return (err);
	}
	(void) close(fd);

	aobjmap.aobjmap_head = NULL;
	(void) pthread_rwlock_init(&aobjmap.aobjmap_rwlock, NULL);

	/*
	 * If the daemon is recovering from a crash or restart, read the
	 * address object to logical interface mapping and build an in-memory
	 * representation of the mapping. That is, build `aobjmap' structure
	 * from address object data store.
	 */
	if ((err = ipadm_rw_db(ipmgmt_aobjmap_init, NULL,
	    ADDROBJ_MAPPING_DB_FILE, 0, IPADM_DB_READ)) != 0) {
		/* if there was nothing to initialize, it's fine */
		if (err != ENOENT)
			return (err);
		err = 0;
	}

	ipmgmt_ngz_persist_if(); /* create persistent interface info for NGZ */

	return (err);
}

static int
ipmgmt_door_init()
{
	int fd;
	int err;

	/* create the door file for ipmgmtd */
	if ((fd = open(IPMGMT_DOOR, O_CREAT|O_RDONLY, IPADM_FILE_MODE)) == -1) {
		err = errno;
		ipmgmt_log(LOG_ERR, "could not open %s: %s",
		    IPMGMT_DOOR, strerror(err));
		return (err);
	}
	(void) close(fd);

	if ((ipmgmt_door_fd = door_create(ipmgmt_handler, NULL,
	    DOOR_REFUSE_DESC | DOOR_NO_CANCEL)) == -1) {
		err = errno;
		ipmgmt_log(LOG_ERR, "failed to create door: %s", strerror(err));
		return (err);
	}
	/*
	 * fdetach first in case a previous daemon instance exited
	 * ungracefully.
	 */
	(void) fdetach(IPMGMT_DOOR);
	if (fattach(ipmgmt_door_fd, IPMGMT_DOOR) != 0) {
		err = errno;
		ipmgmt_log(LOG_ERR, "failed to attach door to %s: %s",
		    IPMGMT_DOOR, strerror(err));
		goto fail;
	}
	return (0);
fail:
	(void) door_revoke(ipmgmt_door_fd);
	ipmgmt_door_fd = -1;
	return (err);
}

static void
ipmgmt_door_fini()
{
	if (ipmgmt_door_fd == -1)
		return;

	(void) fdetach(IPMGMT_DOOR);
	if (door_revoke(ipmgmt_door_fd) == -1) {
		ipmgmt_log(LOG_ERR, "failed to revoke access to door %s: %s",
		    IPMGMT_DOOR, strerror(errno));
	}
}

static int
ipmgmt_init()
{
	int err;

	if (signal(SIGTERM, ipmgmt_exit) == SIG_ERR ||
	    signal(SIGINT, ipmgmt_exit) == SIG_ERR) {
		err = errno;
		ipmgmt_log(LOG_ERR, "signal() for SIGTERM/INT failed: %s",
		    strerror(err));
		return (err);
	}
	if ((err = ipmgmt_db_init()) != 0 || (err = ipmgmt_door_init()) != 0)
		return (err);
	return (0);
}

/*
 * This is called by the child process to inform the parent process to
 * exit with the given return value.
 */
static void
ipmgmt_inform_parent_exit(int rv)
{
	if (write(pfds[1], &rv, sizeof (int)) != sizeof (int)) {
		ipmgmt_log(LOG_WARNING,
		    "failed to inform parent process of status: %s",
		    strerror(errno));
		(void) close(pfds[1]);
		exit(EXIT_FAILURE);
	}
	(void) close(pfds[1]);
}

/*ARGSUSED*/
static void
ipmgmt_exit(int signo)
{
	(void) close(pfds[1]);
	ipmgmt_door_fini();
	exit(EXIT_FAILURE);
}

/*
 * On the first reboot after installation of an ipkg zone,
 * ipmgmt_persist_if_cb() is used in non-global zones to track the interfaces
 * that have IP address configuration assignments from the global zone.
 * Persistent configuration for the interfaces is created on the first boot
 * by ipmgmtd, and the addresses assigned to the interfaces by the GZ
 * will be subsequently configured when the interface is enabled.
 * Note that ipmgmt_persist_if_cb() only sets up a list of interfaces
 * that need to be persisted- the actual update of the ipadm data-store happens
 * in ipmgmt_persist_if() after the appropriate privs/uid state has been set up.
 */
static void
ipmgmt_persist_if_cb(char *ifname, boolean_t v4, boolean_t v6)
{
	ipmgmt_pif_t *pif;

	pif = calloc(1, sizeof (*pif));
	if (pif == NULL) {
		ipmgmt_log(LOG_WARNING,
		    "Could not allocate memory to configure %s", ifname);
		return;
	}
	(void) strlcpy(pif->pif_ifname, ifname, sizeof (pif->pif_ifname));
	pif->pif_v4 = v4;
	pif->pif_v6 = v6;
	pif->pif_next = ngz_pifs;
	ngz_pifs = pif;
}

/*
 * ipmgmt_ngz_init() initializes exclusive-IP stack non-global zones by
 * extracting configuration that has been saved in the kernel and applying
 * it at zone boot.
 */
static void
ipmgmt_ngz_init()
{
	zoneid_t zoneid;
	boolean_t firstboot = B_TRUE, s10c = B_FALSE;
	char brand[MAXNAMELEN];
	ipadm_status_t ipstatus;

	zoneid = getzoneid();
	if (zoneid != GLOBAL_ZONEID) {

		if (zone_getattr(zoneid, ZONE_ATTR_BRAND, brand,
		    sizeof (brand)) < 0) {
			ipmgmt_log(LOG_ERR, "Could not get brand name");
			return;
		}
		/*
		 * firstboot is always true for S10C zones, where ipadm is not
		 * available for restoring persistent configuration.
		 */
		if (strcmp(brand, NATIVE_BRAND_NAME) == 0)
			firstboot = ipmgmt_ngz_firstboot_postinstall();
		else
			s10c = B_TRUE;

		if (!firstboot)
			return;

		ipstatus = ipadm_open(&iph, IPH_IPMGMTD);
		if (ipstatus != IPADM_SUCCESS) {
			ipmgmt_log(LOG_ERR, "could not open ipadm handle",
			    ipadm_status2str(ipstatus));
			return;
		}
		/*
		 * Only pass down the callback to persist the interface
		 * for NATIVE (ipkg) zones.
		 */
		(void) ipadm_init_net_from_gz(iph, NULL,
		    (s10c ? NULL : ipmgmt_persist_if_cb));
		ipadm_close(iph);
	}
}

/*
 * Set the uid of this daemon to the "netadm" user. Finish the following
 * operations before setuid() because they need root privileges:
 *
 *    - create the /etc/svc/volatile/ipadm directory;
 *    - change its uid/gid to "netadm"/"netadm";
 */
static int
ipmgmt_init_privileges()
{
	struct stat	statbuf;
	int		err;

	/* create the IPADM_TMPFS_DIR directory */
	if (stat(IPADM_TMPFS_DIR, &statbuf) < 0) {
		if (mkdir(IPADM_TMPFS_DIR, (mode_t)0755) < 0) {
			err = errno;
			goto fail;
		}
	} else {
		if ((statbuf.st_mode & S_IFMT) != S_IFDIR) {
			err = ENOTDIR;
			goto fail;
		}
	}

	if ((chmod(IPADM_TMPFS_DIR, 0755) < 0) ||
	    (chown(IPADM_TMPFS_DIR, UID_NETADM, GID_NETADM) < 0)) {
		err = errno;
		goto fail;
	}

	/*
	 * initialize any NGZ specific network information before dropping
	 * privileges. We need these privileges to plumb IP interfaces handed
	 * down from the GZ (for dlpi_open() etc.) and also to configure the
	 * address itself (for any IPI_PRIV ioctls like SLIFADDR)
	 */
	ipmgmt_ngz_init();

	/*
	 * Apply all protocol module properties. We need to apply all protocol
	 * properties before we drop root privileges.
	 */
	ipmgmt_init_prop();

	/*
	 * limit the privileges of this daemon and set the uid of this
	 * daemon to UID_NETADM
	 */
	if (__init_daemon_priv(PU_RESETGROUPS|PU_CLEARLIMITSET, UID_NETADM,
	    GID_NETADM, NULL) == -1) {
		err = EPERM;
		goto fail;
	}

	return (0);
fail:
	(void) ipmgmt_log(LOG_ERR, "failed to initialize the daemon: %s",
	    strerror(err));
	return (err);
}

/*
 * Keep the pfds fd open, close other fds.
 */
/*ARGSUSED*/
static int
closefunc(void *arg, int fd)
{
	if (fd != pfds[1])
		(void) close(fd);
	return (0);
}

/*
 * We cannot use libc's daemon() because the door we create is associated with
 * the process ID. If we create the door before the call to daemon(), it will
 * be associated with the parent and it's incorrect. On the other hand if we
 * create the door later, after the call to daemon(), parent process exits
 * early and gives a false notion to SMF that 'ipmgmtd' is up and running,
 * which is incorrect. So, we have our own daemon() equivalent.
 */
static boolean_t
ipmgmt_daemonize(void)
{
	pid_t pid;
	int rv;

	if (pipe(pfds) < 0) {
		(void) fprintf(stderr, "%s: pipe() failed: %s\n",
		    progname, strerror(errno));
		exit(EXIT_FAILURE);
	}

	if ((pid = fork()) == -1) {
		(void) fprintf(stderr, "%s: fork() failed: %s\n",
		    progname, strerror(errno));
		exit(EXIT_FAILURE);
	} else if (pid > 0) { /* Parent */
		(void) close(pfds[1]);

		/*
		 * Parent should not exit early, it should wait for the child
		 * to return Success/Failure. If the parent exits early, then
		 * SMF will think 'ipmgmtd' is up and would start all the
		 * depended services.
		 *
		 * If the child process exits unexpectedly, read() returns -1.
		 */
		if (read(pfds[0], &rv, sizeof (int)) != sizeof (int)) {
			(void) kill(pid, SIGKILL);
			rv = EXIT_FAILURE;
		}

		(void) close(pfds[0]);
		exit(rv);
	}

	/* Child */
	(void) close(pfds[0]);
	(void) setsid();

	/* close all files except pfds[1] */
	(void) fdwalk(closefunc, NULL);
	(void) chdir("/");
	openlog(progname, LOG_PID, LOG_DAEMON);
	return (B_TRUE);
}

int
main(int argc, char *argv[])
{
	int opt;
	boolean_t fg = B_FALSE;

	progname = strrchr(argv[0], '/');
	if (progname != NULL)
		progname++;
	else
		progname = argv[0];

	/* Process options */
	while ((opt = getopt(argc, argv, "f")) != EOF) {
		switch (opt) {
		case 'f':
			fg = B_TRUE;
			break;
		default:
			(void) fprintf(stderr, "Usage: %s [-f]\n", progname);
			return (EXIT_FAILURE);
		}
	}

	if (!fg && getenv("SMF_FMRI") == NULL) {
		(void) fprintf(stderr,
		    "ipmgmtd is a smf(7) managed service and cannot be run "
		    "from the command line.\n");
		return (EINVAL);
	}

	if (!fg && !ipmgmt_daemonize())
		return (EXIT_FAILURE);

	if (ipmgmt_init_privileges() != 0)
		goto child_out;

	if (ipmgmt_init() != 0)
		goto child_out;

	/* Inform the parent process that it can successfully exit */
	ipmgmt_inform_parent_exit(EXIT_SUCCESS);

	for (;;)
		(void) pause();

child_out:
	/* return from main() forcibly exits an MT process */
	ipmgmt_inform_parent_exit(EXIT_FAILURE);
	return (EXIT_FAILURE);
}

/*
 * Persist any NGZ interfaces assigned to us from the global zone if they do
 * not already exist in the persistent db. We need to
 * do this before any calls to ipadm_enable_if() can succeed (i.e.,
 * before opening up for door_calls), and after setuid to 'netadm' so that
 * the persistent db is created with the right permissions.
 */
static void
ipmgmt_ngz_persist_if()
{
	ipmgmt_pif_t *pif, *next;
	ipmgmt_if_arg_t ifarg;

	for (pif = ngz_pifs; pif != NULL; pif = next) {
		next = pif->pif_next;
		bzero(&ifarg, sizeof (ifarg));
		(void) strlcpy(ifarg.ia_ifname, pif->pif_ifname,
		    sizeof (ifarg.ia_ifname));
		ifarg.ia_flags = IPMGMT_PERSIST;
		if (pif->pif_v4 &&
		    !ipmgmt_persist_if_exists(pif->pif_ifname, AF_INET)) {
			ifarg.ia_family = AF_INET;
			(void) ipmgmt_persist_if(&ifarg);
		}
		if (pif->pif_v6 &&
		    !ipmgmt_persist_if_exists(pif->pif_ifname, AF_INET6)) {
			ifarg.ia_family = AF_INET6;
			(void) ipmgmt_persist_if(&ifarg);
		}
		free(pif);
	}
	ngz_pifs = NULL; /* no red herrings */
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2018 Joyent, Inc.
 * Copyright 2016 Argo Technologie SA.
 * Copyright (c) 2016-2017, Chris Fraire <cfraire@me.com>.
 * Copyright 2021 Tintri by DDN, Inc. All rights reserved.
 */

/*
 * Contains DB walker functions, which are of type `db_wfunc_t';
 *
 * typedef boolean_t db_wfunc_t(void *cbarg, nvlist_t *db_nvl, char *buf,
 *				size_t bufsize, int *errp);
 *
 * ipadm_rw_db() walks through the data store, one line at a time and calls
 * these call back functions with:
 *	`cbarg'  - callback argument
 *	`db_nvl' - representing a line from DB in nvlist_t form
 *	`buf'	 - character buffer to hold modified line
 *	`bufsize'- size of the buffer
 *	`errp' - captures any error inside the walker function.
 *
 * All the 'write' callback functions modify `db_nvl' based on `cbarg' and
 * copy string representation of `db_nvl' (using ipadm_nvlist2str()) into `buf'.
 * To delete a line from the DB, buf[0] is set to `\0'. Inside ipadm_rw_db(),
 * the modified `buf' is written back into DB.
 *
 * All the 'read' callback functions, retrieve the information from the DB, by
 * reading `db_nvl' and then populate the `cbarg'.
 */

#include <stdlib.h>
#include <strings.h>
#include <errno.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "ipmgmt_impl.h"

/* SCF related property group names and property names */
#define	IPMGMTD_APP_PG		"ipmgmtd"
#define	IPMGMTD_PROP_FBD	"first_boot_done"
#define	IPMGMTD_PROP_DBVER	"datastore_version"
#define	IPMGMTD_TRUESTR		"true"

#define	ATYPE	"_atype"		/* name of the address type nvpair */
#define	FLAGS	"_flags"		/* name of the flags nvpair */

/*
 * flag used by ipmgmt_persist_aobjmap() to indicate address type is
 * IPADM_ADDR_IPV6_ADDRCONF.
 */
#define	IPMGMT_ATYPE_V6ACONF	0x1

extern pthread_rwlock_t ipmgmt_dbconf_lock;

/* signifies whether volatile copy of data store is in use */
static boolean_t ipmgmt_rdonly_root = B_FALSE;

typedef int ipmgmt_if_updater_func_t(nvlist_t *, nvpair_t *, uint_t);

static ipmgmt_if_updater_func_t ipmgmt_if_family_updater;
static ipmgmt_if_updater_func_t ipmgmt_if_groupmembers_updater;

static int ipmgmt_get_ifinfo_nvl(const char *ifname, nvlist_t **if_info_nvl);

typedef struct {
	const char	*name;
	ipmgmt_if_updater_func_t	*func;
} ipmgmt_if_updater_ent_t;

static ipmgmt_if_updater_ent_t ipmgmt_if_updater_ent[] = {
	{IPADM_NVP_FAMILIES, ipmgmt_if_family_updater},
	{IPADM_NVP_MIFNAMES, ipmgmt_if_groupmembers_updater},
	{NULL, NULL}
};

static ipmgmt_if_updater_ent_t *
ipmgmt_find_if_field_updater(const char *field_name)
{
	int i;

	for (i = 0; ipmgmt_if_updater_ent[i].name != NULL; i++) {
		if (strcmp(field_name, ipmgmt_if_updater_ent[i].name) == 0) {
			break;
		}
	}

	return (&ipmgmt_if_updater_ent[i]);
}

static int
ipmgmt_if_groupmembers_updater(nvlist_t *db_nvl, nvpair_t *member_nvp,
    uint_t flags)
{
	char	**members;
	char	*member;
	char	**out_members;
	uint_t  nelem = 0, cnt = 0;
	int	err;

	if ((err = nvpair_value_string(member_nvp, &member)) != 0)
		return (err);

	err = nvlist_lookup_string_array(db_nvl, IPADM_NVP_MIFNAMES,
	    &members, &nelem);

	if (err != 0 && (flags & IPMGMT_REMOVE))
		return (ENOENT);

	/*
	 * Reserve one extra slot for IPMGMT_APPEND.
	 * Probably not worth conditionalizing.
	 */
	out_members = calloc(nelem + 1, sizeof (char *));
	if (out_members == NULL)
		return (ENOMEM);

	while (nelem-- > 0) {
		if ((flags & IPMGMT_REMOVE) &&
		    (strcmp(member, members[nelem]) == 0))
			continue;

		if ((out_members[cnt] = strdup(members[nelem])) == NULL) {
			err = ENOMEM;
			goto fail;
		}

		cnt++;
	}

	if (flags & IPMGMT_APPEND) {
		if ((out_members[cnt] = strdup(member)) == NULL) {
			err = ENOMEM;
			goto fail;
		}
		cnt++;
	}

	if (cnt == 0) {
		err = nvlist_remove(db_nvl, IPADM_NVP_MIFNAMES,
		    DATA_TYPE_STRING_ARRAY);
	} else {
		err = nvlist_add_string_array(db_nvl, IPADM_NVP_MIFNAMES,
		    out_members, cnt);
	}

fail:
	while (cnt--)
		free(out_members[cnt]);

	free(out_members);

	return (err);
}

static int
ipmgmt_if_family_updater(nvlist_t *db_nvl, nvpair_t *families_nvp, uint_t flags)
{
	uint16_t *families;
	uint_t  nelem = 0;
	int	err;

	if ((err = nvpair_value_uint16_array(families_nvp, &families,
	    &nelem)) != 0)
		return (err);

	return (ipmgmt_update_family_nvp(db_nvl, families[0], flags));
}

int
ipmgmt_update_family_nvp(nvlist_t *nvl, sa_family_t af, uint_t flags)
{
	uint16_t	*families = NULL;
	uint16_t	out_families[2];
	uint_t	nelem = 0, cnt;
	int	err;

	err = nvlist_lookup_uint16_array(nvl, IPADM_NVP_FAMILIES,
	    &families, &nelem);
	if (err != 0 && (flags & IPMGMT_REMOVE)) {
		return (ENOENT);
	}

	if (flags & IPMGMT_APPEND) {
		if (families != NULL) {
			if (nelem == 2 || families[0] == af) {
				return (EEXIST);
			}
			out_families[0] = families[0];
			out_families[1] = af;
			cnt = 2;
		} else {
			out_families[0] = af;
			cnt = 1;
		}
	} else {
		assert(nelem == 1 || nelem == 2);
		cnt = 0;
		while (nelem-- > 0) {
			if (families[nelem] != af) {
				out_families[cnt] = families[nelem];
				cnt++;
			}
		}
	}

	if (cnt != 0) {
		return (nvlist_add_uint16_array(nvl, IPADM_NVP_FAMILIES,
		    out_families, cnt));
	}
	return (nvlist_remove(nvl, IPADM_NVP_FAMILIES, DATA_TYPE_UINT16_ARRAY));
}

/*
 * Checks if the database nvl, `db_nvl' contains and matches ALL of the passed
 * in private nvpairs `proto', `ifname' & `aobjname'.
 */
static boolean_t
ipmgmt_nvlist_match(nvlist_t *db_nvl, const char *proto, const char *ifname,
    const char *aobjname)
{
	char		*db_proto = NULL, *db_ifname = NULL;
	char		*db_aobjname = NULL;
	nvpair_t	*nvp;
	char		*name;

	/* walk through db_nvl and retrieve all its private nvpairs */
	for (nvp = nvlist_next_nvpair(db_nvl, NULL); nvp != NULL;
	    nvp = nvlist_next_nvpair(db_nvl, nvp)) {
		name = nvpair_name(nvp);
		if (strcmp(IPADM_NVP_PROTONAME, name) == 0)
			(void) nvpair_value_string(nvp, &db_proto);
		else if (strcmp(IPADM_NVP_IFNAME, name) == 0)
			(void) nvpair_value_string(nvp, &db_ifname);
		else if (strcmp(IPADM_NVP_AOBJNAME, name) == 0)
			(void) nvpair_value_string(nvp, &db_aobjname);
	}

	if (proto != NULL && proto[0] == '\0')
		proto = NULL;
	if (ifname != NULL && ifname[0] == '\0')
		ifname = NULL;
	if (aobjname != NULL && aobjname[0] == '\0')
		aobjname = NULL;

	if ((proto == NULL && db_proto != NULL) ||
	    (proto != NULL && db_proto == NULL) ||
	    (proto != NULL && db_proto != NULL &&
	    strcmp(proto, db_proto) != 0)) {
		/* no intersection - different protocols. */
		return (B_FALSE);
	}
	if ((ifname == NULL && db_ifname != NULL) ||
	    (ifname != NULL && db_ifname == NULL) ||
	    (ifname != NULL && db_ifname != NULL &&
	    strcmp(ifname, db_ifname) != 0)) {
		/* no intersection - different interfaces. */
		return (B_FALSE);
	}
	if ((aobjname == NULL && db_aobjname != NULL) ||
	    (aobjname != NULL && db_aobjname == NULL) ||
	    (aobjname != NULL && db_aobjname != NULL &&
	    strcmp(aobjname, db_aobjname) != 0)) {
		/* no intersection - different address objects */
		return (B_FALSE);
	}

	return (B_TRUE);
}

/*
 * Checks if the database nvl, `db_nvl' and the input nvl, `in_nvl' intersects.
 */
static boolean_t
ipmgmt_nvlist_intersects(nvlist_t *db_nvl, nvlist_t *in_nvl)
{
	nvpair_t	*nvp;
	char		*name;
	char		*proto = NULL, *ifname = NULL, *aobjname = NULL;

	/* walk through in_nvl and retrieve all its private nvpairs */
	for (nvp = nvlist_next_nvpair(in_nvl, NULL); nvp != NULL;
	    nvp = nvlist_next_nvpair(in_nvl, nvp)) {
		name = nvpair_name(nvp);
		if (strcmp(IPADM_NVP_PROTONAME, name) == 0)
			(void) nvpair_value_string(nvp, &proto);
		else if (strcmp(IPADM_NVP_IFNAME, name) == 0)
			(void) nvpair_value_string(nvp, &ifname);
		else if (strcmp(IPADM_NVP_AOBJNAME, name) == 0)
			(void) nvpair_value_string(nvp, &aobjname);
	}

	return (ipmgmt_nvlist_match(db_nvl, proto, ifname, aobjname));
}

/*
 * Checks if the database nvl, `db_nvl', contains and matches ANY of the passed
 * in private nvpairs `proto', `ifname' & `aobjname'.
 */
static boolean_t
ipmgmt_nvlist_contains(nvlist_t *db_nvl, const char *proto,
    const char *ifname, char *aobjname)
{
	char		*db_ifname = NULL, *db_proto = NULL;
	char		*db_aobjname = NULL;
	nvpair_t	*nvp;
	char		*name;

	/* walk through db_nvl and retrieve all private nvpairs */
	for (nvp = nvlist_next_nvpair(db_nvl, NULL); nvp != NULL;
	    nvp = nvlist_next_nvpair(db_nvl, nvp)) {
		name = nvpair_name(nvp);
		if (strcmp(IPADM_NVP_PROTONAME, name) == 0)
			(void) nvpair_value_string(nvp, &db_proto);
		else if (strcmp(IPADM_NVP_IFNAME, name) == 0)
			(void) nvpair_value_string(nvp, &db_ifname);
		else if (strcmp(IPADM_NVP_AOBJNAME, name) == 0)
			(void) nvpair_value_string(nvp, &db_aobjname);
	}

	if (proto != NULL && proto[0] != '\0') {
		if ((db_proto == NULL || strcmp(proto, db_proto) != 0))
			return (B_FALSE);
	}
	if (ifname != NULL && ifname[0] != '\0') {
		if ((db_ifname == NULL || strcmp(ifname, db_ifname) != 0))
			return (B_FALSE);
	}
	if (aobjname != NULL && aobjname[0] != '\0') {
		if ((db_aobjname == NULL || strcmp(aobjname, db_aobjname) != 0))
			return (B_FALSE);
	}

	return (B_TRUE);
}

/*
 * Retrieves the property value from the DB. The property whose value is to be
 * retrieved is in `pargp->ia_pname'.
 */
/* ARGSUSED */
boolean_t
ipmgmt_db_getprop(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	ipmgmt_prop_arg_t	*pargp = arg;
	boolean_t		cont = B_TRUE;
	char			*pval;
	int			err = 0;

	*errp = 0;

	if (!ipmgmt_nvlist_match(db_nvl, pargp->ia_module,
	    pargp->ia_ifname, pargp->ia_aobjname))
		return (B_TRUE);

	if ((err = nvlist_lookup_string(db_nvl, pargp->ia_pname,
	    &pval)) == 0) {
		(void) strlcpy(pargp->ia_pval, pval, sizeof (pargp->ia_pval));
		/*
		 * We have retrieved what we are looking for.
		 * Stop the walker.
		 */
		cont = B_FALSE;
	} else {
		if (err == ENOENT)
			err = 0;
		*errp = err;
	}

	return (cont);
}

/*
 * Removes the property value from the DB. The property whose value is to be
 * removed is in `pargp->ia_pname'.
 */
/* ARGSUSED */
boolean_t
ipmgmt_db_resetprop(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	ipmgmt_prop_arg_t	*pargp = arg;

	*errp = 0;
	if (!ipmgmt_nvlist_match(db_nvl, pargp->ia_module,
	    pargp->ia_ifname, pargp->ia_aobjname))
		return (B_TRUE);

	if (!nvlist_exists(db_nvl, pargp->ia_pname))
		return (B_TRUE);

	/*
	 * We found the property in the DB. If IPMGMT_REMOVE is not set then
	 * delete the entry from the db. If it is set, then the property is a
	 * multi-valued property so just remove the specified values from DB.
	 */
	if (pargp->ia_flags & IPMGMT_REMOVE) {
		char	*dbpval = NULL;
		char	*inpval = pargp->ia_pval;
		char	pval[MAXPROPVALLEN];
		char	*val, *lasts;

		*errp = nvlist_lookup_string(db_nvl, pargp->ia_pname, &dbpval);
		if (*errp != 0)
			return (B_FALSE);

		/*
		 * multi-valued properties are represented as comma separated
		 * values. Use string tokenizer functions to split them and
		 * search for the value to be removed.
		 */
		bzero(pval, sizeof (pval));
		if ((val = strtok_r(dbpval, ",", &lasts)) != NULL) {
			if (strcmp(val, inpval) != 0)
				(void) strlcat(pval, val, MAXPROPVALLEN);
			while ((val = strtok_r(NULL, ",", &lasts)) != NULL) {
				if (strcmp(val, inpval) != 0) {
					if (pval[0] != '\0')
						(void) strlcat(pval, ",",
						    MAXPROPVALLEN);
					(void) strlcat(pval, val,
					    MAXPROPVALLEN);
				}
			}
		} else {
			if (strcmp(dbpval, inpval) != 0)
				*errp = ENOENT;
			else
				buf[0] =  '\0';
			return (B_FALSE);
		}
		*errp = nvlist_add_string(db_nvl, pargp->ia_pname, pval);
		if (*errp != 0)
			return (B_FALSE);

		(void) memset(buf, 0, buflen);
		if (ipadm_nvlist2str(db_nvl, buf, buflen) == 0) {
			/* buffer overflow */
			*errp = ENOBUFS;
		}
	} else {
		buf[0] = '\0';
	}

	/* stop the search */
	return (B_FALSE);
}

/*
 * Input arguments can have IPADM_NVP_AOBJNAME or IPADM_NVP_IFNAME. A match is
 * found, when one of the following occurs first.
 * - the input aobjname matches the db aobjname. Return the db address.
 * - the input interface matches the db interface. Return all the
 *   matching db lines with addresses.
 */
/* ARGSUSED */
boolean_t
ipmgmt_db_getaddr(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	ipmgmt_get_cbarg_t	*cbarg = arg;
	char		*db_aobjname = NULL;
	char		*db_ifname = NULL;
	nvlist_t	*db_addr = NULL;
	char		name[IPMGMT_STRSIZE];
	nvpair_t	*nvp;
	boolean_t	add_nvl = B_FALSE;

	/* Parse db nvlist */
	for (nvp = nvlist_next_nvpair(db_nvl, NULL); nvp != NULL;
	    nvp = nvlist_next_nvpair(db_nvl, nvp)) {
		if (nvpair_type(nvp) == DATA_TYPE_NVLIST)
			(void) nvpair_value_nvlist(nvp, &db_addr);
		else if (strcmp(nvpair_name(nvp), IPADM_NVP_IFNAME) == 0)
			(void) nvpair_value_string(nvp, &db_ifname);
		else if (strcmp(nvpair_name(nvp), IPADM_NVP_AOBJNAME) == 0)
			(void) nvpair_value_string(nvp, &db_aobjname);
	}

	if (db_aobjname == NULL) /* Not an address */
		return (B_TRUE);

	/* Check for a match between the aobjnames or the interface name */
	if (cbarg->cb_aobjname[0] != '\0') {
		if (strcmp(cbarg->cb_aobjname, db_aobjname) == 0)
			add_nvl = B_TRUE;
	} else if (cbarg->cb_ifname[0] != '\0') {
		if (strcmp(cbarg->cb_ifname, db_ifname) == 0)
			add_nvl = B_TRUE;
	} else {
		add_nvl = B_TRUE;
	}

	if (add_nvl) {
		(void) snprintf(name, sizeof (name), "%s_%d", db_ifname,
		    cbarg->cb_ocnt);
		*errp = nvlist_add_nvlist(cbarg->cb_onvl, name, db_nvl);
		if (*errp == 0)
			cbarg->cb_ocnt++;
	}
	return (B_TRUE);
}

/*
 * This function only gets called if a volatile filesystem version
 * of the configuration file has been created. This only happens in the
 * extremely rare case that a request has been made to update the configuration
 * file at boottime while the root filesystem was read-only. This is
 * really a rare occurrence now that we don't support UFS root filesystems
 * any longer. This function will periodically attempt to write the
 * configuration back to its location on the root filesystem. Success
 * will indicate that the filesystem is no longer read-only.
 */
/* ARGSUSED */
static void *
ipmgmt_db_restore_thread(void *arg)
{
	int err;

	for (;;) {
		(void) sleep(5);
		(void) pthread_rwlock_wrlock(&ipmgmt_dbconf_lock);
		if (!ipmgmt_rdonly_root)
			break;
		err = ipmgmt_cpfile(IPADM_VOL_DB_FILE, IPADM_DB_FILE, B_FALSE);
		if (err == 0) {
			ipmgmt_rdonly_root = B_FALSE;
			break;
		}
		(void) pthread_rwlock_unlock(&ipmgmt_dbconf_lock);
	}
	(void) pthread_rwlock_unlock(&ipmgmt_dbconf_lock);
	return (NULL);
}

/*
 * This function takes the appropriate lock, read or write, based on the
 * `db_op' and then calls DB walker ipadm_rw_db(). The code is complicated
 * by the fact that we are not always guaranteed to have a writable root
 * filesystem since it is possible that we are reading or writing during
 * bootime while the root filesystem is still read-only. This is, by far,
 * the exception case. Normally, this function will be called when the
 * root filesystem is writable. In the unusual case where this is not
 * true, the configuration file is copied to the volatile file system
 * and is updated there until the root filesystem becomes writable. At
 * that time the file will be moved back to its proper location by
 * ipmgmt_db_restore_thread().
 */
extern int
ipmgmt_db_walk(db_wfunc_t *db_walk_func, void *db_warg, ipadm_db_op_t db_op)
{
	int		err;
	boolean_t	writeop;
	mode_t		mode;
	pthread_t	tid;
	pthread_attr_t	attr;

	writeop = (db_op != IPADM_DB_READ);
	if (writeop) {
		(void) pthread_rwlock_wrlock(&ipmgmt_dbconf_lock);
		mode = IPADM_FILE_MODE;
	} else {
		(void) pthread_rwlock_rdlock(&ipmgmt_dbconf_lock);
		mode = 0;
	}

	/*
	 * Did a previous write attempt fail? If so, don't even try to
	 * read/write to IPADM_DB_FILE.
	 */
	if (!ipmgmt_rdonly_root) {
		err = ipadm_rw_db(db_walk_func, db_warg, IPADM_DB_FILE,
		    mode, db_op);
		if (err != EROFS)
			goto done;
	}

	/*
	 * If we haven't already copied the file to the volatile
	 * file system, do so. This should only happen on a failed
	 * writeop(i.e., we have acquired the write lock above).
	 */
	if (access(IPADM_VOL_DB_FILE, F_OK) != 0) {
		assert(writeop);
		err = ipmgmt_cpfile(IPADM_DB_FILE, IPADM_VOL_DB_FILE, B_TRUE);
		if (err != 0)
			goto done;
		(void) pthread_attr_init(&attr);
		(void) pthread_attr_setdetachstate(&attr,
		    PTHREAD_CREATE_DETACHED);
		(void) pthread_attr_setname_np(&attr, "db_restore");
		err = pthread_create(&tid, &attr, ipmgmt_db_restore_thread,
		    NULL);
		(void) pthread_attr_destroy(&attr);
		if (err != 0) {
			(void) unlink(IPADM_VOL_DB_FILE);
			goto done;
		}
		ipmgmt_rdonly_root = B_TRUE;
	}

	/*
	 * Read/write from the volatile copy.
	 */
	err = ipadm_rw_db(db_walk_func, db_warg, IPADM_VOL_DB_FILE,
	    mode, db_op);
done:
	(void) pthread_rwlock_unlock(&ipmgmt_dbconf_lock);
	return (err);
}

/*
 * Used to add an entry towards the end of DB. It just returns B_TRUE for
 * every line of the DB. When we reach the end, ipadm_rw_db() adds the
 * line at the end.
 */
/* ARGSUSED */
boolean_t
ipmgmt_db_add(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen, int *errp)
{
	return (B_TRUE);
}

/*
 * This function is used to update or create an entry in DB. The nvlist_t,
 * `in_nvl', represents the line we are looking for. Once we ensure the right
 * line from DB, we update that entry.
 */
boolean_t
ipmgmt_db_update(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	ipadm_dbwrite_cbarg_t	*cb = arg;
	uint_t			flags = cb->dbw_flags;
	nvlist_t		*in_nvl = cb->dbw_nvl;
	nvpair_t		*nvp;
	char			*name, *instrval = NULL, *dbstrval = NULL;
	char			pval[MAXPROPVALLEN];

	*errp = 0;
	if (!ipmgmt_nvlist_intersects(db_nvl, in_nvl))
		return (B_TRUE);

	for (nvp = nvlist_next_nvpair(in_nvl, NULL); nvp != NULL;
	    nvp = nvlist_next_nvpair(in_nvl, nvp)) {
		name = nvpair_name(nvp);
		if (!IPADM_PRIV_NVP(name) && nvlist_exists(db_nvl, name))
			break;
	}

	if (nvp == NULL)
		return (B_TRUE);

	assert(nvpair_type(nvp) == DATA_TYPE_STRING);

	if ((*errp = nvpair_value_string(nvp, &instrval)) != 0)
		return (B_FALSE);

	/*
	 * If IPMGMT_APPEND is set then we are dealing with multi-valued
	 * properties. We append to the entry from the db, with the new value.
	 */
	if (flags & IPMGMT_APPEND) {
		if ((*errp = nvlist_lookup_string(db_nvl, name,
		    &dbstrval)) != 0)
			return (B_FALSE);
		(void) snprintf(pval, MAXPROPVALLEN, "%s,%s", dbstrval,
		    instrval);
		if ((*errp = nvlist_add_string(db_nvl, name, pval)) != 0)
			return (B_FALSE);
	} else {
		/* case	of in-line update of a db entry */
		if ((*errp = nvlist_add_string(db_nvl, name, instrval)) != 0)
			return (B_FALSE);
	}

	(void) memset(buf, 0, buflen);
	if (ipadm_nvlist2str(db_nvl, buf, buflen) == 0) {
		/* buffer overflow */
		*errp = ENOBUFS;
	}

	/* we updated the DB entry, so do not continue */
	return (B_FALSE);
}

/*
 * This function is used to update a DB line that describes
 * an interface, its family and group interface
 *
 */
boolean_t
ipmgmt_db_update_if(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	ipadm_dbwrite_cbarg_t *cb = arg;
	ipmgmt_if_updater_ent_t *updater;
	nvlist_t	*in_nvl = cb->dbw_nvl;
	uint_t		flags = cb->dbw_flags;
	nvpair_t	*nvp;
	char		*name;
	char		*db_ifname;
	char		*gifname = NULL;
	char		*mifname = NULL;

	*errp = 0;

	/* Only one flag */
	if ((flags & (IPMGMT_APPEND | IPMGMT_REMOVE)) == 0 ||
	    ((flags & IPMGMT_APPEND) && (flags & IPMGMT_REMOVE))) {
		*errp = EINVAL;
		return (B_FALSE);
	}

	if (!nvlist_exists(db_nvl, IPADM_NVP_FAMILIES))
		return (B_TRUE);

	if (nvlist_exists(db_nvl, IPADM_NVP_IFCLASS) &&
	    nvlist_lookup_string(db_nvl, IPADM_NVP_IFNAME, &db_ifname) == 0 &&
	    nvlist_lookup_string(in_nvl, IPADM_NVP_GIFNAME, &gifname) == 0 &&
	    nvlist_lookup_string(in_nvl, IPADM_NVP_MIFNAMES, &mifname) == 0 &&
	    strcmp(db_ifname, mifname) == 0) {
		if (flags & IPMGMT_APPEND) {
			if ((*errp = nvlist_add_string(db_nvl,
			    IPADM_NVP_GIFNAME, gifname)) != 0)
				return (B_FALSE);
		} else {
			if ((*errp = nvlist_remove(db_nvl, IPADM_NVP_GIFNAME,
			    DATA_TYPE_STRING)) != 0)
				return (B_FALSE);
		}
		cb->dbw_flags &= ~IPMGMT_UPDATE_IPMP;
		goto done;
	}

	if (!ipmgmt_nvlist_intersects(db_nvl, in_nvl))
		return (B_TRUE);

	for (nvp = nvlist_next_nvpair(in_nvl, NULL); nvp != NULL;
	    nvp = nvlist_next_nvpair(in_nvl, nvp)) {
		name = nvpair_name(nvp);
		if (strcmp(name, IPADM_NVP_FAMILIES) != 0 &&
		    strcmp(name, IPADM_NVP_MIFNAMES) != 0)
			continue;

		updater = ipmgmt_find_if_field_updater(name);
		assert(updater != NULL);
		*errp = (*updater->func)(db_nvl, nvp, flags);
		if (*errp != 0)
			return (B_FALSE);
	}

	cb->dbw_flags &= ~IPMGMT_UPDATE_IF;

done:
	(void) memset(buf, 0, buflen);
	if (ipadm_nvlist2str(db_nvl, buf, buflen) == 0) {
		*errp = EOVERFLOW;
		return (B_FALSE);
	}

	/* we finished all operations, so do not continue */
	if ((cb->dbw_flags & (IPMGMT_UPDATE_IF | IPMGMT_UPDATE_IPMP)) == 0)
		return (B_FALSE);

	return (B_TRUE);
}

/*
 * For the given `cbarg->cb_ifname' interface, retrieve the nvlist that
 * represents the persistent interface information.
 * The nvlist contains:
 *      IPADM_NVP_IFNAME
 *      IPADM_NVP_FAMILIES
 *      IPADM_NVP_IF_CLASS
 *
 * (used in 'ipadm show-if')
 */
/* ARGSUSED */
boolean_t
ipmgmt_db_getif(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	ipmgmt_get_cbarg_t *cbarg = arg;
	char		*ifname = cbarg->cb_ifname;
	nvpair_t	*nvp;
	char		*db_ifname = NULL;
	boolean_t	families = B_FALSE;

	/* Parse db nvlist */
	for (nvp = nvlist_next_nvpair(db_nvl, NULL); nvp != NULL;
	    nvp = nvlist_next_nvpair(db_nvl, nvp)) {
		if (strcmp(nvpair_name(nvp), IPADM_NVP_IFNAME) == 0) {
			(void) nvpair_value_string(nvp, &db_ifname);
		} else if (strcmp(nvpair_name(nvp), IPADM_NVP_FAMILIES) == 0) {
			families = B_TRUE;
		}
	}

	if (db_ifname == NULL || !families)
		return (B_TRUE);

	if (ifname != NULL && ifname[0] != '\0' &&
	    strcmp(ifname, db_ifname) != 0)
		return (B_TRUE);

	*errp = nvlist_add_nvlist(cbarg->cb_onvl, db_ifname, db_nvl);
	if (*errp == 0)
		cbarg->cb_ocnt++;

	if (ifname != NULL && ifname[0] != '\0')
		return (B_FALSE);

	return (B_TRUE);
}

/*
 * Deletes those entries from the database for which interface name
 * matches with the given `cbarg->cb_ifname'
 */
/* ARGSUSED */
boolean_t
ipmgmt_db_resetif(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	ipmgmt_if_cbarg_t *cbarg = arg;
	boolean_t	isv6 = (cbarg->cb_family == AF_INET6);
	char		*ifname = cbarg->cb_ifname;
	char		*modstr = NULL;
	char		*aobjname;
	uint_t		proto;
	ipmgmt_aobjmap_t *head;
	boolean_t	aobjfound = B_FALSE;

	*errp = 0;

	if (!ipmgmt_nvlist_contains(db_nvl, NULL, ifname, NULL))
		return (B_TRUE);

	if (nvlist_exists(db_nvl, IPADM_NVP_FAMILIES)) {

		if ((*errp = ipmgmt_update_family_nvp(db_nvl, cbarg->cb_family,
		    IPMGMT_REMOVE)) != 0) {
			return (B_FALSE);
		}

		if (cbarg->cb_family == AF_INET) {
			cbarg->cb_ipv4exists = B_FALSE;
		} else {
			assert(cbarg->cb_family == AF_INET6);
			cbarg->cb_ipv6exists = B_FALSE;
		}
		if (!nvlist_exists(db_nvl, IPADM_NVP_FAMILIES)) {
			cbarg->cb_ipv4exists = B_FALSE;
			cbarg->cb_ipv6exists = B_FALSE;
			goto delete;
		}
		/* Otherwise need to reconstruct this string */
		(void) memset(buf, 0, buflen);
		if (ipadm_nvlist2str(db_nvl, buf, buflen) == 0) {
			/* buffer overflow */
			*errp = EOVERFLOW;
			return (B_FALSE);
		}
		return (B_TRUE);
	}

	/* Reset all the interface configurations for 'ifname' */
	if (isv6 && (nvlist_exists(db_nvl, IPADM_NVP_IPV6ADDR) ||
	    nvlist_exists(db_nvl, IPADM_NVP_INTFID))) {
		goto delete;
	}
	if (!isv6 &&
	    (nvlist_exists(db_nvl, IPADM_NVP_IPV4ADDR) ||
	    nvlist_exists(db_nvl, IPADM_NVP_DHCP))) {
		goto delete;
	}

	if (nvlist_lookup_string(db_nvl, IPADM_NVP_AOBJNAME, &aobjname) == 0) {
		/*
		 * This must be an address property. Delete this
		 * line if there is a match in the address family.
		 */
		head = aobjmap.aobjmap_head;
		while (head != NULL) {
			if (strcmp(head->am_aobjname, aobjname) == 0) {
				aobjfound = B_TRUE;
				if (head->am_family == cbarg->cb_family)
					goto delete;
			}
			head = head->am_next;
		}
		/*
		 * If aobjfound = B_FALSE, then this address is not
		 * available in active configuration. We should go ahead
		 * and delete it.
		 */
		if (!aobjfound)
			goto delete;
	}

	/*
	 * If we are removing both v4 and v6 interface, then we get rid of
	 * all the properties for that interface. On the other hand, if we
	 * are deleting only v4 instance of an interface, then we delete v4
	 * properties only.
	 */
	if (nvlist_lookup_string(db_nvl, IPADM_NVP_PROTONAME, &modstr) == 0) {
		proto = ipadm_str2proto(modstr);
		switch (proto) {
		case MOD_PROTO_IPV6:
			if (isv6)
				goto delete;
			break;
		case MOD_PROTO_IPV4:
			if (!isv6)
				goto delete;
			break;
		case MOD_PROTO_IP:
			if (!cbarg->cb_ipv4exists && !cbarg->cb_ipv6exists)
				goto delete;
			break;
		}
	}
	/* Not found a match yet. Continue processing the db */
	return (B_TRUE);
delete:
	/* delete the line from the db */
	buf[0] = '\0';
	return (B_TRUE);
}

/*
 * Deletes those entries from the database for which address object name
 * matches with the given `cbarg->cb_aobjname'
 */
/* ARGSUSED */
boolean_t
ipmgmt_db_resetaddr(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	ipmgmt_resetaddr_cbarg_t *cbarg = arg;
	char		*aobjname = cbarg->cb_aobjname;

	*errp = 0;
	if (!ipmgmt_nvlist_contains(db_nvl, NULL, NULL, aobjname))
		return (B_TRUE);

	/* delete the line from the db */
	buf[0] = '\0';
	return (B_TRUE);
}

/*
 * Retrieves all interface props, including addresses, for given interface(s).
 * `invl' contains the list of interfaces, for which information need to be
 * retrieved.
 */
/* ARGSUSED */
boolean_t
ipmgmt_db_initif(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	ipmgmt_initif_cbarg_t	*cbarg = arg;
	nvlist_t		*onvl = cbarg->cb_onvl;
	nvlist_t		*invl = cbarg->cb_invl;
	sa_family_t		in_af = cbarg->cb_family;
	char			*db_ifname;

	*errp = 0;
	if (nvlist_lookup_string(db_nvl, IPADM_NVP_IFNAME, &db_ifname) == 0 &&
	    nvlist_exists(invl, db_ifname)) {
		char		name[IPMGMT_STRSIZE];
		sa_family_t	db_af = in_af;
		uint_t		proto;
		char		*pstr;

		if (in_af != AF_UNSPEC) {
			if (nvlist_lookup_string(db_nvl, IPADM_NVP_PROTONAME,
			    &pstr) == 0) {
				proto = ipadm_str2proto(pstr);
				if (proto == MOD_PROTO_IPV4)
					db_af = AF_INET;
				else if (proto == MOD_PROTO_IPV6)
					db_af = AF_INET6;
				else
					db_af = in_af;
			} else {
				if (nvlist_exists(db_nvl, IPADM_NVP_IPV4ADDR) ||
				    nvlist_exists(db_nvl, IPADM_NVP_DHCP))
					db_af = AF_INET;
				else
					db_af = AF_INET6;
			}
		}
		if (in_af == db_af) {
			(void) snprintf(name, sizeof (name), "%s_%d", db_ifname,
			    cbarg->cb_ocnt);
			*errp = nvlist_add_nvlist(onvl, name, db_nvl);
			if (*errp == 0)
				cbarg->cb_ocnt++;
		}
	}
	return (B_TRUE);
}

/*
 * helper function for ipmgmt_aobjmap_op(). Adds the node pointed by `nodep'
 * into `aobjmap' structure.
 */
static int
i_ipmgmt_add_amnode(ipmgmt_aobjmap_t *nodep)
{
	ipmgmt_aobjmap_t	*new, *head;

	head = aobjmap.aobjmap_head;
	if ((new = malloc(sizeof (ipmgmt_aobjmap_t))) == NULL)
		return (ENOMEM);
	*new = *nodep;
	new->am_next = NULL;

	/* Add the node at the beginning of the list */
	if (head == NULL) {
		aobjmap.aobjmap_head = new;
	} else {
		new->am_next = aobjmap.aobjmap_head;
		aobjmap.aobjmap_head = new;
	}
	return (0);
}

/*
 * A recursive function to generate alphabetized number given a decimal number.
 * Decimal 0 to 25 maps to 'a' to 'z' and then the counting continues with 'aa',
 * 'ab', 'ac', et al.
 */
static void
i_ipmgmt_num2priv_aobjname(uint32_t num, char **cp, char *endp)
{
	if (num >= 26)
		i_ipmgmt_num2priv_aobjname(num / 26 - 1, cp, endp);
	if (*cp != endp) {
		*cp[0] = 'a' + (num % 26);
		(*cp)++;
	}
}

/*
 * This function generates an `aobjname', when required, and then does
 * lookup-add. If `nodep->am_aobjname' is not an empty string, then it walks
 * through the `aobjmap' to check if an address object with the same
 * `nodep->am_aobjname' exists. If it exists, EEXIST is returned as duplicate
 * `aobjname's are not allowed.
 *
 * If `nodep->am_aobjname' is an empty string then the daemon generates an
 * `aobjname' using the `am_nextnum', which contains the next number to be
 * used to generate `aobjname'. `am_nextnum' is converted to base26 using
 * `a-z' alphabets in i_ipmgmt_num2priv_aobjname().
 *
 * `am_nextnum' will be 0 to begin with. Every time an address object that
 * needs `aobjname' is added it's incremented by 1. So for the first address
 * object on net0 the `am_aobjname' will be net0/_a and `am_nextnum' will be 1.
 * For the second address object on that interface `am_aobjname' will be net0/_b
 * and  `am_nextnum' will incremented to 2.
 */
static int
i_ipmgmt_lookupadd_amnode(ipmgmt_aobjmap_t *nodep)
{
	ipmgmt_aobjmap_t	*head;
	uint32_t		nextnum;

	for (head = aobjmap.aobjmap_head; head != NULL; head = head->am_next)
		if (strcmp(head->am_ifname, nodep->am_ifname) == 0)
			break;
	nextnum = (head == NULL ? 0 : head->am_nextnum);

	/*
	 * if `aobjname' is empty, then the daemon has to generate the
	 * next `aobjname' for the given interface and family.
	 */
	if (nodep->am_aobjname[0] == '\0') {
		char tmpstr[IPADM_AOBJ_USTRSIZ - 1];  /* 1 for leading  '_' */
		char *cp = tmpstr;
		char *endp = tmpstr + sizeof (tmpstr);

		i_ipmgmt_num2priv_aobjname(nextnum, &cp, endp);

		if (cp == endp)
			return (EINVAL);
		cp[0] = '\0';

		if (snprintf(nodep->am_aobjname, IPADM_AOBJSIZ, "%s/_%s",
		    nodep->am_ifname, tmpstr) >= IPADM_AOBJSIZ) {
			return (EINVAL);
		}
		nodep->am_nextnum = ++nextnum;
	} else {
		for (head = aobjmap.aobjmap_head; head != NULL;
		    head = head->am_next) {
			if (strcmp(head->am_aobjname, nodep->am_aobjname) == 0)
				return (EEXIST);
		}
		nodep->am_nextnum = nextnum;
	}
	return (i_ipmgmt_add_amnode(nodep));
}

/*
 * Performs following operations on the global `aobjmap' linked list.
 * (a) ADDROBJ_ADD: add or update address object in `aobjmap'
 * (b) ADDROBJ_DELETE: delete address object from `aobjmap'
 * (c) ADDROBJ_LOOKUPADD: place a stub address object in `aobjmap'
 * (d) ADDROBJ_SETLIFNUM: Sets the lifnum for an address object in `aobjmap'
 */
int
ipmgmt_aobjmap_op(ipmgmt_aobjmap_t *nodep, uint32_t op)
{
	ipmgmt_aobjmap_t	*head, *prev, *matched = NULL;
	boolean_t		update = B_TRUE;
	int			err = 0;
	ipadm_db_op_t		db_op = IPADM_DB_READ;

	(void) pthread_rwlock_wrlock(&aobjmap.aobjmap_rwlock);

	head = aobjmap.aobjmap_head;
	switch (op) {
	case ADDROBJ_ADD:
		/*
		 * check for stub nodes (added by ADDROBJ_LOOKUPADD) and
		 * update, else add the new node.
		 */
		for (; head != NULL; head = head->am_next) {
			/*
			 * For IPv6, we need to distinguish between the
			 * linklocal and non-linklocal nodes
			 */
			if (strcmp(head->am_aobjname,
			    nodep->am_aobjname) == 0 &&
			    (head->am_atype != IPADM_ADDR_IPV6_ADDRCONF ||
			    head->ipmgmt_am_linklocal ==
			    nodep->ipmgmt_am_linklocal))
				break;
		}

		if (head != NULL) {
			/* update the node */
			(void) strlcpy(head->am_ifname, nodep->am_ifname,
			    sizeof (head->am_ifname));
			head->am_lnum = nodep->am_lnum;
			head->am_family = nodep->am_family;
			head->am_flags = nodep->am_flags;
			head->am_atype = nodep->am_atype;
			head->am_atype_cache = nodep->am_atype_cache;
		} else {
			for (head = aobjmap.aobjmap_head; head != NULL;
			    head = head->am_next) {
				if (strcmp(head->am_ifname,
				    nodep->am_ifname) == 0)
					break;
			}
			nodep->am_nextnum = (head == NULL ? 0 :
			    head->am_nextnum);
			err = i_ipmgmt_add_amnode(nodep);
		}
		db_op = IPADM_DB_WRITE;
		break;
	case ADDROBJ_DELETE:
		prev = head;
		while (head != NULL) {
			if (strcmp(head->am_aobjname,
			    nodep->am_aobjname) == 0) {
				nodep->am_atype = head->am_atype;
				/*
				 * There could be multiple IPV6_ADDRCONF nodes,
				 * with same address object name, so check for
				 * logical number also.
				 */
				if (head->am_atype !=
				    IPADM_ADDR_IPV6_ADDRCONF ||
				    nodep->am_lnum == head->am_lnum)
					break;
			}
			prev = head;
			head = head->am_next;
		}
		if (head != NULL) {
			/*
			 * If the address object is in both active and
			 * persistent configuration and the user is deleting it
			 * only from active configuration then mark this node
			 * for deletion by reseting IPMGMT_ACTIVE bit.
			 * With this the same address object name cannot
			 * be reused until it is permanently removed.
			 */
			if (head->am_flags == (IPMGMT_ACTIVE|IPMGMT_PERSIST) &&
			    nodep->am_flags == IPMGMT_ACTIVE) {
				/* Update flags in the in-memory map. */
				head->am_flags &= ~IPMGMT_ACTIVE;
				head->am_lnum = -1;

				/* Update info in file. */
				db_op = IPADM_DB_WRITE;
				*nodep = *head;
			} else {
				(void) strlcpy(nodep->am_ifname,
				    head->am_ifname,
				    sizeof (nodep->am_ifname));
				/* otherwise delete the node */
				if (head == aobjmap.aobjmap_head)
					aobjmap.aobjmap_head = head->am_next;
				else
					prev->am_next = head->am_next;
				free(head);
				db_op = IPADM_DB_DELETE;
			}
		} else {
			err = ENOENT;
		}
		break;
	case ADDROBJ_LOOKUPADD:
		err = i_ipmgmt_lookupadd_amnode(nodep);
		update = B_FALSE;
		break;
	case ADDROBJ_SETLIFNUM:
		update = B_FALSE;
		for (; head != NULL; head = head->am_next) {
			if (strcmp(head->am_ifname,
			    nodep->am_ifname) == 0 &&
			    head->am_family == nodep->am_family &&
			    head->am_lnum == nodep->am_lnum) {
				err = EEXIST;
				break;
			}
			if (strcmp(head->am_aobjname,
			    nodep->am_aobjname) == 0) {
				matched = head;
			}
		}
		if (err == EEXIST)
			break;
		if (matched != NULL) {
			/* update the lifnum */
			matched->am_lnum = nodep->am_lnum;
		} else {
			err = ENOENT;
		}
		break;
	default:
		assert(0);
	}

	if (err == 0 && update)
		err = ipmgmt_persist_aobjmap(nodep, db_op);

	(void) pthread_rwlock_unlock(&aobjmap.aobjmap_rwlock);

	return (err);
}

/*
 * Given a node in `aobjmap', this function converts it into nvlist_t structure.
 * The content to be written to DB must be represented as nvlist_t.
 */
static int
i_ipmgmt_node2nvl(nvlist_t **nvl, ipmgmt_aobjmap_t *np)
{
	int	err;
	char	strval[IPMGMT_STRSIZE];

	*nvl = NULL;
	if ((err = nvlist_alloc(nvl, NV_UNIQUE_NAME, 0)) != 0)
		goto fail;

	if ((err = nvlist_add_string(*nvl, IPADM_NVP_AOBJNAME,
	    np->am_aobjname)) != 0)
		goto fail;

	if ((err = nvlist_add_string(*nvl, IPADM_NVP_IFNAME,
	    np->am_ifname)) != 0)
		goto fail;

	(void) snprintf(strval, IPMGMT_STRSIZE, "%d", np->am_lnum);
	if ((err = nvlist_add_string(*nvl, IPADM_NVP_LIFNUM, strval)) != 0)
		goto fail;

	(void) snprintf(strval, IPMGMT_STRSIZE, "%d", np->am_family);
	if ((err = nvlist_add_string(*nvl, IPADM_NVP_FAMILY, strval)) != 0)
		goto fail;

	(void) snprintf(strval, IPMGMT_STRSIZE, "%d", np->am_flags);
	if ((err = nvlist_add_string(*nvl, FLAGS, strval)) != 0)
		goto fail;

	(void) snprintf(strval, IPMGMT_STRSIZE, "%d", np->am_atype);
	if ((err = nvlist_add_string(*nvl, ATYPE, strval)) != 0)
		goto fail;

	switch (np->am_atype) {
		case IPADM_ADDR_IPV6_ADDRCONF: {
			struct sockaddr_in6	*in6;

			in6 = &np->ipmgmt_am_ifid;
			if (np->ipmgmt_am_linklocal &&
			    IN6_IS_ADDR_UNSPECIFIED(&in6->sin6_addr)) {
				if ((err = nvlist_add_string(*nvl,
				    IPADM_NVP_IPNUMADDR, "default")) != 0) {
					goto fail;
				}
			} else {
				if (inet_ntop(AF_INET6, &in6->sin6_addr, strval,
				    IPMGMT_STRSIZE) == NULL) {
					err = errno;
					goto fail;
				}
				if ((err = nvlist_add_string(*nvl,
				    IPADM_NVP_IPNUMADDR, strval)) != 0) {
					goto fail;
				}
			}
		}
			break;
		case IPADM_ADDR_DHCP: {
			if (*np->ipmgmt_am_reqhost != '\0' &&
			    (err = nvlist_add_string(*nvl, IPADM_NVP_REQHOST,
			    np->ipmgmt_am_reqhost)) != 0)
				goto fail;
		}
			/* FALLTHRU */
		default:
			if ((err = nvlist_add_string(*nvl, IPADM_NVP_IPNUMADDR,
			    "")) != 0)
				goto fail;
			break;
	}
	return (err);
fail:
	nvlist_free(*nvl);
	return (err);
}

/*
 * Read the aobjmap data store and build the in-memory representation
 * of the aobjmap. We don't need to hold any locks while building this as
 * we do this in very early stage of daemon coming up, even before the door
 * is opened.
 */
/* ARGSUSED */
extern boolean_t
ipmgmt_aobjmap_init(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	nvpair_t		*nvp = NULL;
	char			*name, *strval = NULL;
	ipmgmt_aobjmap_t	node;
	struct sockaddr_in6	*in6;

	*errp = 0;
	node.am_next = NULL;
	for (nvp = nvlist_next_nvpair(db_nvl, NULL); nvp != NULL;
	    nvp = nvlist_next_nvpair(db_nvl, nvp)) {
		name = nvpair_name(nvp);

		if ((*errp = nvpair_value_string(nvp, &strval)) != 0)
			return (B_TRUE);
		if (strcmp(IPADM_NVP_AOBJNAME, name) == 0) {
			(void) strlcpy(node.am_aobjname, strval,
			    sizeof (node.am_aobjname));
		} else if (strcmp(IPADM_NVP_IFNAME, name) == 0) {
			(void) strlcpy(node.am_ifname, strval,
			    sizeof (node.am_ifname));
		} else if (strcmp(IPADM_NVP_LIFNUM, name) == 0) {
			node.am_lnum = atoi(strval);
		} else if (strcmp(IPADM_NVP_FAMILY, name) == 0) {
			node.am_family = (sa_family_t)atoi(strval);
		} else if (strcmp(FLAGS, name) == 0) {
			node.am_flags = atoi(strval);
		} else if (strcmp(ATYPE, name) == 0) {
			node.am_atype = (ipadm_addr_type_t)atoi(strval);
		} else if (strcmp(IPADM_NVP_IPNUMADDR, name) == 0) {
			if (node.am_atype == IPADM_ADDR_IPV6_ADDRCONF) {
				in6 = &node.ipmgmt_am_ifid;
				if (strcmp(strval, "default") == 0) {
					bzero(in6,
					    sizeof (node.ipmgmt_am_ifid));
					node.ipmgmt_am_linklocal = B_TRUE;
				} else {
					(void) inet_pton(AF_INET6, strval,
					    &in6->sin6_addr);
					if (IN6_IS_ADDR_UNSPECIFIED(
					    &in6->sin6_addr))
						node.ipmgmt_am_linklocal =
						    B_TRUE;
				}
			}
		}
	}

	/* we have all the information we need, add the node */
	*errp = i_ipmgmt_add_amnode(&node);

	return (B_TRUE);
}

/*
 * Updates an entry from the temporary cache file, which matches the given
 * address object name.
 */
/* ARGSUSED */
static boolean_t
ipmgmt_update_aobjmap(void *arg, nvlist_t *db_nvl, char *buf,
    size_t buflen, int *errp)
{
	ipadm_dbwrite_cbarg_t	*cb = arg;
	nvlist_t		*in_nvl = cb->dbw_nvl;
	uint32_t		flags = cb->dbw_flags;
	char			*db_lifnumstr = NULL, *in_lifnumstr = NULL;

	*errp = 0;
	if (!ipmgmt_nvlist_intersects(db_nvl, in_nvl))
		return (B_TRUE);

	if (flags & IPMGMT_ATYPE_V6ACONF) {
		if (nvlist_lookup_string(db_nvl, IPADM_NVP_LIFNUM,
		    &db_lifnumstr) != 0 ||
		    nvlist_lookup_string(in_nvl, IPADM_NVP_LIFNUM,
		    &in_lifnumstr) != 0 ||
		    (atoi(db_lifnumstr) != -1 && atoi(in_lifnumstr) != -1 &&
		    strcmp(db_lifnumstr, in_lifnumstr) != 0))
			return (B_TRUE);
	}

	/* we found the match */
	(void) memset(buf, 0, buflen);
	if (ipadm_nvlist2str(in_nvl, buf, buflen) == 0) {
		/* buffer overflow */
		*errp = ENOBUFS;
	}

	/* stop the walker */
	return (B_FALSE);
}

/*
 * Deletes an entry from the temporary cache file, which matches the given
 * address object name.
 */
/* ARGSUSED */
static boolean_t
ipmgmt_delete_aobjmap(void *arg, nvlist_t *db_nvl, char *buf,
    size_t buflen, int *errp)
{
	ipmgmt_aobjmap_t	*nodep = arg;
	char			*db_lifnumstr = NULL;

	*errp = 0;
	if (!ipmgmt_nvlist_match(db_nvl, NULL, nodep->am_ifname,
	    nodep->am_aobjname))
		return (B_TRUE);

	if (nodep->am_atype == IPADM_ADDR_IPV6_ADDRCONF) {
		if (nvlist_lookup_string(db_nvl, IPADM_NVP_LIFNUM,
		    &db_lifnumstr) != 0 || atoi(db_lifnumstr) != nodep->am_lnum)
			return (B_TRUE);
	}

	/* we found the match, delete the line from the db */
	buf[0] = '\0';

	/* stop the walker */
	return (B_FALSE);
}

/*
 * Adds or deletes aobjmap node information into a temporary cache file.
 */
extern int
ipmgmt_persist_aobjmap(ipmgmt_aobjmap_t *nodep, ipadm_db_op_t op)
{
	int			err;
	ipadm_dbwrite_cbarg_t	cb;
	nvlist_t		*nvl = NULL;

	if (op == IPADM_DB_WRITE) {
		if ((err = i_ipmgmt_node2nvl(&nvl, nodep)) != 0)
			return (err);
		cb.dbw_nvl = nvl;
		if (nodep->am_atype == IPADM_ADDR_IPV6_ADDRCONF)
			cb.dbw_flags = IPMGMT_ATYPE_V6ACONF;
		else
			cb.dbw_flags = 0;

		err = ipadm_rw_db(ipmgmt_update_aobjmap, &cb,
		    ADDROBJ_MAPPING_DB_FILE, IPADM_FILE_MODE, IPADM_DB_WRITE);
		nvlist_free(nvl);
	} else {
		assert(op == IPADM_DB_DELETE);

		err = ipadm_rw_db(ipmgmt_delete_aobjmap, nodep,
		    ADDROBJ_MAPPING_DB_FILE, IPADM_FILE_MODE, IPADM_DB_DELETE);
	}
	return (err);
}

/*
 * upgrades the ipadm data-store. It renames all the old private protocol
 * property names which start with leading protocol names to begin with
 * IPADM_PRIV_PROP_PREFIX.
 */
/* ARGSUSED */
boolean_t
ipmgmt_db_upgrade(void *arg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	nvpair_t	*nvp;
	char		*name, *pname = NULL, *protostr = NULL, *pval = NULL;
	uint_t		proto, nproto;
	char		nname[IPMGMT_STRSIZE], tmpstr[IPMGMT_STRSIZE];

	*errp = 0;
	/*
	 * We are interested in lines which contain protocol properties. We
	 * walk through other lines in the DB.
	 */
	if (nvlist_exists(db_nvl, IPADM_NVP_IFNAME) ||
	    nvlist_exists(db_nvl, IPADM_NVP_AOBJNAME)) {
		return (B_TRUE);
	}
	assert(nvlist_exists(db_nvl, IPADM_NVP_PROTONAME));

	/*
	 * extract the propname from the `db_nvl' and also extract the
	 * protocol from the `db_nvl'.
	 */
	for (nvp = nvlist_next_nvpair(db_nvl, NULL); nvp != NULL;
	    nvp = nvlist_next_nvpair(db_nvl, nvp)) {
		name = nvpair_name(nvp);
		if (strcmp(name, IPADM_NVP_PROTONAME) == 0) {
			if (nvpair_value_string(nvp, &protostr) != 0)
				return (B_TRUE);
		} else {
			assert(!IPADM_PRIV_NVP(name));
			pname = name;
			if (nvpair_value_string(nvp, &pval) != 0)
				return (B_TRUE);
		}
	}

	/* if the private property is in the right format return */
	if (strncmp(pname, IPADM_PERSIST_PRIVPROP_PREFIX,
	    strlen(IPADM_PERSIST_PRIVPROP_PREFIX)) == 0) {
		return (B_TRUE);
	}
	/* if it's a public property move onto the next property */
	nproto = proto = ipadm_str2proto(protostr);
	if (ipadm_legacy2new_propname(pname, nname, sizeof (nname),
	    &nproto) != 0) {
		return (B_TRUE);
	}

	/* replace the old protocol with new protocol, if required */
	if (nproto != proto) {
		protostr = ipadm_proto2str(nproto);
		if (nvlist_add_string(db_nvl, IPADM_NVP_PROTONAME,
		    protostr) != 0) {
			return (B_TRUE);
		}
	}

	/* replace the old property name with new property name, if required */
	/* add the prefix to property name */
	(void) snprintf(tmpstr, sizeof (tmpstr), "_%s", nname);
	if (nvlist_add_string(db_nvl, tmpstr, pval) != 0 ||
	    nvlist_remove(db_nvl, pname, DATA_TYPE_STRING) != 0) {
		return (B_TRUE);
	}
	(void) memset(buf, 0, buflen);
	if (ipadm_nvlist2str(db_nvl, buf, buflen) == 0) {
		/* buffer overflow */
		*errp = ENOBUFS;
	}
	return (B_TRUE);
}

/*
 * Called during boot.
 *
 * Walk through the DB and apply all the global module properties. We plow
 * through the DB even if we fail to apply property.
 */
/* ARGSUSED */
static boolean_t
ipmgmt_db_init(void *cbarg, nvlist_t *db_nvl, char *buf, size_t buflen,
    int *errp)
{
	ipadm_handle_t	iph = cbarg;
	nvpair_t	*nvp, *pnvp = NULL;
	char		*strval = NULL, *name, *mod = NULL, *pname;
	char		tmpstr[IPMGMT_STRSIZE];
	uint_t		proto;

	/*
	 * We could have used nvl_exists() directly, however we need several
	 * calls to it and each call traverses the list. Since this codepath
	 * is exercised during boot, let's traverse the list ourselves and do
	 * the necessary checks.
	 */
	for (nvp = nvlist_next_nvpair(db_nvl, NULL); nvp != NULL;
	    nvp = nvlist_next_nvpair(db_nvl, nvp)) {
		name = nvpair_name(nvp);
		if (IPADM_PRIV_NVP(name)) {
			if (strcmp(name, IPADM_NVP_IFNAME) == 0 ||
			    strcmp(name, IPADM_NVP_AOBJNAME) == 0)
				return (B_TRUE);
			else if (strcmp(name, IPADM_NVP_PROTONAME) == 0 &&
			    nvpair_value_string(nvp, &mod) != 0)
				return (B_TRUE);
		} else {
			/* possible a property */
			pnvp = nvp;
		}
	}

	/* If we are here then we have found a global property */
	assert(mod != NULL);
	assert(nvpair_type(pnvp) == DATA_TYPE_STRING);

	proto = ipadm_str2proto(mod);
	name = nvpair_name(pnvp);
	if (nvpair_value_string(pnvp, &strval) == 0) {
		if (strncmp(name, IPADM_PERSIST_PRIVPROP_PREFIX,
		    strlen(IPADM_PERSIST_PRIVPROP_PREFIX)) == 0) {
			/* private protocol property */
			pname = &name[1];
		} else if (ipadm_legacy2new_propname(name, tmpstr,
		    sizeof (tmpstr), &proto) == 0) {
			pname = tmpstr;
		} else {
			pname = name;
		}
		if (ipadm_set_prop(iph, pname, strval, proto,
		    IPADM_OPT_ACTIVE) != IPADM_SUCCESS) {
			ipmgmt_log(LOG_WARNING, "Failed to reapply property %s",
			    pname);
		}
	}

	return (B_TRUE);
}

/* initialize global module properties */
void
ipmgmt_init_prop()
{
	ipadm_handle_t	iph = NULL;

	if (ipadm_open(&iph, IPH_INIT) != IPADM_SUCCESS) {
		ipmgmt_log(LOG_WARNING, "Could not reapply any of the "
		    "persisted protocol properties");
		return;
	}
	/* ipmgmt_db_init() logs warnings if there are any issues */
	(void) ipmgmt_db_walk(ipmgmt_db_init, iph, IPADM_DB_READ);
	ipadm_close(iph);
}

void
ipmgmt_release_scf_resources(scf_resources_t *res)
{
	scf_entry_destroy(res->sr_ent);
	scf_transaction_destroy(res->sr_tx);
	scf_value_destroy(res->sr_val);
	scf_property_destroy(res->sr_prop);
	scf_pg_destroy(res->sr_pg);
	scf_instance_destroy(res->sr_inst);
	(void) scf_handle_unbind(res->sr_handle);
	scf_handle_destroy(res->sr_handle);
}

/*
 * It creates the necessary SCF handles and binds the given `fmri' to an
 * instance. These resources are required for retrieving property value,
 * creating property groups and modifying property values.
 */
int
ipmgmt_create_scf_resources(const char *fmri, scf_resources_t *res)
{
	res->sr_tx = NULL;
	res->sr_ent = NULL;
	res->sr_inst = NULL;
	res->sr_pg = NULL;
	res->sr_prop = NULL;
	res->sr_val = NULL;

	if ((res->sr_handle = scf_handle_create(SCF_VERSION)) == NULL)
		return (-1);

	if (scf_handle_bind(res->sr_handle) != 0) {
		scf_handle_destroy(res->sr_handle);
		return (-1);
	}
	if ((res->sr_inst = scf_instance_create(res->sr_handle)) == NULL)
		goto failure;
	if (scf_handle_decode_fmri(res->sr_handle, fmri, NULL, NULL,
	    res->sr_inst, NULL, NULL, SCF_DECODE_FMRI_REQUIRE_INSTANCE) != 0) {
		goto failure;
	}
	/* we will create the rest of the resources on demand */
	return (0);

failure:
	ipmgmt_log(LOG_WARNING, "failed to create scf resources: %s",
	    scf_strerror(scf_error()));
	ipmgmt_release_scf_resources(res);
	return (-1);
}

/*
 * persists the `pval' for a given property `pname' in SCF. The only supported
 * SCF property types are INTEGER and ASTRING.
 */
static int
ipmgmt_set_scfprop_value(scf_resources_t *res, const char *pname, void *pval,
    scf_type_t ptype)
{
	int result = -1;
	boolean_t new;

	if ((res->sr_val = scf_value_create(res->sr_handle)) == NULL)
		goto failure;
	switch (ptype) {
	case SCF_TYPE_INTEGER:
		scf_value_set_integer(res->sr_val, *(int64_t *)pval);
		break;
	case SCF_TYPE_ASTRING:
		if (scf_value_set_astring(res->sr_val, (char *)pval) != 0) {
			ipmgmt_log(LOG_WARNING, "Error setting string value %s "
			    "for property %s: %s", pval, pname,
			    scf_strerror(scf_error()));
			goto failure;
		}
		break;
	default:
		goto failure;
	}

	if ((res->sr_tx = scf_transaction_create(res->sr_handle)) == NULL)
		goto failure;
	if ((res->sr_ent = scf_entry_create(res->sr_handle)) == NULL)
		goto failure;
	if ((res->sr_prop = scf_property_create(res->sr_handle)) == NULL)
		goto failure;

retry:
	new = (scf_pg_get_property(res->sr_pg, pname, res->sr_prop) != 0);
	if (scf_transaction_start(res->sr_tx, res->sr_pg) == -1)
		goto failure;
	if (new) {
		if (scf_transaction_property_new(res->sr_tx, res->sr_ent,
		    pname, ptype) == -1) {
			goto failure;
		}
	} else {
		if (scf_transaction_property_change(res->sr_tx, res->sr_ent,
		    pname, ptype) == -1) {
			goto failure;
		}
	}

	if (scf_entry_add_value(res->sr_ent, res->sr_val) != 0)
		goto failure;

	result = scf_transaction_commit(res->sr_tx);
	if (result == 0) {
		scf_transaction_reset(res->sr_tx);
		if (scf_pg_update(res->sr_pg) == -1) {
			goto failure;
		}
		goto retry;
	}
	if (result == -1)
		goto failure;
	return (0);

failure:
	ipmgmt_log(LOG_WARNING, "failed to save the data in SCF: %s",
	    scf_strerror(scf_error()));
	return (-1);
}

/*
 * Given a `pgname'/`pname', it retrieves the value based on `ptype' and
 * places it in `pval'.
 */
static int
ipmgmt_get_scfprop(scf_resources_t *res, const char *pgname, const char *pname,
    void *pval, scf_type_t ptype)
{
	ssize_t		numvals;
	scf_simple_prop_t *prop;

	prop = scf_simple_prop_get(res->sr_handle, IPMGMTD_FMRI, pgname, pname);
	numvals = scf_simple_prop_numvalues(prop);
	if (numvals <= 0)
		goto ret;
	switch (ptype) {
	case SCF_TYPE_INTEGER:
		*(int64_t **)pval = scf_simple_prop_next_integer(prop);
		break;
	case SCF_TYPE_ASTRING:
		*(char **)pval = scf_simple_prop_next_astring(prop);
		break;
	default:
		break;
	}
ret:
	scf_simple_prop_free(prop);
	return (numvals);
}

/*
 * It stores the `pval' for given `pgname'/`pname' property group in SCF.
 */
static int
ipmgmt_set_scfprop(scf_resources_t *res, const char *pgname, const char *pname,
    void *pval, scf_type_t ptype)
{
	scf_error_t		err;

	if ((res->sr_pg = scf_pg_create(res->sr_handle)) == NULL) {
		ipmgmt_log(LOG_WARNING, "failed to create property group: %s",
		    scf_strerror(scf_error()));
		return (-1);
	}

	if (scf_instance_add_pg(res->sr_inst, pgname, SCF_GROUP_APPLICATION,
	    0, res->sr_pg) != 0) {
		if ((err = scf_error()) != SCF_ERROR_EXISTS) {
			ipmgmt_log(LOG_WARNING,
			    "Error adding property group '%s/%s': %s",
			    pgname, pname, scf_strerror(err));
			return (-1);
		}
		/*
		 * if the property group already exists, then we get the
		 * composed view of the property group for the given instance.
		 */
		if (scf_instance_get_pg_composed(res->sr_inst, NULL, pgname,
		    res->sr_pg) != 0) {
			ipmgmt_log(LOG_WARNING, "Error getting composed view "
			    "of the property group '%s/%s': %s", pgname, pname,
			    scf_strerror(scf_error()));
			return (-1);
		}
	}

	return (ipmgmt_set_scfprop_value(res, pname, pval, ptype));
}

/*
 * Returns B_TRUE, if the non-global zone is being booted for the first time
 * after being installed. This is required to setup the ipadm data-store for
 * the first boot of the non-global zone. Please see, PSARC 2010/166,
 * for more info.
 *
 * Note that, this API cannot be used to determine first boot post image-update.
 * 'pkg image-update' clones the current BE and the existing value of
 * ipmgmtd/first_boot_done will be carried forward and obviously it will be set
 * to B_TRUE.
 */
boolean_t
ipmgmt_ngz_firstboot_postinstall()
{
	scf_resources_t	res;
	boolean_t	bval = B_TRUE;
	char		*strval;

	/* we always err on the side of caution */
	if (ipmgmt_create_scf_resources(IPMGMTD_FMRI, &res) != 0)
		return (bval);

	if (ipmgmt_get_scfprop(&res, IPMGMTD_APP_PG, IPMGMTD_PROP_FBD, &strval,
	    SCF_TYPE_ASTRING) > 0) {
		bval = (strcmp(strval, IPMGMTD_TRUESTR) == 0 ?
		    B_FALSE : B_TRUE);
	} else {
		/*
		 * IPMGMTD_PROP_FBD does not exist in the SCF. Lets create it.
		 * Since we err on the side of caution, we ignore the return
		 * error and return B_TRUE.
		 */
		(void) ipmgmt_set_scfprop(&res, IPMGMTD_APP_PG,
		    IPMGMTD_PROP_FBD, IPMGMTD_TRUESTR, SCF_TYPE_ASTRING);
	}
	ipmgmt_release_scf_resources(&res);
	return (bval);
}

/*
 * Returns B_TRUE, if the data-store needs upgrade otherwise returns B_FALSE.
 * Today we have to take care of, one case of, upgrading from version 0 to
 * version 1, so we will use boolean_t as means to decide if upgrade is needed
 * or not. Further, the upcoming projects might completely move the flatfile
 * data-store into SCF and hence we shall keep this interface simple.
 */
boolean_t
ipmgmt_needs_upgrade(scf_resources_t *res)
{
	boolean_t	bval = B_TRUE;
	int64_t		*verp;

	if (ipmgmt_get_scfprop(res, IPMGMTD_APP_PG, IPMGMTD_PROP_DBVER,
	    &verp, SCF_TYPE_INTEGER) > 0) {
		if (*verp == IPADM_DB_VERSION)
			bval = B_FALSE;
	}
	/*
	 * 'datastore_version' doesn't exist. Which means that we need to
	 * upgrade the datastore. We will create 'datastore_version' and set
	 * the version value to IPADM_DB_VERSION, after we upgrade the file.
	 */
	return (bval);
}

/*
 * This is called after the successful upgrade of the local data-store. With
 * the data-store upgraded to recent version we don't have to do anything on
 * subsequent reboots.
 */
void
ipmgmt_update_dbver(scf_resources_t *res)
{
	int64_t		version = IPADM_DB_VERSION;

	(void) ipmgmt_set_scfprop(res, IPMGMTD_APP_PG,
	    IPMGMTD_PROP_DBVER, &version, SCF_TYPE_INTEGER);
}

/*
 * Return TRUE if `ifname' has persistent configuration for the `af' address
 * family in the datastore.
 * It is possible to call the function with af == AF_UNSPEC, so in this case
 * the function returns TRUE if either AF_INET or AF_INET6 interface exists
 */
boolean_t
ipmgmt_persist_if_exists(const char *ifname, sa_family_t af)
{
	boolean_t exists = B_FALSE;
	nvlist_t    *if_info_nvl;
	uint16_t    *families = NULL;
	sa_family_t af_db;
	uint_t	nelem = 0;

	if (ipmgmt_get_ifinfo_nvl(ifname, &if_info_nvl) != 0)
		goto done;

	if (nvlist_lookup_uint16_array(if_info_nvl, IPADM_NVP_FAMILIES,
	    &families, &nelem) != 0)
		goto done;

	while (nelem-- > 0) {
		af_db = families[nelem];
		if (af_db == af || (af == AF_UNSPEC &&
		    (af_db == AF_INET || af_db == AF_INET6))) {
			exists = B_TRUE;
			break;
		}
	}

done:
	if (if_info_nvl != NULL)
		nvlist_free(if_info_nvl);

	return (exists);
}

/*
 * Retrieves the membership information for the requested mif_name
 * if mif_name is a member of a IPMP group, then gif_name will contain
 * the name of IPMP group interface, otherwise the variable will be empty
 */
void
ipmgmt_get_group_interface(const char *mif_name, char *gif_name, size_t size)
{
	char	*gif_name_from_nvl;
	nvlist_t	*if_info_nvl;

	gif_name[0] = '\0';

	if (ipmgmt_get_ifinfo_nvl(mif_name, &if_info_nvl) != 0)
		goto done;

	if (nvlist_lookup_string(if_info_nvl, IPADM_NVP_GIFNAME,
	    &gif_name_from_nvl) != 0)
		goto done;

	(void) strlcpy(gif_name, gif_name_from_nvl, size);

done:
	if (if_info_nvl != NULL)
		nvlist_free(if_info_nvl);
}

static int
ipmgmt_get_ifinfo_nvl(const char *ifname, nvlist_t **if_info_nvl)
{
	ipmgmt_get_cbarg_t cbarg;
	nvpair_t    *nvp;
	nvlist_t    *nvl;
	int	err;

	cbarg.cb_ifname = NULL;
	cbarg.cb_aobjname = NULL;
	cbarg.cb_ocnt = 0;

	*if_info_nvl = NULL;

	if ((err = nvlist_alloc(&cbarg.cb_onvl, NV_UNIQUE_NAME, 0)) != 0)
		goto done;

	err = ipmgmt_db_walk(ipmgmt_db_getif, &cbarg, IPADM_DB_READ);
	if (err == ENOENT && cbarg.cb_ocnt > 0)
		err = 0;

	if (err != 0)
		goto done;

	for (nvp = nvlist_next_nvpair(cbarg.cb_onvl, NULL); nvp != NULL;
	    nvp = nvlist_next_nvpair(cbarg.cb_onvl, nvp)) {

		if (strcmp(nvpair_name(nvp), ifname) != 0)
			continue;

		if ((err = nvpair_value_nvlist(nvp, &nvl)) != 0 ||
		    (err = nvlist_dup(nvl, if_info_nvl, NV_UNIQUE_NAME)) != 0)
			*if_info_nvl = NULL;

		break;
	}

done:
	nvlist_free(cbarg.cb_onvl);

	return (err);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * Utility functions used by the ipmgmtd daemon.
 */

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <syslog.h>
#include <stdarg.h>
#include <unistd.h>
#include <errno.h>
#include "ipmgmt_impl.h"

#define	IPMGMT_BUFSIZ	1024

void
ipmgmt_log(int pri, const char *fmt, ...)
{
	va_list alist;

	va_start(alist, fmt);
	vsyslog(pri, fmt, alist);
	va_end(alist);
}

/*
 * Copy a source file to a new destination. The source file will be
 * removed if rdonly is false (i.e., used when the source file resides
 * on a read-only file system).
 *
 * Returns 0 on success and errno on failure.
 */
int
ipmgmt_cpfile(const char *src, const char *dst, boolean_t rdonly)
{
	struct stat statbuf;
	FILE *sfp, *dfp;
	char buf[IPMGMT_BUFSIZ];
	int err = 0;

	errno = 0;
	/*
	 * Attempt to open the destination file first since we
	 * want to optimize for the case where it is read-only
	 * and will return EROFS.
	 */
	if ((dfp = fopen(dst, "w+")) == NULL)
		return (errno);

	/*
	 * Require that the source file exists.
	 */
	if (stat(src, &statbuf) != 0) {
		err = errno;
		(void) fclose(dfp);
		return (err);
	}
	if ((sfp = fopen(src, "r")) == NULL) {
		err = errno;
		(void) fclose(dfp);
		return (err);
	}

	/*
	 * Copy the file.
	 */
	while (fgets(buf, sizeof (buf), sfp) != NULL && errno == 0) {
		(void) fputs(buf, dfp);
		if (errno != 0)
			break;
	}
	if (errno != 0)
		err = errno;
	else if (fflush(dfp) == EOF)
		err = errno;

	(void) fclose(sfp);
	(void) fclose(dfp);

	/*
	 * If any error occurred, then remove the destination file.
	 */
	if (err != 0) {
		(void) unlink(dst);
		return (err);
	}

	/*
	 * Make sure the file attributes are correct.
	 */
	if (chmod(dst, IPADM_FILE_MODE) != 0 ||
	    chown(dst, UID_NETADM, GID_NETADM) != 0) {
		err = errno;
		(void) unlink(dst);
		return (err);
	}

	/*
	 * If the source file does not reside on a read-only file system
	 * then remove it.
	 */
	if (!rdonly)
		(void) unlink(src);

	return (0);
}
#!/sbin/sh
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2012, Joyent, Inc. All rights reserved.
#
# This daemon stores address object to logical interface number mappings
# (among other things) and reads/writes from/to ipmgmtd data store.
#

. /lib/svc/share/smf_include.sh

if [ -z "$SMF_FMRI" ]; then
        echo "this script can only be invoked by smf(7)"
        exit $SMF_EXIT_ERR_NOSMF
fi

#
# network/ip-interface-management:default service is always enabled by default.
# When the non-global shared-IP stack zone boots, it tries to bring up this
# service as well. If we don't start a background process and simply exit the
# service, the service will go into maintenance mode and so will all it's
# dependents.  Ideally we would simply exit with SMF_EXIT_NODAEMON, but since
# this method is also used in an S10C zone, where support for SMF_EXIT_NODAEMON
# does not exist, we have to stick around.
#
# In S10C zone (where this script is also used) smf_isnonglobalzone
# function is unavailable in smf_include.sh
#
if [ `/sbin/zonename` != global ]; then
	if [ `/sbin/zonename -t` = shared ]; then
		(while true ; do sleep 3600 ; done) &
		exit $SMF_EXIT_OK
	fi
fi

#
# We must be now in a global zone or non-global zone with exclusive-IP stack.
# Start the ipmgmtd daemon.
#
if /lib/inet/ipmgmtd ; then
	exit $SMF_EXIT_OK
else
        exit $SMF_EXIT_ERR_FATAL
fi
<?xml version="1.0"?>
<!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">
<!--
 Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
 Use is subject to license terms.

 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

	NOTE:  This service manifest is not editable; its contents will
	be overwritten by package or patch operations, including
	operating system upgrade.  Make customizations in a different
	file.
-->

<service_bundle type='manifest' name='SUNWcsr:ipmgmtd'>

<service
	name='network/ip-interface-management'
	type='service'
	version='1'>

	<create_default_instance enabled='true' />

	<single_instance />

	<dependent name='ipmgmt-loopback'
		grouping='require_all'
		restart_on='none'>
		<service_fmri value='svc:/network/loopback' />
	</dependent>

        <dependent name='ipmgmt-physical'
                grouping='require_all'
                restart_on='none'>
                <service_fmri value='svc:/network/physical' />
        </dependent>

        <dependent name='ipmgmt-iptun'
                grouping='require_all'
                restart_on='none'>
                <service_fmri value='svc:/network/iptun' />
        </dependent>

	<exec_method
		type='method'
		name='start'
		exec='/lib/svc/method/net-ipmgmt'
		timeout_seconds='60' />

	<exec_method
		type='method'
		name='stop'
		exec=':kill'
		timeout_seconds='5' />

	<stability value='Unstable' />

	<template>
		<common_name>
			<loctext xml:lang='C'>
				IP interface management
			</loctext>
		</common_name>
		<description>
			<loctext xml:lang='C'>
				Create IP interfaces, apply
				TCP/IP properties and manage
				address object mappings.
			</loctext>
		</description>
		<documentation>
			<manpage title='ipadm' section='8'
				manpath='/usr/share/man' />
		</documentation>
	</template>
</service>

</service_bundle>