|
root / base / usr / src / cmd / cmd-inet / lib / nwamd
nwamd Plain Text 15518 lines 445.5 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
 4197
 4198
 4199
 4200
 4201
 4202
 4203
 4204
 4205
 4206
 4207
 4208
 4209
 4210
 4211
 4212
 4213
 4214
 4215
 4216
 4217
 4218
 4219
 4220
 4221
 4222
 4223
 4224
 4225
 4226
 4227
 4228
 4229
 4230
 4231
 4232
 4233
 4234
 4235
 4236
 4237
 4238
 4239
 4240
 4241
 4242
 4243
 4244
 4245
 4246
 4247
 4248
 4249
 4250
 4251
 4252
 4253
 4254
 4255
 4256
 4257
 4258
 4259
 4260
 4261
 4262
 4263
 4264
 4265
 4266
 4267
 4268
 4269
 4270
 4271
 4272
 4273
 4274
 4275
 4276
 4277
 4278
 4279
 4280
 4281
 4282
 4283
 4284
 4285
 4286
 4287
 4288
 4289
 4290
 4291
 4292
 4293
 4294
 4295
 4296
 4297
 4298
 4299
 4300
 4301
 4302
 4303
 4304
 4305
 4306
 4307
 4308
 4309
 4310
 4311
 4312
 4313
 4314
 4315
 4316
 4317
 4318
 4319
 4320
 4321
 4322
 4323
 4324
 4325
 4326
 4327
 4328
 4329
 4330
 4331
 4332
 4333
 4334
 4335
 4336
 4337
 4338
 4339
 4340
 4341
 4342
 4343
 4344
 4345
 4346
 4347
 4348
 4349
 4350
 4351
 4352
 4353
 4354
 4355
 4356
 4357
 4358
 4359
 4360
 4361
 4362
 4363
 4364
 4365
 4366
 4367
 4368
 4369
 4370
 4371
 4372
 4373
 4374
 4375
 4376
 4377
 4378
 4379
 4380
 4381
 4382
 4383
 4384
 4385
 4386
 4387
 4388
 4389
 4390
 4391
 4392
 4393
 4394
 4395
 4396
 4397
 4398
 4399
 4400
 4401
 4402
 4403
 4404
 4405
 4406
 4407
 4408
 4409
 4410
 4411
 4412
 4413
 4414
 4415
 4416
 4417
 4418
 4419
 4420
 4421
 4422
 4423
 4424
 4425
 4426
 4427
 4428
 4429
 4430
 4431
 4432
 4433
 4434
 4435
 4436
 4437
 4438
 4439
 4440
 4441
 4442
 4443
 4444
 4445
 4446
 4447
 4448
 4449
 4450
 4451
 4452
 4453
 4454
 4455
 4456
 4457
 4458
 4459
 4460
 4461
 4462
 4463
 4464
 4465
 4466
 4467
 4468
 4469
 4470
 4471
 4472
 4473
 4474
 4475
 4476
 4477
 4478
 4479
 4480
 4481
 4482
 4483
 4484
 4485
 4486
 4487
 4488
 4489
 4490
 4491
 4492
 4493
 4494
 4495
 4496
 4497
 4498
 4499
 4500
 4501
 4502
 4503
 4504
 4505
 4506
 4507
 4508
 4509
 4510
 4511
 4512
 4513
 4514
 4515
 4516
 4517
 4518
 4519
 4520
 4521
 4522
 4523
 4524
 4525
 4526
 4527
 4528
 4529
 4530
 4531
 4532
 4533
 4534
 4535
 4536
 4537
 4538
 4539
 4540
 4541
 4542
 4543
 4544
 4545
 4546
 4547
 4548
 4549
 4550
 4551
 4552
 4553
 4554
 4555
 4556
 4557
 4558
 4559
 4560
 4561
 4562
 4563
 4564
 4565
 4566
 4567
 4568
 4569
 4570
 4571
 4572
 4573
 4574
 4575
 4576
 4577
 4578
 4579
 4580
 4581
 4582
 4583
 4584
 4585
 4586
 4587
 4588
 4589
 4590
 4591
 4592
 4593
 4594
 4595
 4596
 4597
 4598
 4599
 4600
 4601
 4602
 4603
 4604
 4605
 4606
 4607
 4608
 4609
 4610
 4611
 4612
 4613
 4614
 4615
 4616
 4617
 4618
 4619
 4620
 4621
 4622
 4623
 4624
 4625
 4626
 4627
 4628
 4629
 4630
 4631
 4632
 4633
 4634
 4635
 4636
 4637
 4638
 4639
 4640
 4641
 4642
 4643
 4644
 4645
 4646
 4647
 4648
 4649
 4650
 4651
 4652
 4653
 4654
 4655
 4656
 4657
 4658
 4659
 4660
 4661
 4662
 4663
 4664
 4665
 4666
 4667
 4668
 4669
 4670
 4671
 4672
 4673
 4674
 4675
 4676
 4677
 4678
 4679
 4680
 4681
 4682
 4683
 4684
 4685
 4686
 4687
 4688
 4689
 4690
 4691
 4692
 4693
 4694
 4695
 4696
 4697
 4698
 4699
 4700
 4701
 4702
 4703
 4704
 4705
 4706
 4707
 4708
 4709
 4710
 4711
 4712
 4713
 4714
 4715
 4716
 4717
 4718
 4719
 4720
 4721
 4722
 4723
 4724
 4725
 4726
 4727
 4728
 4729
 4730
 4731
 4732
 4733
 4734
 4735
 4736
 4737
 4738
 4739
 4740
 4741
 4742
 4743
 4744
 4745
 4746
 4747
 4748
 4749
 4750
 4751
 4752
 4753
 4754
 4755
 4756
 4757
 4758
 4759
 4760
 4761
 4762
 4763
 4764
 4765
 4766
 4767
 4768
 4769
 4770
 4771
 4772
 4773
 4774
 4775
 4776
 4777
 4778
 4779
 4780
 4781
 4782
 4783
 4784
 4785
 4786
 4787
 4788
 4789
 4790
 4791
 4792
 4793
 4794
 4795
 4796
 4797
 4798
 4799
 4800
 4801
 4802
 4803
 4804
 4805
 4806
 4807
 4808
 4809
 4810
 4811
 4812
 4813
 4814
 4815
 4816
 4817
 4818
 4819
 4820
 4821
 4822
 4823
 4824
 4825
 4826
 4827
 4828
 4829
 4830
 4831
 4832
 4833
 4834
 4835
 4836
 4837
 4838
 4839
 4840
 4841
 4842
 4843
 4844
 4845
 4846
 4847
 4848
 4849
 4850
 4851
 4852
 4853
 4854
 4855
 4856
 4857
 4858
 4859
 4860
 4861
 4862
 4863
 4864
 4865
 4866
 4867
 4868
 4869
 4870
 4871
 4872
 4873
 4874
 4875
 4876
 4877
 4878
 4879
 4880
 4881
 4882
 4883
 4884
 4885
 4886
 4887
 4888
 4889
 4890
 4891
 4892
 4893
 4894
 4895
 4896
 4897
 4898
 4899
 4900
 4901
 4902
 4903
 4904
 4905
 4906
 4907
 4908
 4909
 4910
 4911
 4912
 4913
 4914
 4915
 4916
 4917
 4918
 4919
 4920
 4921
 4922
 4923
 4924
 4925
 4926
 4927
 4928
 4929
 4930
 4931
 4932
 4933
 4934
 4935
 4936
 4937
 4938
 4939
 4940
 4941
 4942
 4943
 4944
 4945
 4946
 4947
 4948
 4949
 4950
 4951
 4952
 4953
 4954
 4955
 4956
 4957
 4958
 4959
 4960
 4961
 4962
 4963
 4964
 4965
 4966
 4967
 4968
 4969
 4970
 4971
 4972
 4973
 4974
 4975
 4976
 4977
 4978
 4979
 4980
 4981
 4982
 4983
 4984
 4985
 4986
 4987
 4988
 4989
 4990
 4991
 4992
 4993
 4994
 4995
 4996
 4997
 4998
 4999
 5000
 5001
 5002
 5003
 5004
 5005
 5006
 5007
 5008
 5009
 5010
 5011
 5012
 5013
 5014
 5015
 5016
 5017
 5018
 5019
 5020
 5021
 5022
 5023
 5024
 5025
 5026
 5027
 5028
 5029
 5030
 5031
 5032
 5033
 5034
 5035
 5036
 5037
 5038
 5039
 5040
 5041
 5042
 5043
 5044
 5045
 5046
 5047
 5048
 5049
 5050
 5051
 5052
 5053
 5054
 5055
 5056
 5057
 5058
 5059
 5060
 5061
 5062
 5063
 5064
 5065
 5066
 5067
 5068
 5069
 5070
 5071
 5072
 5073
 5074
 5075
 5076
 5077
 5078
 5079
 5080
 5081
 5082
 5083
 5084
 5085
 5086
 5087
 5088
 5089
 5090
 5091
 5092
 5093
 5094
 5095
 5096
 5097
 5098
 5099
 5100
 5101
 5102
 5103
 5104
 5105
 5106
 5107
 5108
 5109
 5110
 5111
 5112
 5113
 5114
 5115
 5116
 5117
 5118
 5119
 5120
 5121
 5122
 5123
 5124
 5125
 5126
 5127
 5128
 5129
 5130
 5131
 5132
 5133
 5134
 5135
 5136
 5137
 5138
 5139
 5140
 5141
 5142
 5143
 5144
 5145
 5146
 5147
 5148
 5149
 5150
 5151
 5152
 5153
 5154
 5155
 5156
 5157
 5158
 5159
 5160
 5161
 5162
 5163
 5164
 5165
 5166
 5167
 5168
 5169
 5170
 5171
 5172
 5173
 5174
 5175
 5176
 5177
 5178
 5179
 5180
 5181
 5182
 5183
 5184
 5185
 5186
 5187
 5188
 5189
 5190
 5191
 5192
 5193
 5194
 5195
 5196
 5197
 5198
 5199
 5200
 5201
 5202
 5203
 5204
 5205
 5206
 5207
 5208
 5209
 5210
 5211
 5212
 5213
 5214
 5215
 5216
 5217
 5218
 5219
 5220
 5221
 5222
 5223
 5224
 5225
 5226
 5227
 5228
 5229
 5230
 5231
 5232
 5233
 5234
 5235
 5236
 5237
 5238
 5239
 5240
 5241
 5242
 5243
 5244
 5245
 5246
 5247
 5248
 5249
 5250
 5251
 5252
 5253
 5254
 5255
 5256
 5257
 5258
 5259
 5260
 5261
 5262
 5263
 5264
 5265
 5266
 5267
 5268
 5269
 5270
 5271
 5272
 5273
 5274
 5275
 5276
 5277
 5278
 5279
 5280
 5281
 5282
 5283
 5284
 5285
 5286
 5287
 5288
 5289
 5290
 5291
 5292
 5293
 5294
 5295
 5296
 5297
 5298
 5299
 5300
 5301
 5302
 5303
 5304
 5305
 5306
 5307
 5308
 5309
 5310
 5311
 5312
 5313
 5314
 5315
 5316
 5317
 5318
 5319
 5320
 5321
 5322
 5323
 5324
 5325
 5326
 5327
 5328
 5329
 5330
 5331
 5332
 5333
 5334
 5335
 5336
 5337
 5338
 5339
 5340
 5341
 5342
 5343
 5344
 5345
 5346
 5347
 5348
 5349
 5350
 5351
 5352
 5353
 5354
 5355
 5356
 5357
 5358
 5359
 5360
 5361
 5362
 5363
 5364
 5365
 5366
 5367
 5368
 5369
 5370
 5371
 5372
 5373
 5374
 5375
 5376
 5377
 5378
 5379
 5380
 5381
 5382
 5383
 5384
 5385
 5386
 5387
 5388
 5389
 5390
 5391
 5392
 5393
 5394
 5395
 5396
 5397
 5398
 5399
 5400
 5401
 5402
 5403
 5404
 5405
 5406
 5407
 5408
 5409
 5410
 5411
 5412
 5413
 5414
 5415
 5416
 5417
 5418
 5419
 5420
 5421
 5422
 5423
 5424
 5425
 5426
 5427
 5428
 5429
 5430
 5431
 5432
 5433
 5434
 5435
 5436
 5437
 5438
 5439
 5440
 5441
 5442
 5443
 5444
 5445
 5446
 5447
 5448
 5449
 5450
 5451
 5452
 5453
 5454
 5455
 5456
 5457
 5458
 5459
 5460
 5461
 5462
 5463
 5464
 5465
 5466
 5467
 5468
 5469
 5470
 5471
 5472
 5473
 5474
 5475
 5476
 5477
 5478
 5479
 5480
 5481
 5482
 5483
 5484
 5485
 5486
 5487
 5488
 5489
 5490
 5491
 5492
 5493
 5494
 5495
 5496
 5497
 5498
 5499
 5500
 5501
 5502
 5503
 5504
 5505
 5506
 5507
 5508
 5509
 5510
 5511
 5512
 5513
 5514
 5515
 5516
 5517
 5518
 5519
 5520
 5521
 5522
 5523
 5524
 5525
 5526
 5527
 5528
 5529
 5530
 5531
 5532
 5533
 5534
 5535
 5536
 5537
 5538
 5539
 5540
 5541
 5542
 5543
 5544
 5545
 5546
 5547
 5548
 5549
 5550
 5551
 5552
 5553
 5554
 5555
 5556
 5557
 5558
 5559
 5560
 5561
 5562
 5563
 5564
 5565
 5566
 5567
 5568
 5569
 5570
 5571
 5572
 5573
 5574
 5575
 5576
 5577
 5578
 5579
 5580
 5581
 5582
 5583
 5584
 5585
 5586
 5587
 5588
 5589
 5590
 5591
 5592
 5593
 5594
 5595
 5596
 5597
 5598
 5599
 5600
 5601
 5602
 5603
 5604
 5605
 5606
 5607
 5608
 5609
 5610
 5611
 5612
 5613
 5614
 5615
 5616
 5617
 5618
 5619
 5620
 5621
 5622
 5623
 5624
 5625
 5626
 5627
 5628
 5629
 5630
 5631
 5632
 5633
 5634
 5635
 5636
 5637
 5638
 5639
 5640
 5641
 5642
 5643
 5644
 5645
 5646
 5647
 5648
 5649
 5650
 5651
 5652
 5653
 5654
 5655
 5656
 5657
 5658
 5659
 5660
 5661
 5662
 5663
 5664
 5665
 5666
 5667
 5668
 5669
 5670
 5671
 5672
 5673
 5674
 5675
 5676
 5677
 5678
 5679
 5680
 5681
 5682
 5683
 5684
 5685
 5686
 5687
 5688
 5689
 5690
 5691
 5692
 5693
 5694
 5695
 5696
 5697
 5698
 5699
 5700
 5701
 5702
 5703
 5704
 5705
 5706
 5707
 5708
 5709
 5710
 5711
 5712
 5713
 5714
 5715
 5716
 5717
 5718
 5719
 5720
 5721
 5722
 5723
 5724
 5725
 5726
 5727
 5728
 5729
 5730
 5731
 5732
 5733
 5734
 5735
 5736
 5737
 5738
 5739
 5740
 5741
 5742
 5743
 5744
 5745
 5746
 5747
 5748
 5749
 5750
 5751
 5752
 5753
 5754
 5755
 5756
 5757
 5758
 5759
 5760
 5761
 5762
 5763
 5764
 5765
 5766
 5767
 5768
 5769
 5770
 5771
 5772
 5773
 5774
 5775
 5776
 5777
 5778
 5779
 5780
 5781
 5782
 5783
 5784
 5785
 5786
 5787
 5788
 5789
 5790
 5791
 5792
 5793
 5794
 5795
 5796
 5797
 5798
 5799
 5800
 5801
 5802
 5803
 5804
 5805
 5806
 5807
 5808
 5809
 5810
 5811
 5812
 5813
 5814
 5815
 5816
 5817
 5818
 5819
 5820
 5821
 5822
 5823
 5824
 5825
 5826
 5827
 5828
 5829
 5830
 5831
 5832
 5833
 5834
 5835
 5836
 5837
 5838
 5839
 5840
 5841
 5842
 5843
 5844
 5845
 5846
 5847
 5848
 5849
 5850
 5851
 5852
 5853
 5854
 5855
 5856
 5857
 5858
 5859
 5860
 5861
 5862
 5863
 5864
 5865
 5866
 5867
 5868
 5869
 5870
 5871
 5872
 5873
 5874
 5875
 5876
 5877
 5878
 5879
 5880
 5881
 5882
 5883
 5884
 5885
 5886
 5887
 5888
 5889
 5890
 5891
 5892
 5893
 5894
 5895
 5896
 5897
 5898
 5899
 5900
 5901
 5902
 5903
 5904
 5905
 5906
 5907
 5908
 5909
 5910
 5911
 5912
 5913
 5914
 5915
 5916
 5917
 5918
 5919
 5920
 5921
 5922
 5923
 5924
 5925
 5926
 5927
 5928
 5929
 5930
 5931
 5932
 5933
 5934
 5935
 5936
 5937
 5938
 5939
 5940
 5941
 5942
 5943
 5944
 5945
 5946
 5947
 5948
 5949
 5950
 5951
 5952
 5953
 5954
 5955
 5956
 5957
 5958
 5959
 5960
 5961
 5962
 5963
 5964
 5965
 5966
 5967
 5968
 5969
 5970
 5971
 5972
 5973
 5974
 5975
 5976
 5977
 5978
 5979
 5980
 5981
 5982
 5983
 5984
 5985
 5986
 5987
 5988
 5989
 5990
 5991
 5992
 5993
 5994
 5995
 5996
 5997
 5998
 5999
 6000
 6001
 6002
 6003
 6004
 6005
 6006
 6007
 6008
 6009
 6010
 6011
 6012
 6013
 6014
 6015
 6016
 6017
 6018
 6019
 6020
 6021
 6022
 6023
 6024
 6025
 6026
 6027
 6028
 6029
 6030
 6031
 6032
 6033
 6034
 6035
 6036
 6037
 6038
 6039
 6040
 6041
 6042
 6043
 6044
 6045
 6046
 6047
 6048
 6049
 6050
 6051
 6052
 6053
 6054
 6055
 6056
 6057
 6058
 6059
 6060
 6061
 6062
 6063
 6064
 6065
 6066
 6067
 6068
 6069
 6070
 6071
 6072
 6073
 6074
 6075
 6076
 6077
 6078
 6079
 6080
 6081
 6082
 6083
 6084
 6085
 6086
 6087
 6088
 6089
 6090
 6091
 6092
 6093
 6094
 6095
 6096
 6097
 6098
 6099
 6100
 6101
 6102
 6103
 6104
 6105
 6106
 6107
 6108
 6109
 6110
 6111
 6112
 6113
 6114
 6115
 6116
 6117
 6118
 6119
 6120
 6121
 6122
 6123
 6124
 6125
 6126
 6127
 6128
 6129
 6130
 6131
 6132
 6133
 6134
 6135
 6136
 6137
 6138
 6139
 6140
 6141
 6142
 6143
 6144
 6145
 6146
 6147
 6148
 6149
 6150
 6151
 6152
 6153
 6154
 6155
 6156
 6157
 6158
 6159
 6160
 6161
 6162
 6163
 6164
 6165
 6166
 6167
 6168
 6169
 6170
 6171
 6172
 6173
 6174
 6175
 6176
 6177
 6178
 6179
 6180
 6181
 6182
 6183
 6184
 6185
 6186
 6187
 6188
 6189
 6190
 6191
 6192
 6193
 6194
 6195
 6196
 6197
 6198
 6199
 6200
 6201
 6202
 6203
 6204
 6205
 6206
 6207
 6208
 6209
 6210
 6211
 6212
 6213
 6214
 6215
 6216
 6217
 6218
 6219
 6220
 6221
 6222
 6223
 6224
 6225
 6226
 6227
 6228
 6229
 6230
 6231
 6232
 6233
 6234
 6235
 6236
 6237
 6238
 6239
 6240
 6241
 6242
 6243
 6244
 6245
 6246
 6247
 6248
 6249
 6250
 6251
 6252
 6253
 6254
 6255
 6256
 6257
 6258
 6259
 6260
 6261
 6262
 6263
 6264
 6265
 6266
 6267
 6268
 6269
 6270
 6271
 6272
 6273
 6274
 6275
 6276
 6277
 6278
 6279
 6280
 6281
 6282
 6283
 6284
 6285
 6286
 6287
 6288
 6289
 6290
 6291
 6292
 6293
 6294
 6295
 6296
 6297
 6298
 6299
 6300
 6301
 6302
 6303
 6304
 6305
 6306
 6307
 6308
 6309
 6310
 6311
 6312
 6313
 6314
 6315
 6316
 6317
 6318
 6319
 6320
 6321
 6322
 6323
 6324
 6325
 6326
 6327
 6328
 6329
 6330
 6331
 6332
 6333
 6334
 6335
 6336
 6337
 6338
 6339
 6340
 6341
 6342
 6343
 6344
 6345
 6346
 6347
 6348
 6349
 6350
 6351
 6352
 6353
 6354
 6355
 6356
 6357
 6358
 6359
 6360
 6361
 6362
 6363
 6364
 6365
 6366
 6367
 6368
 6369
 6370
 6371
 6372
 6373
 6374
 6375
 6376
 6377
 6378
 6379
 6380
 6381
 6382
 6383
 6384
 6385
 6386
 6387
 6388
 6389
 6390
 6391
 6392
 6393
 6394
 6395
 6396
 6397
 6398
 6399
 6400
 6401
 6402
 6403
 6404
 6405
 6406
 6407
 6408
 6409
 6410
 6411
 6412
 6413
 6414
 6415
 6416
 6417
 6418
 6419
 6420
 6421
 6422
 6423
 6424
 6425
 6426
 6427
 6428
 6429
 6430
 6431
 6432
 6433
 6434
 6435
 6436
 6437
 6438
 6439
 6440
 6441
 6442
 6443
 6444
 6445
 6446
 6447
 6448
 6449
 6450
 6451
 6452
 6453
 6454
 6455
 6456
 6457
 6458
 6459
 6460
 6461
 6462
 6463
 6464
 6465
 6466
 6467
 6468
 6469
 6470
 6471
 6472
 6473
 6474
 6475
 6476
 6477
 6478
 6479
 6480
 6481
 6482
 6483
 6484
 6485
 6486
 6487
 6488
 6489
 6490
 6491
 6492
 6493
 6494
 6495
 6496
 6497
 6498
 6499
 6500
 6501
 6502
 6503
 6504
 6505
 6506
 6507
 6508
 6509
 6510
 6511
 6512
 6513
 6514
 6515
 6516
 6517
 6518
 6519
 6520
 6521
 6522
 6523
 6524
 6525
 6526
 6527
 6528
 6529
 6530
 6531
 6532
 6533
 6534
 6535
 6536
 6537
 6538
 6539
 6540
 6541
 6542
 6543
 6544
 6545
 6546
 6547
 6548
 6549
 6550
 6551
 6552
 6553
 6554
 6555
 6556
 6557
 6558
 6559
 6560
 6561
 6562
 6563
 6564
 6565
 6566
 6567
 6568
 6569
 6570
 6571
 6572
 6573
 6574
 6575
 6576
 6577
 6578
 6579
 6580
 6581
 6582
 6583
 6584
 6585
 6586
 6587
 6588
 6589
 6590
 6591
 6592
 6593
 6594
 6595
 6596
 6597
 6598
 6599
 6600
 6601
 6602
 6603
 6604
 6605
 6606
 6607
 6608
 6609
 6610
 6611
 6612
 6613
 6614
 6615
 6616
 6617
 6618
 6619
 6620
 6621
 6622
 6623
 6624
 6625
 6626
 6627
 6628
 6629
 6630
 6631
 6632
 6633
 6634
 6635
 6636
 6637
 6638
 6639
 6640
 6641
 6642
 6643
 6644
 6645
 6646
 6647
 6648
 6649
 6650
 6651
 6652
 6653
 6654
 6655
 6656
 6657
 6658
 6659
 6660
 6661
 6662
 6663
 6664
 6665
 6666
 6667
 6668
 6669
 6670
 6671
 6672
 6673
 6674
 6675
 6676
 6677
 6678
 6679
 6680
 6681
 6682
 6683
 6684
 6685
 6686
 6687
 6688
 6689
 6690
 6691
 6692
 6693
 6694
 6695
 6696
 6697
 6698
 6699
 6700
 6701
 6702
 6703
 6704
 6705
 6706
 6707
 6708
 6709
 6710
 6711
 6712
 6713
 6714
 6715
 6716
 6717
 6718
 6719
 6720
 6721
 6722
 6723
 6724
 6725
 6726
 6727
 6728
 6729
 6730
 6731
 6732
 6733
 6734
 6735
 6736
 6737
 6738
 6739
 6740
 6741
 6742
 6743
 6744
 6745
 6746
 6747
 6748
 6749
 6750
 6751
 6752
 6753
 6754
 6755
 6756
 6757
 6758
 6759
 6760
 6761
 6762
 6763
 6764
 6765
 6766
 6767
 6768
 6769
 6770
 6771
 6772
 6773
 6774
 6775
 6776
 6777
 6778
 6779
 6780
 6781
 6782
 6783
 6784
 6785
 6786
 6787
 6788
 6789
 6790
 6791
 6792
 6793
 6794
 6795
 6796
 6797
 6798
 6799
 6800
 6801
 6802
 6803
 6804
 6805
 6806
 6807
 6808
 6809
 6810
 6811
 6812
 6813
 6814
 6815
 6816
 6817
 6818
 6819
 6820
 6821
 6822
 6823
 6824
 6825
 6826
 6827
 6828
 6829
 6830
 6831
 6832
 6833
 6834
 6835
 6836
 6837
 6838
 6839
 6840
 6841
 6842
 6843
 6844
 6845
 6846
 6847
 6848
 6849
 6850
 6851
 6852
 6853
 6854
 6855
 6856
 6857
 6858
 6859
 6860
 6861
 6862
 6863
 6864
 6865
 6866
 6867
 6868
 6869
 6870
 6871
 6872
 6873
 6874
 6875
 6876
 6877
 6878
 6879
 6880
 6881
 6882
 6883
 6884
 6885
 6886
 6887
 6888
 6889
 6890
 6891
 6892
 6893
 6894
 6895
 6896
 6897
 6898
 6899
 6900
 6901
 6902
 6903
 6904
 6905
 6906
 6907
 6908
 6909
 6910
 6911
 6912
 6913
 6914
 6915
 6916
 6917
 6918
 6919
 6920
 6921
 6922
 6923
 6924
 6925
 6926
 6927
 6928
 6929
 6930
 6931
 6932
 6933
 6934
 6935
 6936
 6937
 6938
 6939
 6940
 6941
 6942
 6943
 6944
 6945
 6946
 6947
 6948
 6949
 6950
 6951
 6952
 6953
 6954
 6955
 6956
 6957
 6958
 6959
 6960
 6961
 6962
 6963
 6964
 6965
 6966
 6967
 6968
 6969
 6970
 6971
 6972
 6973
 6974
 6975
 6976
 6977
 6978
 6979
 6980
 6981
 6982
 6983
 6984
 6985
 6986
 6987
 6988
 6989
 6990
 6991
 6992
 6993
 6994
 6995
 6996
 6997
 6998
 6999
 7000
 7001
 7002
 7003
 7004
 7005
 7006
 7007
 7008
 7009
 7010
 7011
 7012
 7013
 7014
 7015
 7016
 7017
 7018
 7019
 7020
 7021
 7022
 7023
 7024
 7025
 7026
 7027
 7028
 7029
 7030
 7031
 7032
 7033
 7034
 7035
 7036
 7037
 7038
 7039
 7040
 7041
 7042
 7043
 7044
 7045
 7046
 7047
 7048
 7049
 7050
 7051
 7052
 7053
 7054
 7055
 7056
 7057
 7058
 7059
 7060
 7061
 7062
 7063
 7064
 7065
 7066
 7067
 7068
 7069
 7070
 7071
 7072
 7073
 7074
 7075
 7076
 7077
 7078
 7079
 7080
 7081
 7082
 7083
 7084
 7085
 7086
 7087
 7088
 7089
 7090
 7091
 7092
 7093
 7094
 7095
 7096
 7097
 7098
 7099
 7100
 7101
 7102
 7103
 7104
 7105
 7106
 7107
 7108
 7109
 7110
 7111
 7112
 7113
 7114
 7115
 7116
 7117
 7118
 7119
 7120
 7121
 7122
 7123
 7124
 7125
 7126
 7127
 7128
 7129
 7130
 7131
 7132
 7133
 7134
 7135
 7136
 7137
 7138
 7139
 7140
 7141
 7142
 7143
 7144
 7145
 7146
 7147
 7148
 7149
 7150
 7151
 7152
 7153
 7154
 7155
 7156
 7157
 7158
 7159
 7160
 7161
 7162
 7163
 7164
 7165
 7166
 7167
 7168
 7169
 7170
 7171
 7172
 7173
 7174
 7175
 7176
 7177
 7178
 7179
 7180
 7181
 7182
 7183
 7184
 7185
 7186
 7187
 7188
 7189
 7190
 7191
 7192
 7193
 7194
 7195
 7196
 7197
 7198
 7199
 7200
 7201
 7202
 7203
 7204
 7205
 7206
 7207
 7208
 7209
 7210
 7211
 7212
 7213
 7214
 7215
 7216
 7217
 7218
 7219
 7220
 7221
 7222
 7223
 7224
 7225
 7226
 7227
 7228
 7229
 7230
 7231
 7232
 7233
 7234
 7235
 7236
 7237
 7238
 7239
 7240
 7241
 7242
 7243
 7244
 7245
 7246
 7247
 7248
 7249
 7250
 7251
 7252
 7253
 7254
 7255
 7256
 7257
 7258
 7259
 7260
 7261
 7262
 7263
 7264
 7265
 7266
 7267
 7268
 7269
 7270
 7271
 7272
 7273
 7274
 7275
 7276
 7277
 7278
 7279
 7280
 7281
 7282
 7283
 7284
 7285
 7286
 7287
 7288
 7289
 7290
 7291
 7292
 7293
 7294
 7295
 7296
 7297
 7298
 7299
 7300
 7301
 7302
 7303
 7304
 7305
 7306
 7307
 7308
 7309
 7310
 7311
 7312
 7313
 7314
 7315
 7316
 7317
 7318
 7319
 7320
 7321
 7322
 7323
 7324
 7325
 7326
 7327
 7328
 7329
 7330
 7331
 7332
 7333
 7334
 7335
 7336
 7337
 7338
 7339
 7340
 7341
 7342
 7343
 7344
 7345
 7346
 7347
 7348
 7349
 7350
 7351
 7352
 7353
 7354
 7355
 7356
 7357
 7358
 7359
 7360
 7361
 7362
 7363
 7364
 7365
 7366
 7367
 7368
 7369
 7370
 7371
 7372
 7373
 7374
 7375
 7376
 7377
 7378
 7379
 7380
 7381
 7382
 7383
 7384
 7385
 7386
 7387
 7388
 7389
 7390
 7391
 7392
 7393
 7394
 7395
 7396
 7397
 7398
 7399
 7400
 7401
 7402
 7403
 7404
 7405
 7406
 7407
 7408
 7409
 7410
 7411
 7412
 7413
 7414
 7415
 7416
 7417
 7418
 7419
 7420
 7421
 7422
 7423
 7424
 7425
 7426
 7427
 7428
 7429
 7430
 7431
 7432
 7433
 7434
 7435
 7436
 7437
 7438
 7439
 7440
 7441
 7442
 7443
 7444
 7445
 7446
 7447
 7448
 7449
 7450
 7451
 7452
 7453
 7454
 7455
 7456
 7457
 7458
 7459
 7460
 7461
 7462
 7463
 7464
 7465
 7466
 7467
 7468
 7469
 7470
 7471
 7472
 7473
 7474
 7475
 7476
 7477
 7478
 7479
 7480
 7481
 7482
 7483
 7484
 7485
 7486
 7487
 7488
 7489
 7490
 7491
 7492
 7493
 7494
 7495
 7496
 7497
 7498
 7499
 7500
 7501
 7502
 7503
 7504
 7505
 7506
 7507
 7508
 7509
 7510
 7511
 7512
 7513
 7514
 7515
 7516
 7517
 7518
 7519
 7520
 7521
 7522
 7523
 7524
 7525
 7526
 7527
 7528
 7529
 7530
 7531
 7532
 7533
 7534
 7535
 7536
 7537
 7538
 7539
 7540
 7541
 7542
 7543
 7544
 7545
 7546
 7547
 7548
 7549
 7550
 7551
 7552
 7553
 7554
 7555
 7556
 7557
 7558
 7559
 7560
 7561
 7562
 7563
 7564
 7565
 7566
 7567
 7568
 7569
 7570
 7571
 7572
 7573
 7574
 7575
 7576
 7577
 7578
 7579
 7580
 7581
 7582
 7583
 7584
 7585
 7586
 7587
 7588
 7589
 7590
 7591
 7592
 7593
 7594
 7595
 7596
 7597
 7598
 7599
 7600
 7601
 7602
 7603
 7604
 7605
 7606
 7607
 7608
 7609
 7610
 7611
 7612
 7613
 7614
 7615
 7616
 7617
 7618
 7619
 7620
 7621
 7622
 7623
 7624
 7625
 7626
 7627
 7628
 7629
 7630
 7631
 7632
 7633
 7634
 7635
 7636
 7637
 7638
 7639
 7640
 7641
 7642
 7643
 7644
 7645
 7646
 7647
 7648
 7649
 7650
 7651
 7652
 7653
 7654
 7655
 7656
 7657
 7658
 7659
 7660
 7661
 7662
 7663
 7664
 7665
 7666
 7667
 7668
 7669
 7670
 7671
 7672
 7673
 7674
 7675
 7676
 7677
 7678
 7679
 7680
 7681
 7682
 7683
 7684
 7685
 7686
 7687
 7688
 7689
 7690
 7691
 7692
 7693
 7694
 7695
 7696
 7697
 7698
 7699
 7700
 7701
 7702
 7703
 7704
 7705
 7706
 7707
 7708
 7709
 7710
 7711
 7712
 7713
 7714
 7715
 7716
 7717
 7718
 7719
 7720
 7721
 7722
 7723
 7724
 7725
 7726
 7727
 7728
 7729
 7730
 7731
 7732
 7733
 7734
 7735
 7736
 7737
 7738
 7739
 7740
 7741
 7742
 7743
 7744
 7745
 7746
 7747
 7748
 7749
 7750
 7751
 7752
 7753
 7754
 7755
 7756
 7757
 7758
 7759
 7760
 7761
 7762
 7763
 7764
 7765
 7766
 7767
 7768
 7769
 7770
 7771
 7772
 7773
 7774
 7775
 7776
 7777
 7778
 7779
 7780
 7781
 7782
 7783
 7784
 7785
 7786
 7787
 7788
 7789
 7790
 7791
 7792
 7793
 7794
 7795
 7796
 7797
 7798
 7799
 7800
 7801
 7802
 7803
 7804
 7805
 7806
 7807
 7808
 7809
 7810
 7811
 7812
 7813
 7814
 7815
 7816
 7817
 7818
 7819
 7820
 7821
 7822
 7823
 7824
 7825
 7826
 7827
 7828
 7829
 7830
 7831
 7832
 7833
 7834
 7835
 7836
 7837
 7838
 7839
 7840
 7841
 7842
 7843
 7844
 7845
 7846
 7847
 7848
 7849
 7850
 7851
 7852
 7853
 7854
 7855
 7856
 7857
 7858
 7859
 7860
 7861
 7862
 7863
 7864
 7865
 7866
 7867
 7868
 7869
 7870
 7871
 7872
 7873
 7874
 7875
 7876
 7877
 7878
 7879
 7880
 7881
 7882
 7883
 7884
 7885
 7886
 7887
 7888
 7889
 7890
 7891
 7892
 7893
 7894
 7895
 7896
 7897
 7898
 7899
 7900
 7901
 7902
 7903
 7904
 7905
 7906
 7907
 7908
 7909
 7910
 7911
 7912
 7913
 7914
 7915
 7916
 7917
 7918
 7919
 7920
 7921
 7922
 7923
 7924
 7925
 7926
 7927
 7928
 7929
 7930
 7931
 7932
 7933
 7934
 7935
 7936
 7937
 7938
 7939
 7940
 7941
 7942
 7943
 7944
 7945
 7946
 7947
 7948
 7949
 7950
 7951
 7952
 7953
 7954
 7955
 7956
 7957
 7958
 7959
 7960
 7961
 7962
 7963
 7964
 7965
 7966
 7967
 7968
 7969
 7970
 7971
 7972
 7973
 7974
 7975
 7976
 7977
 7978
 7979
 7980
 7981
 7982
 7983
 7984
 7985
 7986
 7987
 7988
 7989
 7990
 7991
 7992
 7993
 7994
 7995
 7996
 7997
 7998
 7999
 8000
 8001
 8002
 8003
 8004
 8005
 8006
 8007
 8008
 8009
 8010
 8011
 8012
 8013
 8014
 8015
 8016
 8017
 8018
 8019
 8020
 8021
 8022
 8023
 8024
 8025
 8026
 8027
 8028
 8029
 8030
 8031
 8032
 8033
 8034
 8035
 8036
 8037
 8038
 8039
 8040
 8041
 8042
 8043
 8044
 8045
 8046
 8047
 8048
 8049
 8050
 8051
 8052
 8053
 8054
 8055
 8056
 8057
 8058
 8059
 8060
 8061
 8062
 8063
 8064
 8065
 8066
 8067
 8068
 8069
 8070
 8071
 8072
 8073
 8074
 8075
 8076
 8077
 8078
 8079
 8080
 8081
 8082
 8083
 8084
 8085
 8086
 8087
 8088
 8089
 8090
 8091
 8092
 8093
 8094
 8095
 8096
 8097
 8098
 8099
 8100
 8101
 8102
 8103
 8104
 8105
 8106
 8107
 8108
 8109
 8110
 8111
 8112
 8113
 8114
 8115
 8116
 8117
 8118
 8119
 8120
 8121
 8122
 8123
 8124
 8125
 8126
 8127
 8128
 8129
 8130
 8131
 8132
 8133
 8134
 8135
 8136
 8137
 8138
 8139
 8140
 8141
 8142
 8143
 8144
 8145
 8146
 8147
 8148
 8149
 8150
 8151
 8152
 8153
 8154
 8155
 8156
 8157
 8158
 8159
 8160
 8161
 8162
 8163
 8164
 8165
 8166
 8167
 8168
 8169
 8170
 8171
 8172
 8173
 8174
 8175
 8176
 8177
 8178
 8179
 8180
 8181
 8182
 8183
 8184
 8185
 8186
 8187
 8188
 8189
 8190
 8191
 8192
 8193
 8194
 8195
 8196
 8197
 8198
 8199
 8200
 8201
 8202
 8203
 8204
 8205
 8206
 8207
 8208
 8209
 8210
 8211
 8212
 8213
 8214
 8215
 8216
 8217
 8218
 8219
 8220
 8221
 8222
 8223
 8224
 8225
 8226
 8227
 8228
 8229
 8230
 8231
 8232
 8233
 8234
 8235
 8236
 8237
 8238
 8239
 8240
 8241
 8242
 8243
 8244
 8245
 8246
 8247
 8248
 8249
 8250
 8251
 8252
 8253
 8254
 8255
 8256
 8257
 8258
 8259
 8260
 8261
 8262
 8263
 8264
 8265
 8266
 8267
 8268
 8269
 8270
 8271
 8272
 8273
 8274
 8275
 8276
 8277
 8278
 8279
 8280
 8281
 8282
 8283
 8284
 8285
 8286
 8287
 8288
 8289
 8290
 8291
 8292
 8293
 8294
 8295
 8296
 8297
 8298
 8299
 8300
 8301
 8302
 8303
 8304
 8305
 8306
 8307
 8308
 8309
 8310
 8311
 8312
 8313
 8314
 8315
 8316
 8317
 8318
 8319
 8320
 8321
 8322
 8323
 8324
 8325
 8326
 8327
 8328
 8329
 8330
 8331
 8332
 8333
 8334
 8335
 8336
 8337
 8338
 8339
 8340
 8341
 8342
 8343
 8344
 8345
 8346
 8347
 8348
 8349
 8350
 8351
 8352
 8353
 8354
 8355
 8356
 8357
 8358
 8359
 8360
 8361
 8362
 8363
 8364
 8365
 8366
 8367
 8368
 8369
 8370
 8371
 8372
 8373
 8374
 8375
 8376
 8377
 8378
 8379
 8380
 8381
 8382
 8383
 8384
 8385
 8386
 8387
 8388
 8389
 8390
 8391
 8392
 8393
 8394
 8395
 8396
 8397
 8398
 8399
 8400
 8401
 8402
 8403
 8404
 8405
 8406
 8407
 8408
 8409
 8410
 8411
 8412
 8413
 8414
 8415
 8416
 8417
 8418
 8419
 8420
 8421
 8422
 8423
 8424
 8425
 8426
 8427
 8428
 8429
 8430
 8431
 8432
 8433
 8434
 8435
 8436
 8437
 8438
 8439
 8440
 8441
 8442
 8443
 8444
 8445
 8446
 8447
 8448
 8449
 8450
 8451
 8452
 8453
 8454
 8455
 8456
 8457
 8458
 8459
 8460
 8461
 8462
 8463
 8464
 8465
 8466
 8467
 8468
 8469
 8470
 8471
 8472
 8473
 8474
 8475
 8476
 8477
 8478
 8479
 8480
 8481
 8482
 8483
 8484
 8485
 8486
 8487
 8488
 8489
 8490
 8491
 8492
 8493
 8494
 8495
 8496
 8497
 8498
 8499
 8500
 8501
 8502
 8503
 8504
 8505
 8506
 8507
 8508
 8509
 8510
 8511
 8512
 8513
 8514
 8515
 8516
 8517
 8518
 8519
 8520
 8521
 8522
 8523
 8524
 8525
 8526
 8527
 8528
 8529
 8530
 8531
 8532
 8533
 8534
 8535
 8536
 8537
 8538
 8539
 8540
 8541
 8542
 8543
 8544
 8545
 8546
 8547
 8548
 8549
 8550
 8551
 8552
 8553
 8554
 8555
 8556
 8557
 8558
 8559
 8560
 8561
 8562
 8563
 8564
 8565
 8566
 8567
 8568
 8569
 8570
 8571
 8572
 8573
 8574
 8575
 8576
 8577
 8578
 8579
 8580
 8581
 8582
 8583
 8584
 8585
 8586
 8587
 8588
 8589
 8590
 8591
 8592
 8593
 8594
 8595
 8596
 8597
 8598
 8599
 8600
 8601
 8602
 8603
 8604
 8605
 8606
 8607
 8608
 8609
 8610
 8611
 8612
 8613
 8614
 8615
 8616
 8617
 8618
 8619
 8620
 8621
 8622
 8623
 8624
 8625
 8626
 8627
 8628
 8629
 8630
 8631
 8632
 8633
 8634
 8635
 8636
 8637
 8638
 8639
 8640
 8641
 8642
 8643
 8644
 8645
 8646
 8647
 8648
 8649
 8650
 8651
 8652
 8653
 8654
 8655
 8656
 8657
 8658
 8659
 8660
 8661
 8662
 8663
 8664
 8665
 8666
 8667
 8668
 8669
 8670
 8671
 8672
 8673
 8674
 8675
 8676
 8677
 8678
 8679
 8680
 8681
 8682
 8683
 8684
 8685
 8686
 8687
 8688
 8689
 8690
 8691
 8692
 8693
 8694
 8695
 8696
 8697
 8698
 8699
 8700
 8701
 8702
 8703
 8704
 8705
 8706
 8707
 8708
 8709
 8710
 8711
 8712
 8713
 8714
 8715
 8716
 8717
 8718
 8719
 8720
 8721
 8722
 8723
 8724
 8725
 8726
 8727
 8728
 8729
 8730
 8731
 8732
 8733
 8734
 8735
 8736
 8737
 8738
 8739
 8740
 8741
 8742
 8743
 8744
 8745
 8746
 8747
 8748
 8749
 8750
 8751
 8752
 8753
 8754
 8755
 8756
 8757
 8758
 8759
 8760
 8761
 8762
 8763
 8764
 8765
 8766
 8767
 8768
 8769
 8770
 8771
 8772
 8773
 8774
 8775
 8776
 8777
 8778
 8779
 8780
 8781
 8782
 8783
 8784
 8785
 8786
 8787
 8788
 8789
 8790
 8791
 8792
 8793
 8794
 8795
 8796
 8797
 8798
 8799
 8800
 8801
 8802
 8803
 8804
 8805
 8806
 8807
 8808
 8809
 8810
 8811
 8812
 8813
 8814
 8815
 8816
 8817
 8818
 8819
 8820
 8821
 8822
 8823
 8824
 8825
 8826
 8827
 8828
 8829
 8830
 8831
 8832
 8833
 8834
 8835
 8836
 8837
 8838
 8839
 8840
 8841
 8842
 8843
 8844
 8845
 8846
 8847
 8848
 8849
 8850
 8851
 8852
 8853
 8854
 8855
 8856
 8857
 8858
 8859
 8860
 8861
 8862
 8863
 8864
 8865
 8866
 8867
 8868
 8869
 8870
 8871
 8872
 8873
 8874
 8875
 8876
 8877
 8878
 8879
 8880
 8881
 8882
 8883
 8884
 8885
 8886
 8887
 8888
 8889
 8890
 8891
 8892
 8893
 8894
 8895
 8896
 8897
 8898
 8899
 8900
 8901
 8902
 8903
 8904
 8905
 8906
 8907
 8908
 8909
 8910
 8911
 8912
 8913
 8914
 8915
 8916
 8917
 8918
 8919
 8920
 8921
 8922
 8923
 8924
 8925
 8926
 8927
 8928
 8929
 8930
 8931
 8932
 8933
 8934
 8935
 8936
 8937
 8938
 8939
 8940
 8941
 8942
 8943
 8944
 8945
 8946
 8947
 8948
 8949
 8950
 8951
 8952
 8953
 8954
 8955
 8956
 8957
 8958
 8959
 8960
 8961
 8962
 8963
 8964
 8965
 8966
 8967
 8968
 8969
 8970
 8971
 8972
 8973
 8974
 8975
 8976
 8977
 8978
 8979
 8980
 8981
 8982
 8983
 8984
 8985
 8986
 8987
 8988
 8989
 8990
 8991
 8992
 8993
 8994
 8995
 8996
 8997
 8998
 8999
 9000
 9001
 9002
 9003
 9004
 9005
 9006
 9007
 9008
 9009
 9010
 9011
 9012
 9013
 9014
 9015
 9016
 9017
 9018
 9019
 9020
 9021
 9022
 9023
 9024
 9025
 9026
 9027
 9028
 9029
 9030
 9031
 9032
 9033
 9034
 9035
 9036
 9037
 9038
 9039
 9040
 9041
 9042
 9043
 9044
 9045
 9046
 9047
 9048
 9049
 9050
 9051
 9052
 9053
 9054
 9055
 9056
 9057
 9058
 9059
 9060
 9061
 9062
 9063
 9064
 9065
 9066
 9067
 9068
 9069
 9070
 9071
 9072
 9073
 9074
 9075
 9076
 9077
 9078
 9079
 9080
 9081
 9082
 9083
 9084
 9085
 9086
 9087
 9088
 9089
 9090
 9091
 9092
 9093
 9094
 9095
 9096
 9097
 9098
 9099
 9100
 9101
 9102
 9103
 9104
 9105
 9106
 9107
 9108
 9109
 9110
 9111
 9112
 9113
 9114
 9115
 9116
 9117
 9118
 9119
 9120
 9121
 9122
 9123
 9124
 9125
 9126
 9127
 9128
 9129
 9130
 9131
 9132
 9133
 9134
 9135
 9136
 9137
 9138
 9139
 9140
 9141
 9142
 9143
 9144
 9145
 9146
 9147
 9148
 9149
 9150
 9151
 9152
 9153
 9154
 9155
 9156
 9157
 9158
 9159
 9160
 9161
 9162
 9163
 9164
 9165
 9166
 9167
 9168
 9169
 9170
 9171
 9172
 9173
 9174
 9175
 9176
 9177
 9178
 9179
 9180
 9181
 9182
 9183
 9184
 9185
 9186
 9187
 9188
 9189
 9190
 9191
 9192
 9193
 9194
 9195
 9196
 9197
 9198
 9199
 9200
 9201
 9202
 9203
 9204
 9205
 9206
 9207
 9208
 9209
 9210
 9211
 9212
 9213
 9214
 9215
 9216
 9217
 9218
 9219
 9220
 9221
 9222
 9223
 9224
 9225
 9226
 9227
 9228
 9229
 9230
 9231
 9232
 9233
 9234
 9235
 9236
 9237
 9238
 9239
 9240
 9241
 9242
 9243
 9244
 9245
 9246
 9247
 9248
 9249
 9250
 9251
 9252
 9253
 9254
 9255
 9256
 9257
 9258
 9259
 9260
 9261
 9262
 9263
 9264
 9265
 9266
 9267
 9268
 9269
 9270
 9271
 9272
 9273
 9274
 9275
 9276
 9277
 9278
 9279
 9280
 9281
 9282
 9283
 9284
 9285
 9286
 9287
 9288
 9289
 9290
 9291
 9292
 9293
 9294
 9295
 9296
 9297
 9298
 9299
 9300
 9301
 9302
 9303
 9304
 9305
 9306
 9307
 9308
 9309
 9310
 9311
 9312
 9313
 9314
 9315
 9316
 9317
 9318
 9319
 9320
 9321
 9322
 9323
 9324
 9325
 9326
 9327
 9328
 9329
 9330
 9331
 9332
 9333
 9334
 9335
 9336
 9337
 9338
 9339
 9340
 9341
 9342
 9343
 9344
 9345
 9346
 9347
 9348
 9349
 9350
 9351
 9352
 9353
 9354
 9355
 9356
 9357
 9358
 9359
 9360
 9361
 9362
 9363
 9364
 9365
 9366
 9367
 9368
 9369
 9370
 9371
 9372
 9373
 9374
 9375
 9376
 9377
 9378
 9379
 9380
 9381
 9382
 9383
 9384
 9385
 9386
 9387
 9388
 9389
 9390
 9391
 9392
 9393
 9394
 9395
 9396
 9397
 9398
 9399
 9400
 9401
 9402
 9403
 9404
 9405
 9406
 9407
 9408
 9409
 9410
 9411
 9412
 9413
 9414
 9415
 9416
 9417
 9418
 9419
 9420
 9421
 9422
 9423
 9424
 9425
 9426
 9427
 9428
 9429
 9430
 9431
 9432
 9433
 9434
 9435
 9436
 9437
 9438
 9439
 9440
 9441
 9442
 9443
 9444
 9445
 9446
 9447
 9448
 9449
 9450
 9451
 9452
 9453
 9454
 9455
 9456
 9457
 9458
 9459
 9460
 9461
 9462
 9463
 9464
 9465
 9466
 9467
 9468
 9469
 9470
 9471
 9472
 9473
 9474
 9475
 9476
 9477
 9478
 9479
 9480
 9481
 9482
 9483
 9484
 9485
 9486
 9487
 9488
 9489
 9490
 9491
 9492
 9493
 9494
 9495
 9496
 9497
 9498
 9499
 9500
 9501
 9502
 9503
 9504
 9505
 9506
 9507
 9508
 9509
 9510
 9511
 9512
 9513
 9514
 9515
 9516
 9517
 9518
 9519
 9520
 9521
 9522
 9523
 9524
 9525
 9526
 9527
 9528
 9529
 9530
 9531
 9532
 9533
 9534
 9535
 9536
 9537
 9538
 9539
 9540
 9541
 9542
 9543
 9544
 9545
 9546
 9547
 9548
 9549
 9550
 9551
 9552
 9553
 9554
 9555
 9556
 9557
 9558
 9559
 9560
 9561
 9562
 9563
 9564
 9565
 9566
 9567
 9568
 9569
 9570
 9571
 9572
 9573
 9574
 9575
 9576
 9577
 9578
 9579
 9580
 9581
 9582
 9583
 9584
 9585
 9586
 9587
 9588
 9589
 9590
 9591
 9592
 9593
 9594
 9595
 9596
 9597
 9598
 9599
 9600
 9601
 9602
 9603
 9604
 9605
 9606
 9607
 9608
 9609
 9610
 9611
 9612
 9613
 9614
 9615
 9616
 9617
 9618
 9619
 9620
 9621
 9622
 9623
 9624
 9625
 9626
 9627
 9628
 9629
 9630
 9631
 9632
 9633
 9634
 9635
 9636
 9637
 9638
 9639
 9640
 9641
 9642
 9643
 9644
 9645
 9646
 9647
 9648
 9649
 9650
 9651
 9652
 9653
 9654
 9655
 9656
 9657
 9658
 9659
 9660
 9661
 9662
 9663
 9664
 9665
 9666
 9667
 9668
 9669
 9670
 9671
 9672
 9673
 9674
 9675
 9676
 9677
 9678
 9679
 9680
 9681
 9682
 9683
 9684
 9685
 9686
 9687
 9688
 9689
 9690
 9691
 9692
 9693
 9694
 9695
 9696
 9697
 9698
 9699
 9700
 9701
 9702
 9703
 9704
 9705
 9706
 9707
 9708
 9709
 9710
 9711
 9712
 9713
 9714
 9715
 9716
 9717
 9718
 9719
 9720
 9721
 9722
 9723
 9724
 9725
 9726
 9727
 9728
 9729
 9730
 9731
 9732
 9733
 9734
 9735
 9736
 9737
 9738
 9739
 9740
 9741
 9742
 9743
 9744
 9745
 9746
 9747
 9748
 9749
 9750
 9751
 9752
 9753
 9754
 9755
 9756
 9757
 9758
 9759
 9760
 9761
 9762
 9763
 9764
 9765
 9766
 9767
 9768
 9769
 9770
 9771
 9772
 9773
 9774
 9775
 9776
 9777
 9778
 9779
 9780
 9781
 9782
 9783
 9784
 9785
 9786
 9787
 9788
 9789
 9790
 9791
 9792
 9793
 9794
 9795
 9796
 9797
 9798
 9799
 9800
 9801
 9802
 9803
 9804
 9805
 9806
 9807
 9808
 9809
 9810
 9811
 9812
 9813
 9814
 9815
 9816
 9817
 9818
 9819
 9820
 9821
 9822
 9823
 9824
 9825
 9826
 9827
 9828
 9829
 9830
 9831
 9832
 9833
 9834
 9835
 9836
 9837
 9838
 9839
 9840
 9841
 9842
 9843
 9844
 9845
 9846
 9847
 9848
 9849
 9850
 9851
 9852
 9853
 9854
 9855
 9856
 9857
 9858
 9859
 9860
 9861
 9862
 9863
 9864
 9865
 9866
 9867
 9868
 9869
 9870
 9871
 9872
 9873
 9874
 9875
 9876
 9877
 9878
 9879
 9880
 9881
 9882
 9883
 9884
 9885
 9886
 9887
 9888
 9889
 9890
 9891
 9892
 9893
 9894
 9895
 9896
 9897
 9898
 9899
 9900
 9901
 9902
 9903
 9904
 9905
 9906
 9907
 9908
 9909
 9910
 9911
 9912
 9913
 9914
 9915
 9916
 9917
 9918
 9919
 9920
 9921
 9922
 9923
 9924
 9925
 9926
 9927
 9928
 9929
 9930
 9931
 9932
 9933
 9934
 9935
 9936
 9937
 9938
 9939
 9940
 9941
 9942
 9943
 9944
 9945
 9946
 9947
 9948
 9949
 9950
 9951
 9952
 9953
 9954
 9955
 9956
 9957
 9958
 9959
 9960
 9961
 9962
 9963
 9964
 9965
 9966
 9967
 9968
 9969
 9970
 9971
 9972
 9973
 9974
 9975
 9976
 9977
 9978
 9979
 9980
 9981
 9982
 9983
 9984
 9985
 9986
 9987
 9988
 9989
 9990
 9991
 9992
 9993
 9994
 9995
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
#
# 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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
#
# Copyright (c) 2018, Joyent, Inc.

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

PROG=		nwamd
OBJS=		conditions.o dlpi_events.o door_if.o enm.o\
		events.o known_wlans.o llp.o loc.o logging.o\
		main.o ncp.o ncu.o ncu_phys.o ncu_ip.o objects.o\
		routing_events.o sysevent_events.o util.o
SRCS=		$(OBJS:%.o=%.c)
HEADERS=	conditions.h events.h known_wlans.h llp.h ncp.h ncu.h\
		objects.h
LOCFILES=	create_loc_auto create_loc_nonet
NONETLOCFILES=	ipf.conf.dfl ipf6.conf.dfl

ROOTCFGDIR=	$(ROOTETC)/nwam
ROOTLOCDIR=	$(ROOTCFGDIR)/loc
NONETLOCDIR=	$(ROOTLOCDIR)/NoNet
LOCDIRS=	$(NONETLOCDIR)
ROOTCFGFILES=	$(LOCFILES:%=$(ROOTLOCDIR)/%) \
		$(NONETLOCFILES:%=$(NONETLOCDIR)/%)

include		../../../Makefile.cmd

$(ROOTCFGFILES) : FILEMODE= 644

ROOTCMDDIR=	$(ROOTFS_LIBDIR)/inet

LDLIBS +=	-ldhcpagent -ldhcputil -ldladm -ldlpi -lgen \
		-linetutil -lipadm -lkstat -lnsl -lnvpair -lnwam \
		-lsecdb -lscf -lsocket -lsysevent -lumem -luutil

CERRWARN +=	-Wno-parentheses
CERRWARN +=	-Wno-switch

# not linted
SMATCH=off

#
# Instrument 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) $(OBJS) -o $@ $(LDLIBS) $(CTFMERGE_HOOK)
	$(POST_PROCESS)

install: $(ROOTCMD) $(ROOTLOCDIR) $(ROOTCFGFILES)

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

$(ROOTCMD): all

clean:
	$(RM) $(OBJS)

$(ROOTCFGDIR):
	$(INS.dir)

$(ROOTLOCDIR): $(ROOTCFGDIR)
	$(INS.dir)

$(LOCDIRS): $(ROOTLOCDIR)
	$(INS.dir)

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

# Hammerhead: order-only prerequisite so $< is the file, not the directory
$(NONETLOCDIR)/%: % | $(NONETLOCDIR)
	$(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.

Implementation Overview for the NetWork AutoMagic daemon
John Beck, Renee Danson, Michael Hunter, Alan Maguire, Kacheong Poon,
Garima Tripathi, Jan Xie, Anurag Maskey
[Structure and some content shamelessly stolen from Peter Memishian's
dhcpagent architecture overview.]

INTRODUCTION
============

Details about the NWAM requirements, architecture, and design are
available via the NWAM opensolaris project at
http://opensolaris.org/os/project/nwam.  The point of this document is
to place details relevant to somebody attempting to understand the
implementation close to the source code.

THE BASICS
==========

SOURCE FILE ORGANIZATION
=======================
event sources:
	dlpi_events.c
	routing_events.c
	sysevent_events.c
  
object-specific event handlers:
	enm.c
	known_wlans.c
	loc.c
	ncp.c
	ncu_ip.c
	ncu_phys.c

legacy config upgrade
	llp.c

generic code:
	objects.c
	events.c
	conditions.c
	logging.c
	util.c

nwam door requests:
	door_if.c

entry point:
	main.c

OVERVIEW
========

Here we discuss the essential objects and subtle aspects of the NWAM
daemon implementation.  Note that there is of course much more that is
not discussed here, but after this overview you should be able to fend
for yourself in the source code.

Events and Objects
==================

Events come to NWAM from a variety of different sources asyncronously.

o	routing socket
o	dlpi
o	sysevents
o	doors

Routing sockets and dlpi (DL_NOTE_LINK_UP|DOWN events) are handled by
dedicated threads.  Sysevents and doors are both seen as callbacks into
the process proper and will often post their results to the main event
queue.  All event sources post events onto the main event queue.  In
addition state changes of objects and door requests (requesting current
state or a change of state, specification of a WiFi key etc) can
lead to additional events.  We have daemon-internal events (object
initialization, periodic state checks) which are simply enqueued
on the event queue, and external events which are both enqueued on
the event queue and sent to registered listeners (via nwam_event_send()).

So the structure of the daemon is a set of threads that drive event
generation.  Events are posted either directly onto the event queue
or are delayed by posting onto the pending event queue.  SIGALARMs
are set for the event delay,  and when the SIGALARM is received
pending events that have expired are moved onto the event queue
proper.  Delayed enqueueing is useful for periodic checks.

Decisions to change conditions based upon object state changes are
delayed until after bursts of events.  This is achieved by marking a
flag when it is deemed checking is necessary and then the next time the
queue is empty performing those checks.  A typical event profile will
be one event (e.g. a link down) causing a flurry of other events (e.g.
related interface down).  By waiting until all the consequences of the
initial event have been carried out to make higher level decisions we
implicitly debounce those higher level decisions.

At the moment queue quiet actually means that the queue has been quiet
for some short period of time (.1s).  Typically the flurry of events we
want to work through are internally generated and are back to back in
the queue.  We wait a bit longer in case there are reprucussions from
what we do that cause external events to be posted on us.  We are not
interested in waiting for longer term things to happen but merely to
catch immediate changes.

When running, the daemon will consist of a number of threads:

o	the event handling thread: a thread blocking until events appear on the
	event queue, processing each event in order.  Events that require
	time-consuming processing are spawned in worker threads (e.g. WiFi
	connect, DHCP requests etc).
o	door request threads: the door infrastructure manages server threads
	which process synchronous NWAM client requests (e.g. get state of an
	object, connect to a specific WLAN, initiate a scan on a link etc).
o	various wifi/IP threads: threads which do asynchronous work such as
	DHCP requests, WLAN scans etc that cannot hold up event processing in
	the main event handling thread.
o	routing socket threads: process routing socket messages of interest
	(address additons/deletions) and package them as NWAM messages.
o	dlpi threads: used to monitor for DL_NOTE_LINK messages on links

The daemon is structured around a set of objects representing NCPs[1],
NCUs[2], ENMs[3] and known WLANs and a set of state machines which
consume events which act on those objects.  Object lists are maintained
for each object type, and these contain both a libnwam handle (to allow
reading the object directly) and an optional object data pointer which
can point to state information used to configure the object.

Events can be associated with specific objects (e.g. link up), or associated
with no object in particular (e.g. shutdown).

Each object type registers a set of event handler functions with the event
framework such that when an event occurs, the appropriate handler for the
object type is used.  The event handlers are usually called
nwamd_handle_*_event().

[1] NCP Network Configuration Profile; the set of link- and IP-layer
configuration units which collectively specify how a system should be
connected to the network

[2] NCU Network Configuration Unit; the individual components of an NCP

[3] ENM External Network Modifiers; user executable scripts often used
to configure a VPN

Doors and External Events
=========================

The command interface to nwamd is thread a door at NWAM_DOOR
(/etc/svc/volatile/nwam/nwam_door).  This door allows external program to send
messages to nwamd.  The way doors work is to provide a mechanism for
another process to execute code in your process space.  This looks like
a CSPish send/receive/reply in that the receiving process provide a
syncronization point (via door_create(3C)), the calling process uses
that syncronization point to rendezvous with and provide arguments (via
door_call(3C), and then the receive process reply (via
door_return(3C))) passing back data as required.  The OS makes it such
that the memory used to pass data via door_call(3C) is mapped into the
receiving process which can write back into it and then transparently
have it mapped back to the calling process.

As well as handling internal events of interest, the daemon also needs
to send events of interest (link up/down, WLAN scan/connect results etc)
to (possibly) multiple NWAM client listeners.  This is done via
System V message queues. On registering for events via a libnwam door
request into the daemon (nwam_events_register()), a per-client
(identified by pid) message queue file is created.  The
daemon sends messages to all listeners by examining the list of
message queue files (allowing registration to be robust across
daemon restarts) and sending events to each listener.  This is done
via the libnwam function nwam_event_send() which hides the IPC
mechanism from the daemon.

Objects
=======
Four object lists are maintained within the daemon - one each for
the configuration objects libnwam manages. i.e.:

o	ENMs
o	locations
o	known WLANs
o	NCUs of the current active NCP

Objects have an associated libnwam handle and an optional data
field (which is used for NCUs only).

Locking is straightforward - nwamd_object_init() will initialize
an object of a particular type in the appropriate object list,
returning it with the object lock held. When it is no longer  needed,
nwamd_object_unlock() should be called on the object.

To retrieve an existing object, nwamd_object_find() should be
called - again this returns the object in a locked state.

nwamd_object_lock() is deliberately not exposed outside of objects.c,
since object locking is implicit in the above creation/retrieval
functions.

An object is removed from the object list (with handle destroyed)
via nwamd_object_fini() - the object data (if any) is returned
from this call to allow deallocation.

Object state
============
nwamd deals with 3 broad types of object that need to maintain
internal state: NCUs, ENMs and locations (known WLANs are configuration
objects but don't have a state beyond simply being present).
NWAM objects all share a basic set of states:

State		Description
=====		===========
uninitialized	object representation not present on system or in nwamd
initialized	object representation present in system and in nwamd
disabled	disabled manually
offline		external conditions are not satisfied
offline*	external conditions are satisfied, trying to move online
online*		external conditions no longer satisfied, trying to move offline
online		conditions satisfied and configured
maintenance	error occurred in applying configuration

These deliberately mimic SMF states.

The states of interest are offline, offline* and online. 

An object (link/interface NCU, ENM or location) should only move online 
when its conditions are satisfied _and_ its configuration has been successfully
applied. This occurs when an ENM method has run or a link is up, or an
interface has at least one address assigned.

To understand the distinction between offline and offline*, consider the case 
where a link is of prioritized activation, and either is a lower priority
group - and hence inactive (due to cable being unplugged  or inability to
connect to wifi) - or a higher priority group - and hence active. In general,
we want to distinguish between two cases:

1) when we are actively configuring the link with a view to moving online
(offline*), as would be the case when the link's priority group is 
active. 
2) when external policy-based conditions prevent a link from being active. 
offline should be used for such cases. Links in priority groups above and 
below the currently-active group will be offline, since policy precludes them 
from activating (as less-prioritized links).

So we see that offline and offline* can thus be used to distinguish between 
cases that have the potentiality to move online (offline*) from a policy 
perspective - i.e. conditions on the location allow it, or link prioritization 
allows it - and cases where external conditions dictate that it should not 
(offline).

Once an object reaches offline*, its configuration processes should kick in.
This is where auxiliary state is useful, as it allows us to distinguish between
various states in that configuration process. For example, a link can be
waiting for WLAN selection or key data, or an interface can be waiting for 
DHCP response. This auxiliary state can then also be used diagnostically by
libnwam consumers to determine the current status of a link, interface, ENM
etc.

WiFi links present a problem however. On the one hand, we want them
to be inactive when they are not part of the current priority grouping,
while on the other we want to watch out for new WLANs appearing in
scan data if the WiFi link is of a higher priority than the currently-selected
group. The reason we watch out for these is they represent the potential
to change priority grouping to a more preferred group.  To accommodate this,
WiFi links of the same or lower (more preferred) priority group will always
be trying to connect (and thus be offline* if they cannot).

It might appear unnecessary to have a separate state value/machine for 
auxiliary state - why can't we simply add the auxiliary state machine to the
global object state machine? Part of the answer is that there are times we 
need to run through the same configuration state machine when the global
object state is different - in paticular either offline* or online. Consider
WiFi - we want to do periodic scans to find a "better" WLAN - we can easily
do this by running back through the link state machine of auxiliary
states, but we want to stay online while we do it, since we are still
connected (if the WLAN disconnects of course we go to LINK_DOWN and offline).

Another reason we wish to separate the more general states (offline, online
etc) from the more specific ones (WIFI_NEED_SELECTION etc) is to ensure
that the representation of configuration objects closely matches the way
SMF works.

For an NCU physical link, the following link-specific auxiliary states are
used:

Auxiliary state			Description
===============			===========

LINK_WIFI_SCANNING		Scan in progress
LINK_WIFI_NEED_SELECTION	Need user to specify WLAN
LINK_WIFI_NEED_KEY		Need user to specify a WLAN key for selection
LINK_WIFI_CONNECTING		Connecting to current selection

A WiFI link differs from a wired one in that it always has the 
potential to be available - it just depends if visited WLANs are in range. 
So such links - if they are higher in the priority grouping than the 
currently-active priority group - should always be able to scan, as they 
are always "trying" to be activated.

Wired links that do not support  DL_NOTE_LINK_UP/DOWN are problematic,
since we have to simply assume a cable is plugged in.  If an IP NCU
is activated above such a link, and that NCU uses DHCP, a timeout
will be triggered eventually (user-configurable via the nwamd/ncu_wait_time
SMF property of the network/physical:nwam instance) which will cause
us to give up on the link.

For an IP interface NCU, the following auxiliary states are suggested.

Auxiliary state				Description
===============				===========

NWAM_AUX_STATE_IF_WAITING_FOR_ADDR	Waiting for an address to be assigned
NWAM_AUX_STATE_IF_DHCP_TIMED_OUT	DHCP timed out on interface

A link can have multiple logical interfaces plumbed on it consisting
of a mix of static and DHCP-acquired addresses. This means that
we need to decide how to aggregate the state of these logical
interfaces into the NCU state. The concept of "up" we use here
does not correspond to IFF_UP or IFF_RUNNING, but rather
when we get (via getting RTM_NEWADDR events with non-zero
addresses) at least one address assigned to the link.

We use this concept of up as it represents the potential for
network communication - e.g. after assigning a static
address, if the location specifies nameserver etc, it
is possible to communicate over the network. One important
edge case here is that when DHCP information comes
in, we need to reassess location activation conditions and
possibly change or reapply the current location. The problem
is that if we have a static/DHCP mix, and if we rely on
the IP interface's notion of "up" to trigger location activation,
we will likely first apply the location when the static address
has been assigned and before the DHCP information has
been returned (which may include nameserver info). So
the solution is that on getting an RTM_NEWADDR, we 
check if the (logical) interface associated is DHCP, and
even if the interface NCU is already up, we reassess
location activation. This will lead to a reapplication of
the current location or possibly a location switch.

In order to move through the various states, a generic
API is supplied

nwam_error_t
nwamd_object_set_state(nwamd_object_t obj, nwamd_state_t state,
    nwamd_aux_state_t aux_state);

This function creates an OBJECT_STATE event containing
the new state/aux_state and enqueues it in the event
queue. Each object registers its own handler for this
event, and in response to the current state/aux state and
desired aux state it responds appropriately in the event
handling thread, spawning other threads to carry out
actions as appropriate. The object state event is
then sent to any registered listeners. 

So for NCUs, we define a handle_object_state() function
to run the state machine for the NCU object.

Link state and NCP policy
=========================

NCPs can be either:

o	prioritized: where the constituent link NCUs specify priority group
	numbers (where lower are more favoured) and grouping types.  These
	are used to allow link NCUs to be either grouped separately (exclusive)
	or together (shared or all).
o	manual: their activation is governed by the value of their enabled
	property.
o	a combination of the above.

IP interface NCUs interit their activation from the links below them,
so an IP interface NCU will be active if its underlying link is (assuming
it hasn't been disabled).

At startup, and at regular intervals (often triggered by NWAM
events), the NCP policy needs to be reassessed. There
are a number of causes for NCP policy to be reassessed -

o	a periodic check of link state that occurs every N seconds
o	a link goes from offline(*) to online (cable plug/wifi connect)
o	a link goes from online to offline (cable unplug/wifi disconnect).

Any of these should cause the link selecton algorithm to rerun.

The link selection algorithm works as follows:

Starting from the lowest priority grouping value, assess all links 
in that priority group.

The current priority-group is considered failed if:

o	"exclusive" NCUs exist and none are offline*/online,
o	"shared" NCUs exist and none are offline*/online,
o	"all" NCUs exist and all are not offline*/online,
o	no NCUs are offline*/online.

We do not invalidate a link that is offline* since its configuration
is in progress. This has the unfortunate side-effect that
wired links that do not do DL_NOTE_LINK_UP/DOWN will never
fail. If such links wish to be skipped, their priority group value
should be increased (prioritizing wireless links).

One a priority group has been selected, all links in groups above
_and_ below it need to be moved offline.

Location Activation
===================
A basic set of system-supplied locations are supplied - NoNet and
Automatic.  nwamd will apply the NoNet location until such a time
as an interface NCU is online, at which point it will switch
to the Automatic location.  If a user-supplied location is supplied,
and it is either manually enabled or its conditions are satisfied, it
will be preferred and activated instead.  Only one location can be
active at once since each location has its own specification of nameservices
etc.

ENM Activation
==============
ENMs are either manual or conditional in activation and will be
activated if they are enabled (manual) or if the conditions
are met (conditional).  Multiple ENMs can be active at once.
/*
 * 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.
 */

#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <inet/ip.h>
#include <libdladm.h>
#include <libdllink.h>
#include <libdlwlan.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <libnwam.h>
#include "conditions.h"
#include "ncu.h"
#include "objects.h"
#include "util.h"

/*
 * conditions.c - contains routines which check state to see if activation
 * conditions for NWAM objects are satisfied and rates activation conditions to
 * help determine which is most specific.
 *
 * If the activation-mode is CONDITIONAL_ANY or CONDITIONAL_ALL, the conditions
 * property is set to a string made up of conditional expressions. Each
 * expression is made up of a condition that can be assigned a boolean value,
 * e.g. "system-domain is sun.com" or "ncu ip:bge0 is-not active". If the
 * activation-mode is CONDITIONAL_ANY, the condition will be satisfied if any
 * one of the conditions is true; if the activation-mode is CONDITIONAL_ALL,
 * the condition is satisfied only if all of the conditions are true.
 */

uint64_t condition_check_interval = CONDITION_CHECK_INTERVAL_DEFAULT;

extern int getdomainname(char *, int);

/* NCP, NCU, ENM and location conditions */
static boolean_t test_condition_ncp(nwam_condition_t condition,
    const char *ncp_name);
static boolean_t test_condition_ncu(nwam_condition_t condition,
    const char *ncu_name);
static boolean_t test_condition_enm(nwam_condition_t condition,
    const char *enm_name);
static boolean_t test_condition_loc(nwam_condition_t condition,
    const char *loc_name);

/* IP address conditions */
static boolean_t test_condition_ip_address(nwam_condition_t condition,
    const char *ip_address);

/* domainname conditions */
static boolean_t test_condition_sys_domain(nwam_condition_t condition,
    const char *domainname);
static boolean_t test_condition_adv_domain(nwam_condition_t condition,
    const char *domainname);

/*  WLAN conditions */
static boolean_t test_condition_wireless_essid(nwam_condition_t condition,
    const char *essid);
static boolean_t test_condition_wireless_bssid(nwam_condition_t condition,
    const char *essid);

struct nwamd_condition_map {
	nwam_condition_object_type_t object_type;
	boolean_t (*condition_func)(nwam_condition_t, const char *);
} condition_map[] =
{
	{ NWAM_CONDITION_OBJECT_TYPE_NCP, test_condition_ncp },
	{ NWAM_CONDITION_OBJECT_TYPE_NCU, test_condition_ncu },
	{ NWAM_CONDITION_OBJECT_TYPE_ENM, test_condition_enm },
	{ NWAM_CONDITION_OBJECT_TYPE_LOC, test_condition_loc },
	{ NWAM_CONDITION_OBJECT_TYPE_IP_ADDRESS, test_condition_ip_address },
	{ NWAM_CONDITION_OBJECT_TYPE_SYS_DOMAIN, test_condition_sys_domain },
	{ NWAM_CONDITION_OBJECT_TYPE_ADV_DOMAIN, test_condition_adv_domain },
	{ NWAM_CONDITION_OBJECT_TYPE_ESSID, test_condition_wireless_essid },
	{ NWAM_CONDITION_OBJECT_TYPE_BSSID, test_condition_wireless_bssid }
};

/*
 * This function takes which kind of conditions (is or is not) we are testing
 * the object against and an object and applies the conditon to the object.
 */
static boolean_t
test_condition_object_state(nwam_condition_t condition,
    nwam_object_type_t object_type, const char *object_name)
{
	nwamd_object_t object;
	nwam_state_t state;

	object = nwamd_object_find(object_type, object_name);
	if (object == NULL)
		return (B_FALSE);

	state = object->nwamd_object_state;
	nwamd_object_release(object);

	switch (condition) {
	case NWAM_CONDITION_IS:
		return (state == NWAM_STATE_ONLINE);
	case NWAM_CONDITION_IS_NOT:
		return (state != NWAM_STATE_ONLINE);
	default:
		return (B_FALSE);
	}
}

static boolean_t
test_condition_ncp(nwam_condition_t condition, const char *name)
{
	boolean_t active;

	(void) pthread_mutex_lock(&active_ncp_mutex);
	active = (strcasecmp(active_ncp, name) == 0);
	(void) pthread_mutex_unlock(&active_ncp_mutex);

	switch (condition) {
	case NWAM_CONDITION_IS:
		return (active);
	case NWAM_CONDITION_IS_NOT:
		return (active != B_TRUE);
	default:
		return (B_FALSE);
	}
}

static boolean_t
test_condition_ncu(nwam_condition_t condition, const char *name)
{
	char *real_name, *ncu_name;
	nwam_ncu_handle_t ncuh;
	nwam_ncu_type_t ncu_type;
	boolean_t rv;

	/* names are case-insensitive, so get real name from libnwam */
	if (nwam_ncu_read(active_ncph, name, NWAM_NCU_TYPE_INTERFACE, 0, &ncuh)
	    == NWAM_SUCCESS) {
		ncu_type = NWAM_NCU_TYPE_INTERFACE;
	} else if (nwam_ncu_read(active_ncph, name, NWAM_NCU_TYPE_LINK, 0,
	    &ncuh) == NWAM_SUCCESS) {
		ncu_type = NWAM_NCU_TYPE_LINK;
	} else {
		return (B_FALSE);
	}
	if (nwam_ncu_get_name(ncuh, &real_name) != NWAM_SUCCESS) {
		nwam_ncu_free(ncuh);
		return (B_FALSE);
	}
	nwam_ncu_free(ncuh);

	/*
	 * Name may be either unqualified or qualified by NCU type
	 * (interface:/link:).  Need to translate unqualified names
	 * to qualified, specifying interface:name if an interface
	 * NCU is present, otherwise link:ncu.
	 */
	if (nwam_ncu_name_to_typed_name(real_name, ncu_type, &ncu_name)
	    != NWAM_SUCCESS) {
		free(real_name);
		return (B_FALSE);
	}
	free(real_name);

	rv = test_condition_object_state(condition, NWAM_OBJECT_TYPE_NCU,
	    ncu_name);
	free(ncu_name);
	return (rv);
}

static boolean_t
test_condition_enm(nwam_condition_t condition, const char *enm_name)
{
	nwam_enm_handle_t enmh;
	char *real_name;
	boolean_t rv;

	/* names are case-insensitive, so get real name from libnwam */
	if (nwam_enm_read(enm_name, 0, &enmh) != NWAM_SUCCESS)
		return (B_FALSE);
	if (nwam_enm_get_name(enmh, &real_name) != NWAM_SUCCESS) {
		nwam_enm_free(enmh);
		return (B_FALSE);
	}
	nwam_enm_free(enmh);

	rv = test_condition_object_state(condition, NWAM_OBJECT_TYPE_ENM,
	    real_name);
	free(real_name);
	return (rv);
}

static boolean_t
test_condition_loc(nwam_condition_t condition, const char *loc_name)
{
	nwam_loc_handle_t loch;
	char *real_name;
	boolean_t rv;

	/* names are case-insensitive, so get real name from libnwam */
	if (nwam_loc_read(loc_name, 0, &loch) != NWAM_SUCCESS)
		return (B_FALSE);
	if (nwam_loc_get_name(loch, &real_name) != NWAM_SUCCESS) {
		nwam_loc_free(loch);
		return (B_FALSE);
	}
	nwam_loc_free(loch);

	rv = test_condition_object_state(condition, NWAM_OBJECT_TYPE_LOC,
	    real_name);
	free(real_name);
	return (rv);
}

static boolean_t
test_condition_domain(nwam_condition_t condition, const char *target_domain,
    const char *found_domain)
{
	int i, len_t, len_f;
	char target[MAXHOSTNAMELEN], found[MAXHOSTNAMELEN];

	len_t = target_domain == NULL ? 0 : strlen(target_domain);
	len_f = found_domain == NULL ? 0 : strlen(found_domain);

	/* convert target_domain and found_domain to lowercase for strstr() */
	for (i = 0; i < len_t; i++)
		target[i] = tolower(target_domain[i]);
	target[len_t] = '\0';

	for (i = 0; i < len_f; i++)
		found[i] = tolower(found_domain[i]);
	found[len_f] = '\0';

	switch (condition) {
	case NWAM_CONDITION_IS:
		return (found_domain != NULL && strcmp(found, target) == 0);
	case NWAM_CONDITION_IS_NOT:
		return (found_domain == NULL || strcmp(found, target) != 0);
	case NWAM_CONDITION_CONTAINS:
		return (found_domain != NULL && strstr(found, target) != NULL);
	case NWAM_CONDITION_DOES_NOT_CONTAIN:
		return (found_domain == NULL || strstr(found, target) == NULL);
	default:
		return (B_FALSE);
	}
}

struct ncu_adv_domains {
	struct ncu_adv_domains *next;
	char *dns_domain;
	char *nis_domain;
};

static int
get_adv_domains(nwamd_object_t obj, void *arg)
{
	nwamd_ncu_t *ncu = (nwamd_ncu_t *)obj->nwamd_object_data;
	struct ncu_adv_domains **headpp = (struct ncu_adv_domains **)arg;
	struct ncu_adv_domains *adp;
	char *dns, *nis;

	if (ncu->ncu_type != NWAM_NCU_TYPE_INTERFACE)
		return (0);

	dns = nwamd_get_dhcpinfo_data("DNSdmain", ncu->ncu_name);
	nis = nwamd_get_dhcpinfo_data("NISdmain", ncu->ncu_name);

	if (dns != NULL || nis != NULL) {
		adp = (struct ncu_adv_domains *)malloc(sizeof (*adp));
		if (adp == NULL)
			return (1);
		adp->dns_domain = dns;
		adp->nis_domain = nis;
		adp->next = *headpp;
		*headpp = adp;
	}

	return (0);
}

static boolean_t
test_condition_sys_domain(nwam_condition_t condition, const char *domainname)
{
	char cur_domainname[MAXHOSTNAMELEN];

	if (getdomainname(cur_domainname, MAXHOSTNAMELEN) != 0)
		return (B_FALSE);

	return (test_condition_domain(condition, domainname, cur_domainname));
}

static boolean_t
test_condition_adv_domain(nwam_condition_t condition, const char *domainname)
{
	struct ncu_adv_domains *adv_domains = NULL;
	struct ncu_adv_domains *adp, *prev;
	boolean_t positive, rtn;

	(void) nwamd_walk_objects(NWAM_OBJECT_TYPE_NCU, get_adv_domains,
	    &adv_domains);

	positive = (condition == NWAM_CONDITION_IS ||
	    condition == NWAM_CONDITION_CONTAINS);

	/*
	 * Walk the advertised domain list.  Our test function tests one
	 * single domain, but we're dealing with a list: if our condition
	 * is positive ('is' or 'contains'), the test function for each
	 * domain results are or'd together; if our condition is negative
	 * ('is-not' or 'does-not-contain'), the test function results must
	 * be and'd.  Thus our short-circuit exit value depends on our
	 * condition: if the test function returns TRUE it implies immediate
	 * success for a positive condition; if it returns FALSE it implies
	 * immediate failure for a negative condition.
	 */
	adp = adv_domains;
	while (adp != NULL) {
		if ((test_condition_domain(condition, domainname,
		    adp->dns_domain) == positive) ||
		    (test_condition_domain(condition, domainname,
		    adp->nis_domain) == positive)) {
			rtn = positive;
			break;
		}
		adp = adp->next;
	}
	if (adp == NULL) {
		/*
		 * We did not short-circuit; we therefore failed if our
		 * condition was positive, and succeeded if our condition
		 * was negative.
		 */
		rtn = !positive;
	}

	/* now free the domain list */
	adp = adv_domains;
	while (adp != NULL) {
		prev = adp;
		adp = prev->next;
		free(prev->dns_domain);
		free(prev->nis_domain);
		free(prev);
	}

	return (rtn);
}

/*
 * Returns true if prefixlen bits of addr1 match prefixlen bits of addr2.
 */
static boolean_t
prefixmatch(uchar_t *addr1, uchar_t *addr2, int prefixlen)
{
	uchar_t mask[IPV6_ABITS/8];
	int i, j = 0;

	if (prefixlen == 0)
		return (B_TRUE);

	while (prefixlen > 0) {
		if (prefixlen >= 8) {
			mask[j++] = 0xFF;
			prefixlen -= 8;
		} else {
			mask[j] |= 1 << (8 - prefixlen);
			prefixlen--;
		}
	}
	/* Ensure at least one byte is tested */
	if (j == 0) j++;

	for (i = 0; i < j; i++) {
		if ((addr1[i] & mask[i]) != (addr2[i] & mask[i]))
			return (B_FALSE);
	}
	return (B_TRUE);
}

/*
 * Given a string representation of an IPv4 or IPv6 address returns the
 * sockaddr representation. Note that 'sockaddr' should point at the correct
 * sockaddr structure for the address family (sockaddr_in for AF_INET or
 * sockaddr_in6 for AF_INET6) or alternatively at a sockaddr_storage
 * structure.
 */
static struct sockaddr_storage *
nwamd_str2sockaddr(sa_family_t af, const char *straddr,
    struct sockaddr_storage *addr)
{
	struct sockaddr_in *sin;
	struct sockaddr_in6 *sin6;
	int err;

	if (af == AF_INET) {
		sin = (struct sockaddr_in *)addr;
		sin->sin_family = AF_INET;
		err = inet_pton(AF_INET, straddr, &sin->sin_addr);
	} else if (af == AF_INET6) {
		sin6 = (struct sockaddr_in6 *)addr;
		sin6->sin6_family = AF_INET6;
		err = inet_pton(AF_INET6, straddr, &sin6->sin6_addr);
	} else {
		errno = EINVAL;
		return (NULL);
	}
	return (err == 1 ? addr : NULL);
}

struct nwamd_ipaddr_condition_walk_arg {
	nwam_condition_t condition;
	struct sockaddr_storage sockaddr;
	int prefixlen;
	boolean_t res;
};

static int
check_ipaddr(sa_family_t family, struct ifaddrs *ifa, void *arg)
{
	struct nwamd_ipaddr_condition_walk_arg *wa = arg;
	struct sockaddr_in6 addr6;
	struct sockaddr_in addr;
	boolean_t match = B_FALSE;
	uchar_t *addr1, *addr2;

	if (family == AF_INET) {
		(void) memcpy(&addr, ifa->ifa_addr, sizeof (addr));
		addr1 = (uchar_t *)(&addr.sin_addr.s_addr);
		addr2 = (uchar_t *)&(((struct sockaddr_in *)
		    &(wa->sockaddr))->sin_addr.s_addr);
	} else {
		(void) memcpy(&addr6, ifa->ifa_addr, sizeof (addr6));
		addr1 = (uchar_t *)(&addr6.sin6_addr.s6_addr);
		addr2 = (uchar_t *)&(((struct sockaddr_in6 *)
		    &(wa->sockaddr))->sin6_addr.s6_addr);
	}

	match = prefixmatch(addr1, addr2, wa->prefixlen);

	nlog(LOG_DEBUG, "check_ipaddr: match %d\n", match);
	switch (wa->condition) {
	case NWAM_CONDITION_IS:
	case NWAM_CONDITION_IS_IN_RANGE:
		wa->res = match;
		if (match)
			return (1);
		return (0);
	case NWAM_CONDITION_IS_NOT:
	case NWAM_CONDITION_IS_NOT_IN_RANGE:
		wa->res = !match;
		return (0);
	default:
		return (0);
	}
}

static boolean_t
test_condition_ip_address(nwam_condition_t condition,
    const char *ip_address_string)
{
	sa_family_t family;
	char *copy, *ip_address, *prefixlen_string, *lasts;
	struct nwamd_ipaddr_condition_walk_arg wa;
	struct ifaddrs *ifap, *ifa;

	if ((copy = strdup(ip_address_string)) == NULL)
		return (B_FALSE);

	if ((ip_address = strtok_r(copy, " \t/", &lasts)) == NULL) {
		free(copy);
		return (B_FALSE);
	}

	prefixlen_string = strtok_r(NULL, " \t", &lasts);

	if (nwamd_str2sockaddr(AF_INET, ip_address, &wa.sockaddr) != NULL) {
		family = AF_INET;
		wa.prefixlen = IP_ABITS;
	} else if (nwamd_str2sockaddr(AF_INET6, ip_address, &wa.sockaddr)
	    != NULL) {
		family = AF_INET6;
		wa.prefixlen = IPV6_ABITS;
	} else {
		nlog(LOG_ERR, "test_condition_ip_address: "
		    "nwamd_str2sockaddr failed for %s: %s", ip_address,
		    strerror(errno));
		free(copy);
		return (B_FALSE);
	}

	if (prefixlen_string != NULL)
		wa.prefixlen = atoi(prefixlen_string);

	wa.condition = condition;

	switch (condition) {
	case NWAM_CONDITION_IS:
	case NWAM_CONDITION_IS_IN_RANGE:
		wa.res = B_FALSE;
		break;
	case NWAM_CONDITION_IS_NOT:
	case NWAM_CONDITION_IS_NOT_IN_RANGE:
		wa.res = B_TRUE;
		break;
	default:
		free(copy);
		return (B_FALSE);
	}
	free(copy);

	if (getifaddrs(&ifa) == -1) {
		nlog(LOG_ERR, "test_condition_ip_address: "
		    "getifaddrs failed: %s", strerror(errno));
		return (wa.res);
	}
	for (ifap = ifa; ifap != NULL; ifap = ifap->ifa_next) {
		if (ifap->ifa_addr->sa_family != family)
			continue;
		if (check_ipaddr(family, ifap, &wa) == 1)
			break;
	}
	freeifaddrs(ifa);

	return (wa.res);
}

struct nwamd_wlan_condition_walk_arg {
	nwam_condition_t condition;
	const char *exp_essid;
	const char *exp_bssid;
	uint_t num_connected;
	boolean_t res;
};

static int
check_wlan(const char *linkname, void *arg)
{
	struct nwamd_wlan_condition_walk_arg *wa = arg;
	datalink_id_t linkid;
	dladm_wlan_linkattr_t attr;
	dladm_status_t status;
	char cur_essid[DLADM_STRSIZE];
	char cur_bssid[DLADM_STRSIZE];
	char errmsg[DLADM_STRSIZE];

	if ((status = dladm_name2info(dld_handle, linkname, &linkid, NULL, NULL,
	    NULL)) != DLADM_STATUS_OK) {
		nlog(LOG_DEBUG, "check_wlan: dladm_name2info() for %s "
		    "failed: %s", linkname,
		    dladm_status2str(status, errmsg));
		return (DLADM_WALK_CONTINUE);
	}

	status = dladm_wlan_get_linkattr(dld_handle, linkid, &attr);
	if (status != DLADM_STATUS_OK) {
		nlog(LOG_DEBUG, "check_wlan: dladm_wlan_get_linkattr() for %s "
		    "failed: %s", linkname,
		    dladm_status2str(status, errmsg));
		return (DLADM_WALK_CONTINUE);
	}
	if (attr.la_status == DLADM_WLAN_LINK_DISCONNECTED)
		return (DLADM_WALK_TERMINATE);

	wa->num_connected++;

	if (wa->exp_essid != NULL) {
		/* Is the NIC associated with the expected access point? */
		(void) dladm_wlan_essid2str(&attr.la_wlan_attr.wa_essid,
		    cur_essid);
		switch (wa->condition) {
		case NWAM_CONDITION_IS:
			wa->res = strcmp(cur_essid, wa->exp_essid) == 0;
			if (wa->res)
				return (DLADM_WALK_TERMINATE);
			break;
		case NWAM_CONDITION_IS_NOT:
			wa->res = strcmp(cur_essid, wa->exp_essid) != 0;
			if (!wa->res)
				return (DLADM_WALK_TERMINATE);
			break;
		case NWAM_CONDITION_CONTAINS:
			wa->res = strstr(cur_essid, wa->exp_essid) != NULL;
			if (wa->res)
				return (DLADM_WALK_TERMINATE);
			break;
		case NWAM_CONDITION_DOES_NOT_CONTAIN:
			wa->res = strstr(cur_essid, wa->exp_essid) == NULL;
			if (!wa->res)
				return (DLADM_WALK_TERMINATE);
			break;
		default:
			return (DLADM_WALK_TERMINATE);
		}
		return (DLADM_WALK_CONTINUE);
	}
	if (wa->exp_bssid != NULL) {
		/* Is the NIC associated with the expected access point? */
		(void) dladm_wlan_bssid2str(&attr.la_wlan_attr.wa_bssid,
		    cur_bssid);
		switch (wa->condition) {
		case NWAM_CONDITION_IS:
			wa->res = strcmp(cur_bssid, wa->exp_bssid) == 0;
			if (wa->res)
				return (DLADM_WALK_TERMINATE);
			break;
		case NWAM_CONDITION_IS_NOT:
			wa->res = strcmp(cur_bssid, wa->exp_bssid) != 0;
			if (!wa->res)
				return (DLADM_WALK_TERMINATE);
			break;
		default:
			return (DLADM_WALK_TERMINATE);
		}
		return (DLADM_WALK_CONTINUE);
	}
	/*
	 * Neither an ESSID or BSSID match is required - being connected to a
	 * WLAN is enough.
	 */
	switch (wa->condition) {
	case NWAM_CONDITION_IS:
		wa->res = B_TRUE;
		return (DLADM_WALK_TERMINATE);
	default:
		wa->res = B_FALSE;
		return (DLADM_WALK_TERMINATE);
	}
	/*NOTREACHED*/
	return (DLADM_WALK_CONTINUE);
}

static boolean_t
test_condition_wireless_essid(nwam_condition_t condition,
    const char *essid)
{
	struct nwamd_wlan_condition_walk_arg wa;

	wa.condition = condition;
	wa.exp_essid = essid;
	wa.exp_bssid = NULL;
	wa.num_connected = 0;
	wa.res = B_FALSE;

	(void) dladm_walk(check_wlan, dld_handle, &wa, DATALINK_CLASS_PHYS,
	    DL_WIFI, DLADM_OPT_ACTIVE);

	return (wa.num_connected > 0 && wa.res == B_TRUE);
}

static boolean_t
test_condition_wireless_bssid(nwam_condition_t condition,
    const char *bssid)
{
	struct nwamd_wlan_condition_walk_arg wa;

	wa.condition = condition;
	wa.exp_bssid = bssid;
	wa.exp_essid = NULL;
	wa.num_connected = 0;
	wa.res = B_FALSE;

	(void) dladm_walk(check_wlan, dld_handle, &wa, DATALINK_CLASS_PHYS,
	    DL_WIFI, DLADM_OPT_ACTIVE);

	return (wa.num_connected > 0 && wa.res == B_TRUE);
}

/*
 * This function takes an activation mode and a string representation of a
 * condition and evaluates it.
 */
boolean_t
nwamd_check_conditions(nwam_activation_mode_t activation_mode,
    char **condition_strings, uint_t num_conditions)
{
	boolean_t ret = B_FALSE;
	nwam_condition_t condition;
	nwam_condition_object_type_t object_type;
	char *object_name;
	int i, j;

	for (i = 0; i < num_conditions; i++) {

		if (nwam_condition_string_to_condition(condition_strings[i],
		    &object_type, &condition, &object_name) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "check_conditions: invalid condition %s",
			    condition_strings[i]);
			return (B_FALSE);
		}
		ret = B_FALSE;

		for (j = 0; j < (sizeof (condition_map) /
		    sizeof (struct nwamd_condition_map)); j++) {
			if (condition_map[j].object_type == object_type)
				ret = condition_map[j].condition_func(condition,
				    object_name);
		}

		free(object_name);

		if (activation_mode == NWAM_ACTIVATION_MODE_CONDITIONAL_ANY &&
		    ret) {
			return (B_TRUE);
		}
		if (activation_mode == NWAM_ACTIVATION_MODE_CONDITIONAL_ALL &&
		    !ret) {
			return (B_FALSE);
		}
	}
	if (activation_mode == NWAM_ACTIVATION_MODE_CONDITIONAL_ANY && ret)
		return (B_TRUE);
	if (activation_mode == NWAM_ACTIVATION_MODE_CONDITIONAL_ALL && ret)
		return (B_TRUE);

	return (B_FALSE);
}

/*
 * In rating activation conditions, we take the best-rated CONDITIONAL_ANY
 * condition, or sum all the CONDITIONAL_ALL condition ratings. This allows
 * us to compare between location activation conditions to pick the best.
 */
uint64_t
nwamd_rate_conditions(nwam_activation_mode_t activation_mode,
    char **conditions, uint_t num_conditions)
{
	nwam_condition_t condition;
	nwam_condition_object_type_t object_type;
	char *object_name;
	int i;
	uint64_t rating = 0, total_rating = 0;

	for (i = 0; i < num_conditions; i++) {

		object_name = NULL;
		if (nwam_condition_string_to_condition(conditions[i],
		    &object_type, &condition, &object_name) != NWAM_SUCCESS ||
		    nwam_condition_rate(object_type, condition, &rating)
		    != NWAM_SUCCESS) {
			nlog(LOG_ERR, "nwamd_rate_conditions: could not rate "
			    "condition");
			free(object_name);
			return (0);
		}
		free(object_name);

		if (activation_mode == NWAM_ACTIVATION_MODE_CONDITIONAL_ANY) {
			if (rating > total_rating)
				total_rating = rating;
		} else if (activation_mode ==
		    NWAM_ACTIVATION_MODE_CONDITIONAL_ALL) {
			total_rating += rating;
		}
	}
	return (total_rating);
}

/*
 * Different from nwamd_triggered_check_all_conditions() in that this
 * function enqueues a timed check event.
 */
void
nwamd_set_timed_check_all_conditions(void)
{
	nwamd_event_t check_event = nwamd_event_init
	    (NWAM_EVENT_TYPE_TIMED_CHECK_CONDITIONS, NWAM_OBJECT_TYPE_UNKNOWN,
	    0, NULL);
	if (check_event != NULL) {
		/* Add another timed event to recheck conditions */
		nwamd_event_enqueue_timed(check_event,
		    condition_check_interval > CONDITION_CHECK_INTERVAL_MIN ?
		    condition_check_interval : CONDITION_CHECK_INTERVAL_MIN);
	}
}

/*
 * Does not enqueue another check event.
 */
void
nwamd_check_all_conditions(void)
{
	nwamd_enm_check_conditions();
	nwamd_loc_check_conditions();
}

void
nwamd_create_timed_condition_check_event(void)
{
	nwamd_event_t check_event = nwamd_event_init
	    (NWAM_EVENT_TYPE_TIMED_CHECK_CONDITIONS, NWAM_OBJECT_TYPE_UNKNOWN,
	    0, NULL);
	if (check_event != NULL)
		nwamd_event_enqueue(check_event);
}

void
nwamd_create_triggered_condition_check_event(uint32_t when)
{
	nwamd_event_t check_event;

	if (!nwamd_event_enqueued(NWAM_EVENT_TYPE_TRIGGERED_CHECK_CONDITIONS,
	    NWAM_OBJECT_TYPE_UNKNOWN, NULL)) {
		check_event = nwamd_event_init
		    (NWAM_EVENT_TYPE_TRIGGERED_CHECK_CONDITIONS,
		    NWAM_OBJECT_TYPE_UNKNOWN, 0, NULL);
		if (check_event != NULL)
			nwamd_event_enqueue_timed(check_event, when);
	}
}
/*
 * 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.
 */

#ifndef _CONDITIONS_H
#define	_CONDITIONS_H

#include <libnwam.h>

#define	CONDITION_CHECK_INTERVAL_DEFAULT	120
#define	CONDITION_CHECK_INTERVAL_MIN		30

extern uint64_t condition_check_interval;

/* Common condition check function */
extern boolean_t nwamd_check_conditions(nwam_activation_mode_t, char **,
    uint_t);
/* Rate condition (used to pick best location condition) */
extern uint64_t nwamd_rate_conditions(nwam_activation_mode_t, char **,
    uint_t);

/* Check activation conditions */
extern void nwamd_set_timed_check_all_conditions(void);
extern void nwamd_check_all_conditions(void);

/* Create condition check events */
extern void nwamd_create_timed_condition_check_event(void);
extern void nwamd_create_triggered_condition_check_event(uint32_t);

#endif /* _CONDITIONS_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 2010 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

create loc Automatic
set activation-mode=system
set nameservices=dns
set nameservices-config-file=/etc/nsswitch.dns
set dns-nameservice-configsrc=dhcp
end
#
# 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.
#

create loc NoNet
set activation-mode=system
set nameservices=files
set nameservices-config-file=/etc/nsswitch.files
set ipfilter-config-file=/etc/nwam/loc/NoNet/ipf.conf
set ipfilter-v6-config-file=/etc/nwam/loc/NoNet/ipf6.conf
end
/*
 * 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.
 */

#include <arpa/inet.h>
#include <assert.h>
#include <fcntl.h>
#include <libdlpi.h>
#include <libnwam.h>
#include <net/if.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/fcntl.h>
#include <unistd.h>

#include "events.h"
#include "ncp.h"
#include "ncu.h"
#include "objects.h"
#include "util.h"

/*
 * dlpi_events.c - this file contains routines to retrieve
 * DL_NOTE_LINK_[UP|DOWN] events from the system and packages them for high
 * level processing.  Holding a dlpi_handle to a link prevents the
 * associated driver unloading that can happen when IP is not plumbed,
 * so it is vital to ensure that the handle is open for the lifetime
 * of the WiFi connection.
 */

/*
 * This is a callback function executed when dlpi_recv() gets a DL_NOTE_LINK_UP.
 * It packages up the event for consumption by the link state machine.
 */
/* ARGSUSED0 */
static void
nwamd_dlpi_notify(dlpi_handle_t dhp, dlpi_notifyinfo_t *info, void *arg)
{
	nwamd_event_t ev;
	char *name = arg;

	if (info->dni_note & DL_NOTE_LINK_UP)
		ev = nwamd_event_init_link_state(name, B_TRUE);
	else
		ev = nwamd_event_init_link_state(name, B_FALSE);
	if (ev != NULL)
		nwamd_event_enqueue(ev);
}

/*
 * We are only intested in DL_NOTE_LINK_UP events which we've registered for
 * in nwamd_dlpi_add_link().  But we have to keep calling dlpi_recv() to
 * force the notification callback to be executed.
 */
static void *
nwamd_dlpi_thread(void *arg)
{
	int rc;
	dlpi_handle_t *dh = arg;

	do {
		rc = dlpi_recv(*dh, NULL, NULL, NULL, NULL, -1, NULL);
	} while (rc == DLPI_SUCCESS);
	nlog(LOG_ERR, "dlpi_recv failed: %s", dlpi_strerror(rc));
	return (NULL);
}

/*
 * This is called when we want to start receiving notifications from state
 * changes on a link.
 */
void
nwamd_dlpi_add_link(nwamd_object_t obj)
{
	nwamd_ncu_t *ncu = obj->nwamd_object_data;
	nwamd_link_t *link;
	dlpi_notifyid_t id;
	int rc;

	nlog(LOG_DEBUG, "nwamd_dlpi_add_link: ncu %p (%s) type %d",
	    ncu, obj->nwamd_object_name, ncu != NULL ? ncu->ncu_type : -1);

	assert(ncu != NULL && ncu->ncu_type == NWAM_NCU_TYPE_LINK);

	link = &ncu->ncu_link;

	/* Already running? */
	if (link->nwamd_link_dlpi_thread != 0) {
		nlog(LOG_DEBUG, "nwamd_dlpi_add_link(%s) already running",
		    obj->nwamd_object_name);
		return;
	}

	rc = dlpi_open(ncu->ncu_name, &link->nwamd_link_dhp, 0);
	if (rc != DLPI_SUCCESS) {
		nlog(LOG_ERR, "nwamd_dlpi_add_link: dlpi_open(%s) = %s",
		    ncu->ncu_name, dlpi_strerror(rc));
		return;
	}

	nwamd_set_unset_link_properties(ncu, B_TRUE);

	rc = dlpi_enabnotify(link->nwamd_link_dhp,
	    DL_NOTE_LINK_UP | DL_NOTE_LINK_DOWN, nwamd_dlpi_notify,
	    ncu->ncu_name, &id);
	if (rc != DLPI_SUCCESS) {
		nlog(LOG_ERR,
		    "nwamd_dlpi_add_link: dlpi_enabnotify(%s) = %s",
		    obj->nwamd_object_name, dlpi_strerror(rc));
		dlpi_close(link->nwamd_link_dhp);
		return;
	}

	rc = pthread_create(&link->nwamd_link_dlpi_thread, NULL,
	    nwamd_dlpi_thread, &link->nwamd_link_dhp);
	if (rc != 0) {
		nlog(LOG_ERR, "nwamd_dlpi_add_link: couldn't create "
		    "dlpi thread for %s: %s", obj->nwamd_object_name,
		    strerror(rc));
		dlpi_close(link->nwamd_link_dhp);
	}
}

/*
 * This function is called when we are no longer interested in receiving
 * notification from state changes on a link.
 */
void
nwamd_dlpi_delete_link(nwamd_object_t obj)
{
	nwamd_ncu_t *ncu = obj->nwamd_object_data;

	nlog(LOG_DEBUG, "nwamd_dlpi_delete_link: ncu %p (%s) type %d",
	    ncu, obj->nwamd_object_name, ncu != NULL ? ncu->ncu_type : -1);

	if (ncu->ncu_link.nwamd_link_dlpi_thread != 0) {
		(void) pthread_cancel(
		    ncu->ncu_link.nwamd_link_dlpi_thread);
		(void) pthread_join(ncu->ncu_link.nwamd_link_dlpi_thread, NULL);
		ncu->ncu_link.nwamd_link_dlpi_thread = 0;
		/* Unset properties before closing */
		nwamd_set_unset_link_properties(ncu, B_FALSE);
	}

	dlpi_close(ncu->ncu_link.nwamd_link_dhp);
	ncu->ncu_link.nwamd_link_dhp = NULL;
}
/*
 * 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.
 */

#include <auth_attr.h>
#include <auth_list.h>
#include <bsm/adt.h>
#include <bsm/adt_event.h>
#include <door.h>
#include <errno.h>
#include <fcntl.h>
#include <libnwam_priv.h>
#include <libuutil.h>
#include <pthread.h>
#include <pwd.h>
#include <stdlib.h>
#include <sys/stat.h>

#include <sys/mman.h>
#include <syslog.h>
#include <unistd.h>

#include "conditions.h"
#include "events.h"
#include "ncp.h"
#include "ncu.h"
#include "objects.h"
#include "util.h"

/*
 * door_if.c
 * This file contains functions which implement the command interface to
 * nwam via the door NWAM_DOOR.  Doors provide a LPC mechanism that allows
 * for threads in one process to cause code to execute in another process.
 * Doors also provide the ability to pass data and file descriptors.  See
 * libdoor(3LIB) for more information.
 *
 * This file exports two functions, nwamd_door_initialize() (which sets up
 * the door) and nwamd_door_fini(), which removes it.
 *
 * It sets up the static routine nwamd_door_switch() to be called when a client
 * calls the door (via door_call(3C)).  The structure nwam_request_t is
 * passed as data and contains data to specify the type of action requested
 * and any data need to meet that request.  A table consisting of entries
 * for each door request, the associated authorization and the function to
 * process that request is used to handle the various requests.
 */

struct nwamd_door_req_entry
{
	int ndre_type;
	char *ndre_auth;
	nwam_error_t (*ndre_fn)(nwamd_door_arg_t *, ucred_t *, struct passwd *);
};

static nwam_error_t nwamd_door_req_event_register(nwamd_door_arg_t *,
	ucred_t *, struct passwd *);
static nwam_error_t nwamd_door_req_event_unregister(nwamd_door_arg_t *,
	ucred_t *, struct passwd *);
static nwam_error_t nwamd_door_req_wlan_scan(nwamd_door_arg_t *,
	ucred_t *, struct passwd *);
static nwam_error_t nwamd_door_req_wlan_scan_results(nwamd_door_arg_t *,
	ucred_t *, struct passwd *);
static nwam_error_t nwamd_door_req_wlan_select(nwamd_door_arg_t *,
	ucred_t *, struct passwd *);
static nwam_error_t nwamd_door_req_wlan_set_key(nwamd_door_arg_t *,
	ucred_t *, struct passwd *);
static nwam_error_t nwamd_door_req_action(nwamd_door_arg_t *,
	ucred_t *, struct passwd *);
static nwam_error_t nwamd_door_req_state(nwamd_door_arg_t *,
	ucred_t *, struct passwd *);
static nwam_error_t nwamd_door_req_priority_group(nwamd_door_arg_t *,
	ucred_t *, struct passwd *);

/*
 * This table defines the set of door commands available, the required
 * authorizations for each command, and the function that carries out
 * each command.
 */
struct nwamd_door_req_entry door_req_table[] =
{

	{ NWAM_REQUEST_TYPE_EVENT_REGISTER, AUTOCONF_READ_AUTH,
	nwamd_door_req_event_register },
	{ NWAM_REQUEST_TYPE_EVENT_UNREGISTER, AUTOCONF_READ_AUTH,
	nwamd_door_req_event_unregister },
	{ NWAM_REQUEST_TYPE_WLAN_SCAN, AUTOCONF_WLAN_AUTH,
	nwamd_door_req_wlan_scan },
	{ NWAM_REQUEST_TYPE_WLAN_SCAN_RESULTS, AUTOCONF_READ_AUTH,
	nwamd_door_req_wlan_scan_results },
	{ NWAM_REQUEST_TYPE_WLAN_SELECT, AUTOCONF_WLAN_AUTH,
	nwamd_door_req_wlan_select },
	{ NWAM_REQUEST_TYPE_WLAN_SET_KEY, AUTOCONF_WLAN_AUTH,
	nwamd_door_req_wlan_set_key },
	/* Requires WRITE, SELECT or WLAN auth depending on action */
	{ NWAM_REQUEST_TYPE_ACTION, NULL, nwamd_door_req_action },
	{ NWAM_REQUEST_TYPE_STATE, AUTOCONF_READ_AUTH,
	nwamd_door_req_state },
	{ NWAM_REQUEST_TYPE_PRIORITY_GROUP, AUTOCONF_READ_AUTH,
	nwamd_door_req_priority_group },
};

int doorfd = -1;

/* ARGSUSED */
static nwam_error_t
nwamd_door_req_event_register(nwamd_door_arg_t *req, ucred_t *ucr,
    struct passwd *pwd)
{
	nwam_error_t err;

	err = nwam_event_queue_init
	    (req->nwda_data.nwdad_register_info.nwdad_name);
	if (err != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_door_req_event_register: "
		    "could not register events for %s",
		    req->nwda_data.nwdad_register_info.nwdad_name);
	}

	return (err);
}

/* ARGSUSED */
static nwam_error_t
nwamd_door_req_event_unregister(nwamd_door_arg_t *req, ucred_t *ucr,
    struct passwd *pwd)
{
	nwam_event_queue_fini(req->nwda_data.nwdad_register_info.nwdad_name);

	return (NWAM_SUCCESS);
}

/* ARGSUSED1 */
static nwam_error_t
nwamd_door_req_wlan_scan(nwamd_door_arg_t *req, ucred_t *ucr,
    struct passwd *pwd)
{
	nlog(LOG_DEBUG,
	    "nwamd_door_req_wlan_scan: processing WLAN scan request: "
	    "link %s", req->nwda_data.nwdad_wlan_info.nwdad_name);

	return (nwamd_wlan_scan(req->nwda_data.nwdad_wlan_info.nwdad_name));
}

/* ARGSUSED */
static nwam_error_t
nwamd_door_req_wlan_scan_results(nwamd_door_arg_t *req, ucred_t *ucr,
    struct passwd *pwd)
{
	nwamd_object_t obj;
	nwamd_ncu_t *ncu;
	nwamd_link_t *link;
	uint_t num_wlans;

	nlog(LOG_DEBUG, "nwamd_door_req_wlan_scan_results: processing WLAN "
	    "scan results request: link %s",
	    req->nwda_data.nwdad_wlan_info.nwdad_name);

	obj = nwamd_ncu_object_find(NWAM_NCU_TYPE_LINK,
	    req->nwda_data.nwdad_wlan_info.nwdad_name);
	if (obj == NULL) {
		nlog(LOG_ERR,
		    "nwamd_door_req_wlan_scan_results: link %s not found",
		    req->nwda_data.nwdad_wlan_info.nwdad_name);
		return (NWAM_ENTITY_NOT_FOUND);
	}

	ncu = obj->nwamd_object_data;
	link = &ncu->ncu_link;
	num_wlans = link->nwamd_link_wifi_scan.nwamd_wifi_scan_curr_num;

	if (num_wlans > 0) {
		(void) memcpy
		    (req->nwda_data.nwdad_wlan_info.nwdad_wlans,
		    link->nwamd_link_wifi_scan.nwamd_wifi_scan_curr,
		    num_wlans * sizeof (nwam_wlan_t));
	}
	req->nwda_data.nwdad_wlan_info.nwdad_num_wlans = num_wlans;
	nlog(LOG_DEBUG,
	    "nwamd_door_req_wlan_scan_results: returning %d scan results",
	    num_wlans);
	nwamd_object_release(obj);

	return (NWAM_SUCCESS);
}

/* ARGSUSED */
static nwam_error_t
nwamd_door_req_wlan_select(nwamd_door_arg_t *req, ucred_t *ucr,
    struct passwd *pwd)
{
	nlog(LOG_DEBUG,
	    "nwamd_door_req_wlan_select: processing WLAN selection : "
	    "link %s ESSID %s , BSSID %s",
	    req->nwda_data.nwdad_wlan_info.nwdad_name,
	    req->nwda_data.nwdad_wlan_info.nwdad_essid,
	    req->nwda_data.nwdad_wlan_info.nwdad_bssid);
	return (nwamd_wlan_select
	    (req->nwda_data.nwdad_wlan_info.nwdad_name,
	    req->nwda_data.nwdad_wlan_info.nwdad_essid,
	    req->nwda_data.nwdad_wlan_info.nwdad_bssid,
	    req->nwda_data.nwdad_wlan_info.nwdad_security_mode,
	    req->nwda_data.nwdad_wlan_info.nwdad_add_to_known_wlans));
}

/* ARGSUSED */
static nwam_error_t
nwamd_door_req_wlan_set_key(nwamd_door_arg_t *req, ucred_t *ucr,
    struct passwd *pwd)
{
	nlog(LOG_DEBUG,
	    "nwamd_door_req_wlan_set_key: processing WLAN key input : "
	    "link %s ESSID %s BSSID %s",
	    req->nwda_data.nwdad_wlan_info.nwdad_name,
	    req->nwda_data.nwdad_wlan_info.nwdad_essid,
	    req->nwda_data.nwdad_wlan_info.nwdad_bssid);
	return (nwamd_wlan_set_key
	    (req->nwda_data.nwdad_wlan_info.nwdad_name,
	    req->nwda_data.nwdad_wlan_info.nwdad_essid,
	    req->nwda_data.nwdad_wlan_info.nwdad_bssid,
	    req->nwda_data.nwdad_wlan_info.nwdad_security_mode,
	    req->nwda_data.nwdad_wlan_info.nwdad_keyslot,
	    req->nwda_data.nwdad_wlan_info.nwdad_key));
}

static nwam_error_t
nwamd_door_req_action(nwamd_door_arg_t *req, ucred_t *ucr, struct passwd *pwd)
{
	char name[NWAM_MAX_NAME_LEN];
	char parent[NWAM_MAX_NAME_LEN];
	nwam_action_t action = req->nwda_data.nwdad_object_action.nwdad_action;
	nwam_object_type_t object_type =
	    req->nwda_data.nwdad_object_action.nwdad_object_type;
	char *obj_type_str  = (char *)nwam_object_type_to_string(object_type);
	nwam_error_t err;

	/* Check for name, parent overrun */
	if (strlcpy(name, req->nwda_data.nwdad_object_action.nwdad_name,
	    sizeof (name)) == NWAM_MAX_NAME_LEN ||
	    strlcpy(parent, req->nwda_data.nwdad_object_action.nwdad_parent,
	    sizeof (parent)) == NWAM_MAX_NAME_LEN)
		return (NWAM_INVALID_ARG);

	/*
	 * Check authorizations against actions.
	 * - ENABLE/DISABLE requires SELECT auth
	 * - ADD/DESTROY/REFRESH on Known WLANs requires WLAN auth
	 * - ADD/DESTROY on other objects requires WRITE auth
	 * - REFRESH on other objects requires either WRITE or SELECT auth
	 */
	if (action == NWAM_ACTION_ENABLE || action == NWAM_ACTION_DISABLE) {
		if (chkauthattr(AUTOCONF_SELECT_AUTH, pwd->pw_name) == 0) {
			nwam_record_audit_event(ucr,
			    action == NWAM_ACTION_ENABLE ?
			    ADT_nwam_enable : ADT_nwam_disable, name,
			    obj_type_str, ADT_FAILURE, ADT_FAIL_VALUE_AUTH);
			nlog(LOG_ERR, "nwamd_door_req_action: "
			    "need %s for %s action", AUTOCONF_SELECT_AUTH,
			    nwam_action_to_string(action));
			return (NWAM_PERMISSION_DENIED);
		}
	} else if (object_type == NWAM_OBJECT_TYPE_KNOWN_WLAN) {
		if (chkauthattr(AUTOCONF_WLAN_AUTH, pwd->pw_name) == 0) {
			nlog(LOG_ERR, "nwamd_door_req_action: "
			    "need %s for %s action on Known WLAN",
			    AUTOCONF_WLAN_AUTH, nwam_action_to_string(action));
			return (NWAM_PERMISSION_DENIED);
		}
	} else if (action == NWAM_ACTION_ADD || action == NWAM_ACTION_DESTROY) {
		if (chkauthattr(AUTOCONF_WRITE_AUTH, pwd->pw_name) == 0) {
			nlog(LOG_ERR, "nwamd_door_req_action: "
			    "need %s for %s action", AUTOCONF_WRITE_AUTH,
			    nwam_action_to_string(action));
			return (NWAM_PERMISSION_DENIED);
		}
	} else if (action == NWAM_ACTION_REFRESH) {
		if (chkauthattr(AUTOCONF_WRITE_AUTH, pwd->pw_name) == 0 &&
		    chkauthattr(AUTOCONF_SELECT_AUTH, pwd->pw_name) == 0) {
			nlog(LOG_ERR, "nwamd_door_req_action: "
			    "need either %s or %s for %s action",
			    AUTOCONF_WRITE_AUTH, AUTOCONF_SELECT_AUTH,
			    nwam_action_to_string(action));
			return (NWAM_PERMISSION_DENIED);
		}
	} else {
		nlog(LOG_ERR, "nwamd_door_req_action: received unknown "
		    "action %d (%s)", action, nwam_action_to_string(action));
		return (NWAM_INVALID_ARG);
	}

	switch (action) {
	case NWAM_ACTION_ENABLE:
	case NWAM_ACTION_DISABLE:
		nwam_record_audit_event(ucr,
		    action == NWAM_ACTION_ENABLE ?
		    ADT_nwam_enable : ADT_nwam_disable, name,
		    obj_type_str, ADT_SUCCESS, ADT_SUCCESS);

		nlog(LOG_DEBUG, "nwamd_door_req_action: %s %s",
		    action == NWAM_ACTION_ENABLE ? "enabling" : "disabling",
		    name);

		switch (object_type) {
		case NWAM_OBJECT_TYPE_ENM:
			err = nwamd_enm_action(name, action);
			break;
		case NWAM_OBJECT_TYPE_LOC:
			err = nwamd_loc_action(name, action);
			break;
		case NWAM_OBJECT_TYPE_NCU:
			err = nwamd_ncu_action(name, parent, action);
			break;
		case NWAM_OBJECT_TYPE_NCP:
			if (action == NWAM_ACTION_DISABLE) {
				nlog(LOG_ERR, "nwamd_door_req_action: "
				    "NCPs cannot be disabled");
				err = NWAM_INVALID_ARG;
			} else {
				err = nwamd_ncp_action(name, action);
			}
			break;
		default:
			nlog(LOG_ERR, "nwamd_door_req_action: received invalid "
			    "object type %d (%s)", object_type,
			    nwam_object_type_to_string(object_type));
			return (NWAM_INVALID_ARG);
		}
		break;

	case NWAM_ACTION_ADD:
	case NWAM_ACTION_REFRESH:
		/*
		 * Called whenever an object is committed in the library.
		 * Reread that committed object into nwamd.
		 */
		nlog(LOG_DEBUG, "door_switch: refreshing %s", name);

		switch (object_type) {
		case NWAM_OBJECT_TYPE_ENM:
			err = nwamd_enm_action(name, action);
			break;
		case NWAM_OBJECT_TYPE_LOC:
			err = nwamd_loc_action(name, action);
			break;
		case NWAM_OBJECT_TYPE_KNOWN_WLAN:
			err = nwamd_known_wlan_action(name, action);
			break;
		case NWAM_OBJECT_TYPE_NCU:
			err = nwamd_ncu_action(name, parent, action);
			break;
		case NWAM_OBJECT_TYPE_NCP:
			err = nwamd_ncp_action(name, action);
			break;
		default:
			nlog(LOG_ERR, "nwamd_door_req_action: received invalid "
			    "object type %d (%s)", object_type,
			    nwam_object_type_to_string(object_type));
			err = NWAM_INVALID_ARG;
			break;
		}
		break;

	case NWAM_ACTION_DESTROY:
		/* Object was destroyed, remove from nwamd */
		nlog(LOG_DEBUG, "door_switch: removing %s", name);

		switch (object_type) {
		case NWAM_OBJECT_TYPE_ENM:
			err = nwamd_enm_action(name, NWAM_ACTION_DESTROY);
			break;
		case NWAM_OBJECT_TYPE_LOC:
			err = nwamd_loc_action(name, NWAM_ACTION_DESTROY);
			break;
		case NWAM_OBJECT_TYPE_KNOWN_WLAN:
			err = nwamd_known_wlan_action(name,
			    NWAM_ACTION_DESTROY);
			break;
		case NWAM_OBJECT_TYPE_NCU:
			err = nwamd_ncu_action(name, parent,
			    NWAM_ACTION_DESTROY);
			break;
		case NWAM_OBJECT_TYPE_NCP:
			(void) pthread_mutex_lock(&active_ncp_mutex);
			if (strcmp(name, active_ncp) == 0) {
				nlog(LOG_ERR, "nwamd_door_req_action: %s is "
				    "active, cannot destroy", parent);
				err = NWAM_ENTITY_IN_USE;
			} else {
				err = nwamd_ncp_action(name,
				    NWAM_ACTION_DESTROY);
			}
			(void) pthread_mutex_unlock(&active_ncp_mutex);
			break;
		default:
			nlog(LOG_ERR, "nwamd_door_req_action: received invalid "
			    "object type %d (%s)", object_type,
			    nwam_object_type_to_string(object_type));
			err = NWAM_INVALID_ARG;
			break;
		}
		break;

	default:
		nlog(LOG_ERR, "nwamd_door_req_action: received unknown "
		    "action %d (%s)", action, nwam_action_to_string(action));
		err = NWAM_INVALID_ARG;
		break;
	}

	if (err == NWAM_SUCCESS) {
		/*
		 * At this point, we've successfully carried out an action.
		 * Configuration may have changed, so we need to recheck
		 * conditions, however we want to avoid a flurry of condition
		 * check events, so we enqueue a triggered condition check
		 * if none is due in the next few seconds.
		 */
		nwamd_create_triggered_condition_check_event(NEXT_FEW_SECONDS);
	} else {
		nlog(LOG_ERR, "nwamd_door_req_action: could not carry out "
		    "%s action on %s: %s", nwam_action_to_string(action),
		    name, nwam_strerror(err));
	}

	return (err);
}

/* ARGSUSED */
static nwam_error_t
nwamd_door_req_state(nwamd_door_arg_t *req, ucred_t *ucr, struct passwd *pwd)
{
	char name[NWAM_MAX_NAME_LEN];
	nwamd_object_t obj;
	nwam_object_type_t object_type =
	    req->nwda_data.nwdad_object_state.nwdad_object_type;
	boolean_t is_active = B_FALSE;

	/* Check for name, parent overrun */
	if (strlcpy(name, req->nwda_data.nwdad_object_state.nwdad_name,
	    sizeof (name)) == NWAM_MAX_NAME_LEN)
		return (NWAM_INVALID_ARG);

	switch (object_type) {
	case NWAM_OBJECT_TYPE_NCP:
		(void) pthread_mutex_lock(&active_ncp_mutex);
		is_active = (strcmp(active_ncp, name) == 0);
		(void) pthread_mutex_unlock(&active_ncp_mutex);
		if (is_active) {
			req->nwda_data.nwdad_object_state.nwdad_state =
			    NWAM_STATE_ONLINE;
			req->nwda_data.nwdad_object_state.
			    nwdad_aux_state = NWAM_AUX_STATE_ACTIVE;
			nlog(LOG_DEBUG,
			    "nwamd_door_req_state: NCP %s is active", name);
		} else {
			req->nwda_data.nwdad_object_state.nwdad_state =
			    NWAM_STATE_DISABLED;
			req->nwda_data.nwdad_object_state.
			    nwdad_aux_state =
			    NWAM_AUX_STATE_MANUAL_DISABLE;
			nlog(LOG_DEBUG, "nwamd_door_req_state: "
			    "NCP %s is inactive", name);
		}
		break;

	case NWAM_OBJECT_TYPE_LOC:
	case NWAM_OBJECT_TYPE_NCU:
	case NWAM_OBJECT_TYPE_ENM:
		obj = nwamd_object_find(object_type, name);
		if (obj == NULL) {
			nlog(LOG_ERR, "nwamd_door_req_state: %s %s not found",
			    nwam_object_type_to_string(object_type), name);
			return (NWAM_ENTITY_NOT_FOUND);
		}
		nlog(LOG_DEBUG, "nwamd_door_req_state: %s %s is %s",
		    nwam_object_type_to_string(object_type), name,
		    nwam_state_to_string(obj->nwamd_object_state));
		req->nwda_data.nwdad_object_state.nwdad_state =
		    obj->nwamd_object_state;
		req->nwda_data.nwdad_object_state.nwdad_aux_state =
		    obj->nwamd_object_aux_state;
		nwamd_object_release(obj);
		break;

	default:
		nlog(LOG_ERR, "nwamd_door_req_state: received invalid "
		    "object type %d (%s)", object_type,
		    nwam_object_type_to_string(object_type));
		req->nwda_status = NWAM_REQUEST_STATUS_UNKNOWN;
		return (NWAM_INVALID_ARG);
	}

	return (NWAM_SUCCESS);
}

/* ARGSUSED */
static nwam_error_t
nwamd_door_req_priority_group(nwamd_door_arg_t *req, ucred_t *ucr,
    struct passwd *pwd)
{
	(void) pthread_mutex_lock(&active_ncp_mutex);
	nlog(LOG_DEBUG, "nwamd_door_req_priority_group: "
	    "retrieving active priority-group: %d",
	    current_ncu_priority_group);
	req->nwda_data.nwdad_priority_group_info.nwdad_priority =
	    current_ncu_priority_group;
	(void) pthread_mutex_unlock(&active_ncp_mutex);

	return (NWAM_SUCCESS);
}

/* ARGSUSED */
static void
nwamd_door_switch(void *cookie, char *argp, size_t arg_size, door_desc_t *dp,
    uint_t n_desc)
{
	nwamd_door_arg_t *req;
	ucred_t *ucr = NULL;
	uid_t uid;
	struct passwd *pwd = NULL;
	boolean_t found = B_FALSE;
	int i;

	/* LINTED E_BAD_PTR_CAST_ALIGN */
	req = (nwamd_door_arg_t *)argp;
	req->nwda_error = NWAM_SUCCESS;

	if (door_ucred(&ucr) != 0) {
		nlog(LOG_ERR, "nwamd_door_switch: door_ucred failed: %s",
		    strerror(errno));
		req->nwda_error = NWAM_ERROR_INTERNAL;
		req->nwda_status = NWAM_REQUEST_STATUS_FAILED;
		goto done;
	}
	uid = ucred_getruid(ucr);

	if ((pwd = getpwuid(uid)) == NULL) {
		nlog(LOG_ERR, "nwamd_door_switch: getpwuid failed: %s",
		    strerror(errno));
		endpwent();
		req->nwda_error = NWAM_ERROR_INTERNAL;
		req->nwda_status = NWAM_REQUEST_STATUS_FAILED;
		goto done;
	}

	/*
	 * Find door request entry in table, check auths and call the function
	 * handling the request.
	 */
	for (i = 0;
	    i < sizeof (door_req_table) / sizeof (struct nwamd_door_req_entry);
	    i++) {
		if (req->nwda_type != door_req_table[i].ndre_type)
			continue;

		found = B_TRUE;

		if (door_req_table[i].ndre_auth != NULL &&
		    chkauthattr(door_req_table[i].ndre_auth,
		    pwd->pw_name) == 0) {
			nlog(LOG_ERR,
			    "nwamd_door_switch: need %s for request type %d",
			    door_req_table[i].ndre_auth, req->nwda_type);
			req->nwda_error = NWAM_PERMISSION_DENIED;
			break;
		}
		req->nwda_error = door_req_table[i].ndre_fn(req, ucr, pwd);
		break;
	}
	if (!found) {
		nlog(LOG_ERR,
		    "nwamd_door_switch: received unknown request type %d",
		    req->nwda_type);
		req->nwda_status = NWAM_REQUEST_STATUS_UNKNOWN;
	} else {
		if (req->nwda_error == NWAM_SUCCESS)
			req->nwda_status = NWAM_REQUEST_STATUS_OK;
		else
			req->nwda_status = NWAM_REQUEST_STATUS_FAILED;
	}

done:
	ucred_free(ucr);
	endpwent();

	if (door_return((char *)req, sizeof (nwamd_door_arg_t), NULL, 0)
	    == -1) {
		nlog(LOG_ERR, "door_switch: type %d door_return failed: %s",
		    req->nwda_type, strerror(errno));
	}
}

/*
 * We initialize the nwamd door here.  Failure to have this happen is critical
 * to the daemon so we log a message and pass up notice to the caller who
 * will most likely abort trying to start.  This routine is meant to only
 * be called once.
 */
void
nwamd_door_init(void)
{
	const int door_mode = 0644;
	struct stat buf;

	if ((doorfd = door_create(nwamd_door_switch, NULL,
	    DOOR_NO_CANCEL | DOOR_REFUSE_DESC)) == -1)
		pfail("Unable to create door: %s", strerror(errno));

	if (stat(NWAM_DOOR, &buf) < 0) {
		int nwam_door_fd;

		if ((nwam_door_fd = creat(NWAM_DOOR, door_mode)) < 0) {
			int err = errno;
			(void) door_revoke(doorfd);
			doorfd = -1;
			pfail("Couldn't create door: %s", strerror(err));
		}
		(void) close(nwam_door_fd);
	} else {
		if (buf.st_mode != door_mode) {
			if (chmod(NWAM_DOOR, door_mode) == -1) {
				nlog(LOG_ERR, "couldn't change mode of %s: %s",
				    NWAM_DOOR, strerror(errno));
			}
		}
	}
	/* cleanup anything hanging around from a previous invocation */
	(void) fdetach(NWAM_DOOR);

	/* Place our door in the file system so that others can find us. */
	if (fattach(doorfd, NWAM_DOOR) < 0) {
		int err = errno;
		(void) door_revoke(doorfd);
		doorfd = -1;
		pfail("Couldn't attach door: %s", strerror(err));
	}
}

void
nwamd_door_fini(void)
{
	if (doorfd != -1) {
		nlog(LOG_DEBUG, "nwamd_door_fini: closing door");
		(void) door_revoke(doorfd);
		doorfd = -1;
	}
	(void) unlink(NWAM_DOOR);
}
/*
 * 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.
 */

#include <arpa/inet.h>
#include <errno.h>
#include <inet/ip.h>
#include <libdladm.h>
#include <libdllink.h>
#include <libdlwlan.h>
#include <libscf.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>

#include <libnwam.h>
#include "conditions.h"
#include "events.h"
#include "objects.h"
#include "util.h"

/*
 * enm.c - contains routines which handle ENM (external network modifier)
 * abstraction.  ENMs represent scripts or services that can be activated either
 * manually or in response to network conditions.
 */

#define	CTRUN	"/usr/bin/ctrun"

static int
enm_create_init_fini_event(nwam_enm_handle_t enmh, void *data)
{
	boolean_t *init = data;
	char *name;
	nwamd_event_t enm_event;

	if (nwam_enm_get_name(enmh, &name) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "enm_init_fini: could not get enm name");
		return (0);
	}

	enm_event = nwamd_event_init(*init ?
	    NWAM_EVENT_TYPE_OBJECT_INIT : NWAM_EVENT_TYPE_OBJECT_FINI,
	    NWAM_OBJECT_TYPE_ENM, 0, name);
	if (enm_event != NULL)
		nwamd_event_enqueue(enm_event);
	free(name);

	return (0);
}

/*
 * Walk all ENMs, creating init events for each.
 */
void
nwamd_init_enms(void)
{
	boolean_t init = B_TRUE;

	(void) nwam_walk_enms(enm_create_init_fini_event, &init, 0, NULL);
}

/*
 * Walk all ENMs, creating fini events for each.
 */
void
nwamd_fini_enms(void)
{
	boolean_t init = B_FALSE;

	(void) nwam_walk_enms(enm_create_init_fini_event, &init, 0, NULL);
}

static boolean_t
enm_is_enabled(nwam_enm_handle_t enmh)
{
	nwam_value_t enabledval;
	boolean_t enabled = B_FALSE;

	if (nwam_enm_get_prop_value(enmh, NWAM_ENM_PROP_ENABLED,
	    &enabledval) != NWAM_SUCCESS) {
		/* It's legal for a conditional ENM to not specify "enabled" */
		return (B_FALSE);
	}
	if (nwam_value_get_boolean(enabledval, &enabled) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "enm_is_enabled: could not retrieve "
		    "enabled value");
	}
	nwam_value_free(enabledval);
	return (enabled);
}

static int64_t
enm_get_activation_mode(nwam_enm_handle_t enmh)
{
	uint64_t activation;
	int64_t ret;
	nwam_value_t activationval;

	if (nwam_enm_get_prop_value(enmh, NWAM_ENM_PROP_ACTIVATION_MODE,
	    &activationval)  != NWAM_SUCCESS) {
		nlog(LOG_ERR, "enm_get_activation_mode: could not retrieve "
		    "activation mode value");
		return (-1);
	}
	if (nwam_value_get_uint64(activationval, &activation) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "enm_get_activation_mode: could not retrieve "
		    "activation mode value");
		ret = -1;
	} else {
		ret = activation;
	}
	nwam_value_free(activationval);

	return (ret);
}

static void *
nwamd_enm_activate_deactivate_thread(void *arg)
{
	char *object_name = arg;
	nwamd_object_t object;
	nwam_enm_handle_t enmh;
	nwam_value_t scriptval = NULL;
	nwam_state_t state;
	nwam_aux_state_t aux_state;
	char *script, *copy = NULL;
	const char **argv = NULL;
	boolean_t going_online, disable_succeeded = B_FALSE;
	int ret;

	object = nwamd_object_find(NWAM_OBJECT_TYPE_ENM, object_name);
	if (object == NULL) {
		nlog(LOG_ERR, "nwamd_enm_activate_deactivate_thread: "
		    "could not find enm %s", object_name);
		goto done;
	}
	enmh = object->nwamd_object_handle;

	going_online =
	    (object->nwamd_object_state == NWAM_STATE_OFFLINE_TO_ONLINE);
	/*
	 * We're starting if current state is offline* and stopping otherwise.
	 */
	if (nwam_enm_get_prop_value(enmh,
	    going_online ? NWAM_ENM_PROP_START : NWAM_ENM_PROP_STOP,
	    &scriptval) != NWAM_SUCCESS ||
	    nwam_value_get_string(scriptval, &script) != NWAM_SUCCESS) {
		/*
		 * If we're stopping, it's not an error for no script to
		 * be specified.
		 */
		nlog(going_online ? LOG_ERR : LOG_DEBUG,
		    "nwamd_enm_activate_deactivate_thread: "
		    "no script specified for enm %s", object_name);
		if (going_online) {
			state = NWAM_STATE_MAINTENANCE;
			aux_state = NWAM_AUX_STATE_METHOD_MISSING;
		} else {
			disable_succeeded = B_TRUE;
		}
	} else {
		char *lasts;
		const char **newargv;
		int i = 0;
		struct timeval now;

		nlog(LOG_DEBUG, "nwamd_enm_activate_deactivate_thread: "
		    "running script %s for enm %s", script, object_name);

		/*
		 * The script may take a number of arguments. We need to
		 * create a string array consisting of the wrapper command
		 * (ctrun), ENM script name, arguments and NULL array
		 * terminator.  Start with an array of size equal to the
		 * string length (since the number of arguments will always
		 * be less than this) and shrink array to the actual number
		 * of arguments when we have parsed the string.
		 */
		if ((copy = strdup(script)) == NULL ||
		    (argv = calloc(strlen(script), sizeof (char *))) == NULL) {
			ret = 1;
			goto err;
		}
		argv[i++] = CTRUN;
		argv[i++] = strtok_r(copy, " ", &lasts);
		if (argv[1] == NULL) {
			ret = 1;
			goto err;
		}

		for (; (argv[i] = strtok_r(NULL, " ", &lasts)) != NULL; i++) {}

		newargv = realloc(argv, (i + 1) * sizeof (char *));
		argv = newargv;

		/* Store the current time as the time the script began */
		(void) gettimeofday(&now, NULL);
		object->nwamd_script_time = now;

		/*
		 * Release the object so that it is not blocked while the
		 * script is running.
		 */
		nwamd_object_release(object);

		ret = nwamd_start_childv(CTRUN, argv);

		/*
		 * Find the object again, now that the script has finished
		 * running.  Check if this ENM was re-read during that time by
		 * comparing the object's script time with the one from above.
		 */
		object = nwamd_object_find(NWAM_OBJECT_TYPE_ENM, object_name);
		if (object == NULL) {
			nlog(LOG_ERR, "nwamd_enm_activate_deactivate_thread: "
			    "could not find enm %s after running script",
			    object_name);
			goto done;
		}

		if (object->nwamd_script_time.tv_sec != now.tv_sec ||
		    object->nwamd_script_time.tv_usec != now.tv_usec) {
			nlog(LOG_INFO, "nwamd_enm_activate_deactivate_thread: "
			    "enm %s has been refreshed, nothing to do",
			    object_name);
			nwamd_object_release(object);
			goto done;
		}
		(void) gettimeofday(&object->nwamd_script_time, NULL);

err:
		/*
		 * If script execution fails and we're not destroying the
		 * object, go to maintenance.
		 */
		if (ret != 0) {
			nlog(LOG_ERR, "nwamd_enm_activate_deactivate_thread: "
			    "execution of '%s' failed for enm %s",
			    script, object_name);
			if (object->nwamd_object_aux_state !=
			    NWAM_AUX_STATE_UNINITIALIZED) {
				state = NWAM_STATE_MAINTENANCE;
				aux_state = NWAM_AUX_STATE_METHOD_FAILED;
			} else {
				state = NWAM_STATE_UNINITIALIZED;
				aux_state = NWAM_AUX_STATE_UNINITIALIZED;
			}
		} else {
			if (going_online) {
				state = NWAM_STATE_ONLINE;
				aux_state = NWAM_AUX_STATE_ACTIVE;
			} else {
				disable_succeeded = B_TRUE;
			}
		}
	}

	if (disable_succeeded) {
		/*
		 * If aux state is "manual disable", we know
		 * this was a disable request, otherwise it was
		 * _fini request or a condition satisfaction
		 * failure.
		 */
		switch (object->nwamd_object_aux_state) {
		case NWAM_AUX_STATE_MANUAL_DISABLE:
			state = NWAM_STATE_DISABLED;
			aux_state = NWAM_AUX_STATE_MANUAL_DISABLE;
			break;
		case NWAM_AUX_STATE_UNINITIALIZED:
			state = NWAM_STATE_UNINITIALIZED;
			aux_state = NWAM_AUX_STATE_UNINITIALIZED;
			break;
		default:
			state = NWAM_STATE_OFFLINE;
			aux_state = NWAM_AUX_STATE_CONDITIONS_NOT_MET;
			break;
		}
	}

	/* If state/aux state are uninitialized/unintialized, destroy the ENM */
	if (state == NWAM_STATE_UNINITIALIZED &&
	    aux_state == NWAM_AUX_STATE_UNINITIALIZED) {
		object->nwamd_object_state = state;
		object->nwamd_object_aux_state = aux_state;
		(void) nwamd_object_release_and_destroy_after_preserve(object);
	} else {
		nwamd_object_set_state(NWAM_OBJECT_TYPE_ENM,
		    object->nwamd_object_name, state, aux_state);
		(void) nwamd_object_release_after_preserve(object);
	}

done:
	/* object_name was malloc() before this thread was created, free() it */
	free(object_name);
	free(argv);
	free(copy);
	nwam_value_free(scriptval);
	return (NULL);
}

/*
 * Run start/stop method for ENM in a separate thread.  The object lock is not
 * held across threads, so we duplicate the object name for the method
 * execution thread.  Returns true if thread is successfully launched.
 */
boolean_t
nwamd_enm_run_method(nwamd_object_t object)
{
	char *name;
	pthread_t script;

	/*
	 * Launch separate thread to wait for execution of script
	 * to complete.  Do not hold object lock across threads.
	 */
	if ((name = strdup(object->nwamd_object_name)) == NULL) {
		nlog(LOG_ERR, "nwamd_enm_run_method: %s: out of memory",
		    object->nwamd_object_name);
		return (B_FALSE);
	}

	if (pthread_create(&script, NULL,
	    nwamd_enm_activate_deactivate_thread, name) != 0) {
		nlog(LOG_ERR, "nwamd_enm_run_method: could not create "
		    "enm script thread for %s", name);
		free(name);
		return (B_FALSE);
	}
	/* "name" will be freed by the newly-created thread. */

	/* detach thread so that it doesn't become a zombie */
	(void) pthread_detach(script);

	return (B_TRUE);
}

/*
 * Activate the ENM, either in response to an enable event or conditions
 * being satisfied.
 */
static void
nwamd_enm_activate(const char *object_name)
{
	nwamd_object_t object;
	nwam_value_t fmrival;
	char *fmri, *smf_state;
	int ret;
	nwam_enm_handle_t enmh;
	nwam_state_t state;
	nwam_aux_state_t aux_state;
	nwam_error_t err;
	boolean_t ran_method = B_FALSE;

	object = nwamd_object_find(NWAM_OBJECT_TYPE_ENM, object_name);
	if (object == NULL) {
		nlog(LOG_ERR, "nwamd_enm_activate: could not find enm %s",
		    object_name);
		return;
	}
	state = object->nwamd_object_state;
	aux_state = object->nwamd_object_aux_state;
	enmh = object->nwamd_object_handle;

	nlog(LOG_DEBUG, "nwamd_enm_activate: activating enm %s",
	    object->nwamd_object_name);

	err = nwam_enm_get_prop_value(enmh, NWAM_ENM_PROP_FMRI, &fmrival);
	switch (err) {
	case NWAM_SUCCESS:

		if (nwam_value_get_string(fmrival, &fmri) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "nwamd_enm_activate: could not retrieve "
			    "fmri string for enm %s",
			    object->nwamd_object_name);
			nwam_value_free(fmrival);
			state = NWAM_STATE_MAINTENANCE;
			aux_state = NWAM_AUX_STATE_INVALID_CONFIG;
			break;
		}

		if ((smf_state = smf_get_state(fmri)) == NULL) {
			nlog(LOG_ERR, "nwamd_enm_activate: invalid fmri %s "
			    "for enm %s", fmri, object->nwamd_object_name);
			nwam_value_free(fmrival);
			state = NWAM_STATE_MAINTENANCE;
			aux_state = NWAM_AUX_STATE_INVALID_CONFIG;
			break;
		}

		nlog(LOG_DEBUG, "nwamd_enm_activate: activating %s for enm %s",
		    fmri, object->nwamd_object_name);

		if (strcmp(smf_state, SCF_STATE_STRING_ONLINE) == 0)
			ret = smf_restart_instance(fmri);
		else if (strcmp(smf_state, SCF_STATE_STRING_OFFLINE) == 0)
			ret = smf_restart_instance(fmri);
		else if (strcmp(smf_state, SCF_STATE_STRING_DISABLED) == 0)
			ret = smf_enable_instance(fmri, SMF_TEMPORARY);
		else
			ret = smf_restore_instance(fmri);

		if (ret == 0) {
			state = NWAM_STATE_ONLINE;
			aux_state = NWAM_AUX_STATE_ACTIVE;
		} else {
			nlog(LOG_ERR, "nwamd_enm_activate: failed to enable "
			    "fmri %s for enm %s", fmri,
			    object->nwamd_object_name);
			state = NWAM_STATE_MAINTENANCE;
			aux_state = NWAM_AUX_STATE_METHOD_FAILED;
		}
		free(smf_state);
		nwam_value_free(fmrival);
		break;
	default:
		/*
		 * Must be a method-based ENM with start (and stop) script(s).
		 */
		if (!nwamd_enm_run_method(object)) {
			/* Could not launch method execution thread */
			state = NWAM_STATE_MAINTENANCE;
			aux_state = NWAM_AUX_STATE_METHOD_FAILED;
		} else {
			ran_method = B_TRUE;
		}
		break;
	}

	if (state != object->nwamd_object_state ||
	    aux_state != object->nwamd_object_aux_state) {
		nwamd_object_set_state(NWAM_OBJECT_TYPE_ENM,
		    object->nwamd_object_name, state, aux_state);
	}

	/*
	 * If the method thread was created, we drop the lock to the ENM
	 * object without decreasing the reference count, ensuring it will not
	 * be destroyed until method execution has completed.
	 */
	if (ran_method) {
		nwamd_object_release_and_preserve(object);
	} else {
		nwamd_object_release(object);
	}
}

/* Deactivates the ENM. */
static void
nwamd_enm_deactivate(const char *object_name)
{
	nwamd_object_t object;
	nwam_enm_handle_t enmh;
	nwam_value_t fmrival;
	char *fmri, *smf_state;
	int ret;
	nwam_state_t state;
	nwam_aux_state_t aux_state;
	boolean_t destroying = B_FALSE;

	object = nwamd_object_find(NWAM_OBJECT_TYPE_ENM, object_name);
	if (object == NULL) {
		nlog(LOG_ERR, "nwamd_enm_deactivate: could not find enm %s",
		    object_name);
		return;
	}

	state = object->nwamd_object_state;
	aux_state = object->nwamd_object_aux_state;
	enmh = object->nwamd_object_handle;
	state = object->nwamd_object_state;
	/* If destroying, we don't care about method failure/config err */
	destroying = (aux_state == NWAM_AUX_STATE_UNINITIALIZED);

	nlog(LOG_DEBUG, "nwamd_enm_deactivate: deactivating enm %s",
	    object->nwamd_object_name);

	if (nwam_enm_get_prop_value(enmh, NWAM_ENM_PROP_FMRI, &fmrival)
	    != NWAM_SUCCESS) {
		/*
		 * Must be a method-based ENM with start (and stop) script(s).
		 * Script execution thread will take care of the rest.
		 * If the method thread was created, we drop the lock to the ENM
		 * object without decreasing the reference count, ensuring it
		 * will not be destroyed until method execution has completed.
		 */
		if (nwamd_enm_run_method(object)) {
			nwamd_object_release_and_preserve(object);
			return;
		}
		/* Could not launch method execution thread */
		if (!destroying) {
			state = NWAM_STATE_MAINTENANCE;
			aux_state = NWAM_AUX_STATE_METHOD_FAILED;
		}
	} else {
		if (nwam_value_get_string(fmrival, &fmri) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "nwamd_enm_deactivate: could not "
			    "retrieve fmri string for enm %s",
			    object->nwamd_object_name);
			if (!destroying) {
				state = NWAM_STATE_MAINTENANCE;
				aux_state = NWAM_AUX_STATE_INVALID_CONFIG;
			}
		} else {
			if ((smf_state = smf_get_state(fmri)) == NULL) {
				nlog(LOG_ERR, "nwamd_enm_deactivate: invalid "
				    "fmri %s for enm %s", fmri,
				    object->nwamd_object_name);
				nwam_value_free(fmrival);
				if (!destroying) {
					state = NWAM_STATE_MAINTENANCE;
					aux_state =
					    NWAM_AUX_STATE_INVALID_CONFIG;
				}
				goto done;
			}
			free(smf_state);

			nlog(LOG_DEBUG, "nwamd_enm_deactivate: deactivating %s "
			    "for enm %s", fmri, object->nwamd_object_name);

			ret = smf_disable_instance(fmri, SMF_TEMPORARY);

			if (ret != 0) {
				nlog(LOG_ERR, "nwamd_enm_deactivate: "
				    "smf_disable_instance(%s) failed for "
				    "enm %s: %s", fmri,
				    object->nwamd_object_name,
				    scf_strerror(scf_error()));
				if (!destroying) {
					state = NWAM_STATE_MAINTENANCE;
					aux_state =
					    NWAM_AUX_STATE_METHOD_FAILED;
				}
			}
		}
		nwam_value_free(fmrival);
	}
done:
	if (state == object->nwamd_object_state &&
	    aux_state == object->nwamd_object_aux_state) {
		/*
		 * If aux state is "manual disable", we know
		 * this was a disable request, otherwise it was
		 * a _fini request or a condition satisfaction
		 * failure.
		 */
		switch (object->nwamd_object_aux_state) {
		case NWAM_AUX_STATE_MANUAL_DISABLE:
			state = NWAM_STATE_DISABLED;
			aux_state = NWAM_AUX_STATE_MANUAL_DISABLE;
			break;
		case NWAM_AUX_STATE_UNINITIALIZED:
			state = NWAM_STATE_UNINITIALIZED;
			aux_state = NWAM_AUX_STATE_UNINITIALIZED;
			break;
		default:
			state = NWAM_STATE_OFFLINE;
			aux_state = NWAM_AUX_STATE_CONDITIONS_NOT_MET;
			break;
		}
	}

	/* Only change state if we aren't destroying the ENM */
	if (!destroying && (state != object->nwamd_object_state ||
	    aux_state != object->nwamd_object_aux_state)) {
		nwamd_object_set_state(NWAM_OBJECT_TYPE_ENM,
		    object->nwamd_object_name, state, aux_state);
	}

	/* If state/aux state are uninitialized/unintialized, destroy the ENM */
	if (state == NWAM_STATE_UNINITIALIZED &&
	    aux_state == NWAM_AUX_STATE_UNINITIALIZED) {
		(void) nwamd_object_release_and_destroy(object);
	} else {
		(void) nwamd_object_release(object);
	}
}

/*
 * Determine whether an ENM should be (de)activated.
 */
/* ARGSUSED1 */
static int
nwamd_enm_check(nwamd_object_t object, void *data)
{
	nwam_enm_handle_t enmh;
	nwam_value_t conditionval;
	int64_t eactivation;
	boolean_t enabled, satisfied;
	char **conditions;
	nwam_state_t state;
	uint_t nelem;

	state = object->nwamd_object_state;

	enmh = object->nwamd_object_handle;

	eactivation = enm_get_activation_mode(enmh);
	if (eactivation == -1)
		return (0);

	switch (eactivation) {
	case NWAM_ACTIVATION_MODE_MANUAL:
		enabled = enm_is_enabled(enmh);

		if (enabled) {
			nlog(LOG_DEBUG, "nwamd_enm_check: %s is enabled",
			    object->nwamd_object_name);
			switch (state) {
			case NWAM_STATE_ONLINE:
			case NWAM_STATE_MAINTENANCE:
				/* Do nothing */
				break;
			default:
				if (nwamd_enm_action(object->nwamd_object_name,
				    NWAM_ACTION_ENABLE) != 0) {
					nlog(LOG_ERR, "nwamd_enm_check: "
					    "enable failed for enm %s",
					    object->nwamd_object_name);
				}
				break;
			}
		} else {
			nlog(LOG_DEBUG, "nwamd_enm_check: %s is disabled",
			    object->nwamd_object_name);
			switch (state) {
			case NWAM_STATE_ONLINE:
				if (nwamd_enm_action(object->nwamd_object_name,
				    NWAM_ACTION_DISABLE) != 0) {
					nlog(LOG_ERR, "nwamd_enm_check: "
					    "disable failed for enm %s",
					    object->nwamd_object_name);
				}
				break;
			case NWAM_STATE_MAINTENANCE:
				/* Do nothing */
				break;
			case NWAM_STATE_DISABLED:
				/* Do nothing */
				break;
			default:
				nwamd_object_set_state(NWAM_OBJECT_TYPE_ENM,
				    object->nwamd_object_name,
				    NWAM_STATE_DISABLED,
				    NWAM_AUX_STATE_MANUAL_DISABLE);
				break;
			}
		}
		break;

	case NWAM_ACTIVATION_MODE_CONDITIONAL_ANY:
	case NWAM_ACTIVATION_MODE_CONDITIONAL_ALL:
		if (nwam_enm_get_prop_value(enmh,
		    NWAM_ENM_PROP_CONDITIONS, &conditionval) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "nwamd_enm_check: could not retrieve "
			    "condition value");
			break;
		}
		if (nwam_value_get_string_array(conditionval,
		    &conditions, &nelem) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "nwamd_enm_check: could not retrieve "
			    "condition value");
			nwam_value_free(conditionval);
			break;
		}
		satisfied = nwamd_check_conditions((uint64_t)eactivation,
		    conditions, nelem);

		nlog(LOG_DEBUG, "nwamd_enm_check: conditions for enm %s "
		    "%s satisfied", object->nwamd_object_name,
		    satisfied ? "is" : "is not");
		if (state != NWAM_STATE_ONLINE && satisfied) {
			nwamd_object_set_state(NWAM_OBJECT_TYPE_ENM,
			    object->nwamd_object_name,
			    NWAM_STATE_OFFLINE_TO_ONLINE,
			    NWAM_AUX_STATE_METHOD_RUNNING);
		}
		if (state == NWAM_STATE_ONLINE && !satisfied) {
			nwamd_object_set_state(NWAM_OBJECT_TYPE_ENM,
			    object->nwamd_object_name,
			    NWAM_STATE_ONLINE_TO_OFFLINE,
			    NWAM_AUX_STATE_CONDITIONS_NOT_MET);
		}
		nwam_value_free(conditionval);
		break;

	}
	return (0);
}

void
nwamd_enm_check_conditions(void)
{
	(void) nwamd_walk_objects(NWAM_OBJECT_TYPE_ENM, nwamd_enm_check, NULL);
}

int
nwamd_enm_action(const char *enm, nwam_action_t action)
{
	nwamd_event_t event = nwamd_event_init_object_action
	    (NWAM_OBJECT_TYPE_ENM, enm, NULL, action);
	if (event == NULL)
		return (1);
	nwamd_event_enqueue(event);
	return (0);
}

/*
 * Event handling functions.
 */

/* Handle ENM initialization/refresh event */
void
nwamd_enm_handle_init_event(nwamd_event_t event)
{
	nwamd_object_t object;
	nwam_enm_handle_t enmh;
	nwam_error_t err;
	boolean_t manual_disabled = B_FALSE;

	if ((err = nwam_enm_read(event->event_object, 0, &enmh))
	    != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_enm_handle_init_event: could not "
		    "read object '%s': %s", event->event_object,
		    nwam_strerror(err));
		nwamd_event_do_not_send(event);
		return;
	}
	if ((object = nwamd_object_find(NWAM_OBJECT_TYPE_ENM,
	    event->event_object)) != NULL) {
		nwam_enm_free(object->nwamd_object_handle);
		object->nwamd_object_handle = enmh;
	} else {
		object = nwamd_object_init(NWAM_OBJECT_TYPE_ENM,
		    event->event_object, enmh, NULL);
		object->nwamd_object_state = NWAM_STATE_OFFLINE;
		object->nwamd_object_aux_state =
		    NWAM_AUX_STATE_CONDITIONS_NOT_MET;
	}
	/* (Re)set script time to now as the object has just been (re)read */
	(void) gettimeofday(&object->nwamd_script_time, NULL);

	manual_disabled = (enm_get_activation_mode(enmh) ==
	    NWAM_ACTIVATION_MODE_MANUAL && !enm_is_enabled(enmh));

	/*
	 * If this ENM is ONLINE, and not manual and disabled (since in
	 * that case it was online but we've just set enabled = false as part
	 * of a disable action), then it is still active but refreshing.
	 * Change states to re-activate itself.
	 */
	if (!manual_disabled &&
	    object->nwamd_object_state == NWAM_STATE_ONLINE) {
		nwamd_object_set_state(NWAM_OBJECT_TYPE_ENM,
		    event->event_object, NWAM_STATE_OFFLINE_TO_ONLINE,
		    NWAM_AUX_STATE_METHOD_RUNNING);
	}
	nwamd_object_release(object);
}

/* Handle ENM finish event */
void
nwamd_enm_handle_fini_event(nwamd_event_t event)
{
	nwamd_event_t state_event;

	nlog(LOG_DEBUG, "nwamd_enm_handle_fini_event(%s)", event->event_object);

	/*
	 * Simulate a state event so that the state machine can correctly
	 * deactivate the ENM and free up the handle.
	 */
	state_event = nwamd_event_init_object_state(NWAM_OBJECT_TYPE_ENM,
	    event->event_object, NWAM_STATE_ONLINE_TO_OFFLINE,
	    NWAM_AUX_STATE_UNINITIALIZED);
	if (state_event == NULL) {
		nwamd_event_do_not_send(event);
		return;
	}
	nwamd_enm_handle_state_event(state_event);
	nwamd_event_fini(state_event);
	/*
	 * Do not free the handle and object.
	 * nwamd_enm_activate_deactivate_thread() and
	 * nwamd_enm_deactivate() does this after running the stop script
	 * and disabling the FMRI respectively.
	 */
}

void
nwamd_enm_handle_action_event(nwamd_event_t event)
{
	nwamd_object_t object;

	switch (event->event_msg->nwe_data.nwe_object_action.nwe_action) {
	case NWAM_ACTION_ENABLE:
		object = nwamd_object_find(NWAM_OBJECT_TYPE_ENM,
		    event->event_object);
		if (object == NULL) {
			nlog(LOG_ERR, "nwamd_enm_handle_action_event: "
			    "could not find enm %s", event->event_object);
			nwamd_event_do_not_send(event);
			return;
		}
		if (object->nwamd_object_state == NWAM_STATE_ONLINE) {
			nlog(LOG_DEBUG, "nwamd_enm_handle_action_event: "
			    "enm %s already online, nothing to do",
			    event->event_object);
			nwamd_object_release(object);
			return;
		}
		nwamd_object_release(object);

		nwamd_object_set_state(NWAM_OBJECT_TYPE_ENM,
		    event->event_object, NWAM_STATE_OFFLINE_TO_ONLINE,
		    NWAM_AUX_STATE_METHOD_RUNNING);
		break;
	case NWAM_ACTION_DISABLE:
		object = nwamd_object_find(NWAM_OBJECT_TYPE_ENM,
		    event->event_object);
		if (object == NULL) {
			nlog(LOG_ERR, "nwamd_enm_handle_action_event: "
			    "could not find enm %s", event->event_object);
			nwamd_event_do_not_send(event);
			return;
		}
		if (object->nwamd_object_state == NWAM_STATE_DISABLED) {
			nlog(LOG_DEBUG, "nwamd_enm_handle_action_event: "
			    "enm %s already disabled, nothing to do",
			    event->event_object);
			nwamd_object_release(object);
			return;
		}
		nwamd_object_release(object);

		nwamd_object_set_state(NWAM_OBJECT_TYPE_ENM,
		    event->event_object, NWAM_STATE_ONLINE_TO_OFFLINE,
		    NWAM_AUX_STATE_MANUAL_DISABLE);
		break;
	case NWAM_ACTION_ADD:
	case NWAM_ACTION_REFRESH:
		nwamd_enm_handle_init_event(event);
		break;
	case NWAM_ACTION_DESTROY:
		nwamd_enm_handle_fini_event(event);
		break;
	default:
		nlog(LOG_INFO, "nwam_enm_handle_action_event: "
		    "unexpected action");
		nwamd_event_do_not_send(event);
		break;
	}
}

void
nwamd_enm_handle_state_event(nwamd_event_t event)
{
	nwamd_object_t object;
	nwam_state_t new_state;
	nwam_aux_state_t new_aux_state;

	if ((object = nwamd_object_find(NWAM_OBJECT_TYPE_ENM,
	    event->event_object)) == NULL) {
		nlog(LOG_INFO, "nwamd_enm_handle_state_event: "
		    "state event for nonexistent enm %s", event->event_object);
		nwamd_event_do_not_send(event);
		return;
	}
	new_state = event->event_msg->nwe_data.nwe_object_state.nwe_state;
	new_aux_state =
	    event->event_msg->nwe_data.nwe_object_state.nwe_aux_state;

	if (new_state == object->nwamd_object_state &&
	    new_aux_state == object->nwamd_object_aux_state) {
		nlog(LOG_DEBUG, "nwamd_enm_handle_state_event: "
		    "enm %s already in state (%s , %s)",
		    object->nwamd_object_name, nwam_state_to_string(new_state),
		    nwam_aux_state_to_string(new_aux_state));
		nwamd_object_release(object);
		return;
	}

	object->nwamd_object_state = new_state;
	object->nwamd_object_aux_state = new_aux_state;

	nlog(LOG_DEBUG, "nwamd_enm_handle_state_event: changing state for enm "
	    "%s to (%s , %s)", object->nwamd_object_name,
	    nwam_state_to_string(object->nwamd_object_state),
	    nwam_aux_state_to_string(object->nwamd_object_aux_state));

	nwamd_object_release(object);

	/*
	 * State machine for ENMs.
	 */
	switch (new_state) {
	case NWAM_STATE_OFFLINE_TO_ONLINE:
		nwamd_enm_activate(event->event_object);
		break;
	case NWAM_STATE_ONLINE_TO_OFFLINE:
		nwamd_enm_deactivate(event->event_object);
		break;
	case NWAM_STATE_DISABLED:
	case NWAM_STATE_OFFLINE:
	case NWAM_STATE_UNINITIALIZED:
	case NWAM_STATE_MAINTENANCE:
	case NWAM_STATE_DEGRADED:
	default:
		/* do nothing */
		break;
	}
}
/*
 * 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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#include <atomic.h>
#include <errno.h>
#include <execinfo.h>
#include <libuutil.h>
#include <pthread.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <syslog.h>
#include <sys/time.h>
#include <unistd.h>

#include "conditions.h"
#include "events.h"
#include "objects.h"
#include "util.h"

/*
 * events.c - contains routines which create/destroy event sources,
 * handle the event queue and process events from that queue.
 */

/* Add new event sources here. */
struct nwamd_event_source {
	char *name;
	void (*events_init)(void);
	void (*events_fini)(void);
} event_sources[] = {
	{ "routing_events",
	nwamd_routing_events_init, nwamd_routing_events_fini },
	{ "sysevent_events",
	nwamd_sysevent_events_init, nwamd_sysevent_events_fini },
};

/* Counter for event ids */
static uint64_t event_id_counter = 0;

static uu_list_pool_t *event_pool = NULL;
static uu_list_t *event_queue = NULL;
static pthread_mutex_t event_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t event_queue_cond = PTHREAD_COND_INITIALIZER;

static int nwamd_event_compare(const void *, const void *, void *);

static const char *
nwamd_event_name(int event_type)
{
	if (event_type <= NWAM_EVENT_MAX)
		return (nwam_event_type_to_string(event_type));

	switch (event_type) {
	case NWAM_EVENT_TYPE_OBJECT_INIT:
		return ("OBJECT_INIT");
	case NWAM_EVENT_TYPE_OBJECT_FINI:
		return ("OBJECT_FINI");
	case NWAM_EVENT_TYPE_TIMED_CHECK_CONDITIONS:
		return ("TIMED_CHECK_CONDITIONS");
	case NWAM_EVENT_TYPE_TRIGGERED_CHECK_CONDITIONS:
		return ("TRIGGERED_CHECK_CONDITIONS");
	case NWAM_EVENT_TYPE_NCU_CHECK:
		return ("NCU_CHECK");
	case NWAM_EVENT_TYPE_TIMER:
		return ("TIMER");
	case NWAM_EVENT_TYPE_UPGRADE:
		return ("UPGRADE");
	case NWAM_EVENT_TYPE_PERIODIC_SCAN:
		return ("PERIODIC_SCAN");
	case NWAM_EVENT_TYPE_QUEUE_QUIET:
		return ("QUEUE_QUIET");
	default:
		return ("N/A");
	}
}

void
nwamd_event_sources_init(void)
{
	int i;

	/*
	 * Now we can safely initialize event sources.
	 */
	for (i = 0;
	    i < sizeof (event_sources) / sizeof (struct nwamd_event_source);
	    i++) {
		if (event_sources[i].events_init != NULL)
			event_sources[i].events_init();
	}
}

void
nwamd_event_sources_fini(void)
{
	int i;

	for (i = 0;
	    i < sizeof (event_sources) / sizeof (struct nwamd_event_source);
	    i++) {
		if (event_sources[i].events_init != NULL)
			event_sources[i].events_fini();
	}
}

/*
 * Comparison function for events, passed in as callback to
 * uu_list_pool_create(). Compare by time, so that timer
 * event queue can be sorted by nearest time to present.
 */
/* ARGSUSED */
static int
nwamd_event_compare(const void *l_arg, const void *r_arg, void *private)
{
	nwamd_event_t l = (nwamd_event_t)l_arg;
	nwamd_event_t r = (nwamd_event_t)r_arg;
	int rv;

	rv = l->event_time.tv_sec - r->event_time.tv_sec;
	if (rv == 0)
		rv = l->event_time.tv_nsec - r->event_time.tv_nsec;

	return (rv);
}

void
nwamd_event_queue_init(void)
{
	event_pool = uu_list_pool_create("event_queue_pool",
	    sizeof (struct nwamd_event),
	    offsetof(struct nwamd_event, event_node),
	    nwamd_event_compare, UU_LIST_POOL_DEBUG);
	if (event_pool == NULL)
		pfail("uu_list_pool_create failed with error %d", uu_error());
	event_queue = uu_list_create(event_pool, NULL, UU_LIST_SORTED);
	if (event_queue == NULL)
		pfail("uu_list_create failed with error %d", uu_error());
}

void
nwamd_event_queue_fini(void)
{
	void *cookie = NULL;
	nwamd_event_t event;

	while ((event = uu_list_teardown(event_queue, &cookie)) != NULL)
		nwamd_event_fini(event);
	uu_list_destroy(event_queue);
	if (event_pool != NULL)
		uu_list_pool_destroy(event_pool);
}

nwamd_event_t
nwamd_event_init(int32_t type, nwam_object_type_t object_type,
    size_t size, const char *object_name)
{
	nwamd_event_t event;

	event = calloc(1, sizeof (struct nwamd_event));
	if (event == NULL) {
		nlog(LOG_ERR, "nwamd_event_init: could not create %s event for "
		    "object %s", nwamd_event_name(type),
		    object_name != NULL ? object_name : "<no object>");
		return (NULL);
	}

	/* Is this an externally-visible event? */
	if (type <= NWAM_EVENT_MAX) {
		event->event_send = B_TRUE;
		event->event_msg = calloc(1, sizeof (struct nwam_event) + size);
		if (event->event_msg == NULL) {
			nlog(LOG_ERR,
			    "nwamd_event_init: could not create %s event",
			    nwamd_event_name(type));
			free(event);
			return (NULL);
		}
		event->event_msg->nwe_type = type;
		event->event_msg->nwe_size = sizeof (struct nwam_event) + size;
	} else {
		event->event_send = B_FALSE;
		event->event_msg = NULL;
	}

	event->event_type = type;

	if (object_name != NULL) {
		(void) strlcpy(event->event_object, object_name,
		    NWAM_MAX_NAME_LEN);
		event->event_object_type = object_type;
	} else {
		event->event_object[0] = '\0';
	}

	/* Set event id */
	event->event_id = atomic_add_64_nv(&event_id_counter, 1);
	(void) clock_gettime(CLOCK_REALTIME, &event->event_time);

	return (event);
}

void
nwamd_event_do_not_send(nwamd_event_t event)
{
	nlog(LOG_DEBUG, "nwamd_event_do_not_send: cancelling delivery of "
	    "event %s for object %s", nwamd_event_name(event->event_type),
	    event->event_object[0] != '\0' ?
	    event->event_object : "<no object>");
	event->event_send = B_FALSE;
}

void
nwamd_event_fini(nwamd_event_t event)
{
	if (event != NULL) {
		free(event->event_msg);
		free(event);
	}
}

nwamd_event_t
nwamd_event_init_object_action(nwam_object_type_t object_type,
    const char *object_name, const char *parent_name,
    nwam_action_t object_action)
{
	nwamd_event_t event;

	event = nwamd_event_init(NWAM_EVENT_TYPE_OBJECT_ACTION,
	    object_type, 0, object_name);
	if (event == NULL)
		return (NULL);

	event->event_msg->nwe_data.nwe_object_action.nwe_action = object_action;
	event->event_msg->nwe_data.nwe_object_action.nwe_object_type =
	    object_type;
	(void) strlcpy(event->event_msg->nwe_data.nwe_object_action.nwe_name,
	    object_name,
	    sizeof (event->event_msg->nwe_data.nwe_object_action.nwe_name));
	if (parent_name == NULL) {
		event->event_msg->nwe_data.nwe_object_action.nwe_parent[0] =
		    '\0';
		return (event);
	}
	(void) strlcpy
	    (event->event_msg->nwe_data.nwe_object_action.nwe_parent,
	    parent_name,
	    sizeof (event->event_msg->nwe_data.nwe_object_action.nwe_parent));
	return (event);
}

nwamd_event_t
nwamd_event_init_object_state(nwam_object_type_t object_type,
    const char *object_name, nwam_state_t state, nwam_aux_state_t aux_state)
{
	nwamd_event_t event;

	event = nwamd_event_init(NWAM_EVENT_TYPE_OBJECT_STATE,
	    object_type, 0, object_name);
	if (event == NULL)
		return (NULL);

	event->event_msg->nwe_data.nwe_object_state.nwe_state = state;
	event->event_msg->nwe_data.nwe_object_state.nwe_aux_state = aux_state;
	event->event_msg->nwe_data.nwe_object_state.nwe_object_type =
	    object_type;
	(void) strlcpy(event->event_msg->nwe_data.nwe_object_state.nwe_name,
	    object_name,
	    sizeof (event->event_msg->nwe_data.nwe_object_state.nwe_name));

	return (event);
}

nwamd_event_t
nwamd_event_init_priority_group_change(int64_t priority)
{
	nwamd_event_t event;

	event = nwamd_event_init(NWAM_EVENT_TYPE_PRIORITY_GROUP,
	    NWAM_OBJECT_TYPE_UNKNOWN, 0, NULL);
	if (event == NULL)
		return (NULL);

	event->event_msg->nwe_data.nwe_priority_group_info.nwe_priority =
	    priority;

	return (event);
}

nwamd_event_t
nwamd_event_init_link_action(const char *name, nwam_action_t link_action)
{
	nwamd_event_t event;
	nwam_error_t err;
	char *object_name;

	if ((err = nwam_ncu_name_to_typed_name(name, NWAM_NCU_TYPE_LINK,
	    &object_name)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_event_init_link_action: "
		    "nwam_ncu_name_to_typed_name: %s",
		    nwam_strerror(err));
		return (NULL);
	}
	event = nwamd_event_init(NWAM_EVENT_TYPE_LINK_ACTION,
	    NWAM_OBJECT_TYPE_NCU, 0, object_name);
	free(object_name);
	if (event == NULL)
		return (NULL);

	(void) strlcpy(event->event_msg->nwe_data.nwe_link_action.nwe_name,
	    name,
	    sizeof (event->event_msg->nwe_data.nwe_link_action.nwe_name));
	event->event_msg->nwe_data.nwe_link_action.nwe_action = link_action;

	return (event);
}

nwamd_event_t
nwamd_event_init_link_state(const char *name, boolean_t up)
{
	nwamd_event_t event;
	nwam_error_t err;
	char *object_name;

	if ((err = nwam_ncu_name_to_typed_name(name, NWAM_NCU_TYPE_LINK,
	    &object_name)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_event_init_link_state: "
		    "nwam_ncu_name_to_typed_name: %s",
		    nwam_strerror(err));
		return (NULL);
	}

	event = nwamd_event_init(NWAM_EVENT_TYPE_LINK_STATE,
	    NWAM_OBJECT_TYPE_NCU, 0, object_name);
	free(object_name);
	if (event == NULL)
		return (NULL);

	(void) strlcpy(event->event_msg->nwe_data.nwe_link_state.nwe_name, name,
	    sizeof (event->event_msg->nwe_data.nwe_link_state.nwe_name));
	event->event_msg->nwe_data.nwe_link_state.nwe_link_up = up;

	return (event);
}

nwamd_event_t
nwamd_event_init_if_state(const char *linkname, uint32_t flags,
    uint32_t addr_added, struct sockaddr *addr, struct sockaddr *netmask)
{
	nwamd_event_t event;
	nwam_error_t err;
	char *object_name;

	/* linkname does not contain the lifnum */
	if ((err = nwam_ncu_name_to_typed_name(linkname,
	    NWAM_NCU_TYPE_INTERFACE, &object_name)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_event_init_if_state: "
		    "nwam_ncu_name_to_typed_name: %s",
		    nwam_strerror(err));
		return (NULL);
	}

	event = nwamd_event_init(NWAM_EVENT_TYPE_IF_STATE,
	    NWAM_OBJECT_TYPE_NCU, 0, object_name);
	free(object_name);
	if (event == NULL)
		return (NULL);

	(void) strlcpy(event->event_msg->nwe_data.nwe_if_state.nwe_name,
	    linkname,
	    sizeof (event->event_msg->nwe_data.nwe_if_state.nwe_name));
	event->event_msg->nwe_data.nwe_if_state.nwe_flags = flags;
	event->event_msg->nwe_data.nwe_if_state.nwe_addr_added = addr_added;
	event->event_msg->nwe_data.nwe_if_state.nwe_addr_valid = (addr != NULL);

	if (addr != NULL) {
		bcopy(addr, &(event->event_msg->nwe_data.nwe_if_state.nwe_addr),
		    addr->sa_family == AF_INET ? sizeof (struct sockaddr_in) :
		    sizeof (struct sockaddr_in6));
	}
	if (netmask != NULL) {
		bcopy(netmask,
		    &(event->event_msg->nwe_data.nwe_if_state.nwe_netmask),
		    netmask->sa_family == AF_INET ?
		    sizeof (struct sockaddr_in) : sizeof (struct sockaddr_in6));
	}

	return (event);
}

nwamd_event_t
nwamd_event_init_wlan(const char *name, int32_t type, boolean_t connected,
    nwam_wlan_t *wlans, uint_t num_wlans)
{
	size_t size = 0;
	char *object_name;
	nwamd_event_t event;
	nwam_error_t err;

	switch (type) {
	case NWAM_EVENT_TYPE_WLAN_SCAN_REPORT:
	case NWAM_EVENT_TYPE_WLAN_NEED_CHOICE:
		size = sizeof (nwam_wlan_t) * (num_wlans - 1);
		break;
	case NWAM_EVENT_TYPE_WLAN_NEED_KEY:
	case NWAM_EVENT_TYPE_WLAN_CONNECTION_REPORT:
		break;
	default:
		nlog(LOG_ERR, "nwamd_event_init_wlan: unexpected "
		    "event type %s (%d)", nwamd_event_name(type), type);
		return (NULL);
	}
	if ((err = nwam_ncu_name_to_typed_name(name, NWAM_NCU_TYPE_LINK,
	    &object_name)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_event_init_wlan: "
		    "nwam_ncu_name_to_typed_name: %s",
		    nwam_strerror(err));
		return (NULL);
	}

	event = nwamd_event_init(type, NWAM_OBJECT_TYPE_NCU, size, object_name);
	free(object_name);
	if (event == NULL)
		return (NULL);

	(void) strlcpy(event->event_msg->nwe_data.nwe_wlan_info.nwe_name, name,
	    sizeof (event->event_msg->nwe_data.nwe_wlan_info.nwe_name));
	event->event_msg->nwe_data.nwe_wlan_info.nwe_connected = connected;
	event->event_msg->nwe_data.nwe_wlan_info.nwe_num_wlans = num_wlans;

	/* copy the wlans */
	(void) memcpy(event->event_msg->nwe_data.nwe_wlan_info.nwe_wlans, wlans,
	    num_wlans * sizeof (nwam_wlan_t));

	return (event);
}

nwamd_event_t
nwamd_event_init_ncu_check(void)
{
	return (nwamd_event_init(NWAM_EVENT_TYPE_NCU_CHECK,
	    NWAM_OBJECT_TYPE_NCP, 0, NULL));
}

nwamd_event_t
nwamd_event_init_init(void)
{
	return (nwamd_event_init(NWAM_EVENT_TYPE_INIT,
	    NWAM_OBJECT_TYPE_UNKNOWN, 0, NULL));
}

nwamd_event_t
nwamd_event_init_shutdown(void)
{
	return (nwamd_event_init(NWAM_EVENT_TYPE_SHUTDOWN,
	    NWAM_OBJECT_TYPE_UNKNOWN, 0, NULL));
}

/*
 * Add event to the event list.
 */
void
nwamd_event_enqueue(nwamd_event_t event)
{
	nwamd_event_enqueue_timed(event, 0);
}

/*
 * Schedule an event to be added to the event list for future processing.
 * The event will be scheduled in delta_seconds seconds mod schedule delay and
 * time resolution.
 */
void
nwamd_event_enqueue_timed(nwamd_event_t event, int delta_seconds)
{
	uu_list_index_t idx;

	nlog(LOG_DEBUG, "enqueueing event %lld %d (%s) for object %s in %ds",
	    event->event_id, event->event_type,
	    nwamd_event_name(event->event_type),
	    event->event_object[0] != 0 ?  event->event_object : "none",
	    delta_seconds);

	(void) clock_gettime(CLOCK_REALTIME, &event->event_time);
	event->event_time.tv_sec += delta_seconds;

	uu_list_node_init(event, &event->event_node, event_pool);

	(void) pthread_mutex_lock(&event_queue_mutex);

	/*
	 * Find appropriate location to insert the event based on time.
	 */
	(void) uu_list_find(event_queue, event, NULL, &idx);
	(void) uu_list_insert(event_queue, event, idx);

	(void) pthread_cond_signal(&event_queue_cond);
	(void) pthread_mutex_unlock(&event_queue_mutex);
}

/*
 * Is the specified event enqueued on the event (or pending event queue)
 * for execution in when seconds? An object may be specified also.
 */
boolean_t
nwamd_event_enqueued(int32_t event_type, nwam_object_type_t object_type,
    const char *object)
{
	nwamd_event_t event;

	(void) pthread_mutex_lock(&event_queue_mutex);
	for (event = uu_list_first(event_queue);
	    event != NULL;
	    event = uu_list_next(event_queue, event)) {
		if (event->event_type != event_type)
			continue;
		if (object_type != NWAM_OBJECT_TYPE_UNKNOWN &&
		    event->event_object_type != object_type)
			continue;
		if (object != NULL && strcmp(object, event->event_object) != 0)
			continue;
		(void) pthread_mutex_unlock(&event_queue_mutex);
		return (B_TRUE);
	}
	(void) pthread_mutex_unlock(&event_queue_mutex);

	return (B_FALSE);
}

/*
 * Is the time in the past.
 */
static boolean_t
in_past(struct timespec t)
{
	struct timespec now;

	(void) clock_gettime(CLOCK_REALTIME, &now);
	if (t.tv_sec < now.tv_sec)
		return (B_TRUE);
	if (t.tv_sec > now.tv_sec)
		return (B_FALSE);
	if (t.tv_nsec < now.tv_nsec)
		return (B_TRUE);
	return (B_FALSE);
}

/*
 * Remove event at head of event list for processing.  This takes a number of
 * nanoseconds to wait.  If the number is 0 then it blocks.  If there is
 * nothing on the queue then it returns an event which says that the queue
 * is quiet.
 */
static nwamd_event_t
nwamd_event_dequeue(long nsec)
{
	nwamd_event_t event;

	(void) pthread_mutex_lock(&event_queue_mutex);
	event = uu_list_first(event_queue);
	if (event == NULL && nsec == 0) {
		do {
			(void) pthread_cond_wait(&event_queue_cond,
			    &event_queue_mutex);
		} while ((event = uu_list_first(event_queue)) == NULL);
	} else {
		struct timespec waitcap;

		if (nsec != 0) {
			(void) clock_gettime(CLOCK_REALTIME, &waitcap);
			waitcap.tv_nsec += nsec;
			waitcap.tv_sec += NSEC_TO_SEC(waitcap.tv_nsec);
			waitcap.tv_nsec = NSEC_TO_FRACNSEC(waitcap.tv_nsec);
		}

		/*
		 * Keep going as long as the first event hasn't matured and
		 * we havn't passed our maximum wait time.
		 */
		while ((event == NULL || !in_past(event->event_time)) &&
		    (nsec == 0 || !in_past(waitcap)))  {
			struct timespec eventwait;

			/*
			 * Three cases:
			 *	no maximum waittime - just use the event
			 *	both an event and cap - take the least one
			 *	just a maximum waittime - use it
			 */
			if (nsec == 0) {
				eventwait = event->event_time;
			} else if (event != NULL) {
				uint64_t diff;
				diff = SEC_TO_NSEC(event->event_time.tv_sec -
				    waitcap.tv_sec) +
				    event->event_time.tv_nsec - waitcap.tv_nsec;

				if (diff > 0)
					eventwait = waitcap;
				else
					eventwait = event->event_time;
			} else {
				/*
				 * Note that if the event is NULL then nsec is
				 * nonzero and waitcap is valid.
				 */
				eventwait = waitcap;
			}

			(void) pthread_cond_timedwait(&event_queue_cond,
			    &event_queue_mutex, &eventwait);
			event = uu_list_first(event_queue);
		}
	}

	/*
	 * At this point we've met the guard contition of the while loop.
	 * The event at the top of the queue might be mature in which case
	 * we use it.  Otherwise we hit our cap and we need to enqueue a
	 * quiesced queue event.
	 */
	if (event != NULL && in_past(event->event_time)) {
		uu_list_remove(event_queue, event);
		uu_list_node_fini(event, &event->event_node, event_pool);
	} else {
		event = nwamd_event_init(NWAM_EVENT_TYPE_QUEUE_QUIET,
		    NWAM_OBJECT_TYPE_UNKNOWN, 0, NULL);
	}

	if (event != NULL)
		nlog(LOG_DEBUG,
		    "dequeueing event %lld of type %d (%s) for object %s",
		    event->event_id, event->event_type,
		    nwamd_event_name(event->event_type),
		    event->event_object[0] != 0 ?  event->event_object :
		    "none");

	(void) pthread_mutex_unlock(&event_queue_mutex);

	return (event);
}

void
nwamd_event_send(nwam_event_t event_msg)
{
	nwam_error_t err;

	if (shutting_down && event_msg->nwe_type != NWAM_EVENT_TYPE_SHUTDOWN) {
		nlog(LOG_DEBUG, "nwamd_event_send: tossing event as nwamd "
		    "is shutting down");
		return;
	}

	err = nwam_event_send(event_msg);

	if (err != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_event_send: nwam_event_send: %s",
		    nwam_strerror(err));
	}
}

/*
 * Run state machine for object. Method is run if
 * - event method is non-null
 * - event method is valid for current object state (determined by
 * ORing the current state against the set of valid states for the method).
 *
 * If these criteria are met, the method is run.
 */
static void
nwamd_event_run_method(nwamd_event_t event)
{
	nwamd_event_method_t *event_methods;
	int i;

	event_methods = nwamd_object_event_methods(event->event_object_type);

	/* If we're shutting down, only fini events are accepted for objects */
	if (shutting_down && event->event_type != NWAM_EVENT_TYPE_OBJECT_FINI) {
		nlog(LOG_DEBUG, "nwamd_event_run_method: tossing non-fini "
		    "event %s for object %s",
		    nwamd_event_name(event->event_type), event->event_object);
		return;
	}

	for (i = 0;
	    event_methods[i].event_type != NWAM_EVENT_TYPE_NOOP;
	    i++) {
		if (event_methods[i].event_type ==
		    event->event_type &&
		    event_methods[i].event_method != NULL) {
			nlog(LOG_DEBUG,
			    "(%p) %s: running method for event %s",
			    (void *)event, event->event_object,
			    nwamd_event_name(event->event_type));
			/* run method */
			event_methods[i].event_method(event);
			return;
		}
	}
	nlog(LOG_DEBUG, "(%p) %s: no matching method for event %d (%s)",
	    (void *)event, event->event_object, event->event_type,
	    nwamd_event_name(event->event_type));
}

/*
 * Called when we are checking to see what should be activated.  First activate
 * all of the manual NCUs.  Then see if we can find a valid priority group.
 * If we can, activate it.  Otherwise try all the priority groups starting
 * with the lowest one that makes sense.
 */
static void
nwamd_activate_ncus(void) {
	int64_t prio = INVALID_PRIORITY_GROUP;
	boolean_t selected;

	nwamd_ncp_activate_manual_ncus();
	selected = nwamd_ncp_check_priority_group(&prio);
	if (selected) {
		/*
		 * Activate chosen priority group and stop anything going on in
		 * lesser priority groups.
		 */
		nwamd_ncp_activate_priority_group(prio);
		nwamd_ncp_deactivate_priority_group_all(prio + 1);
	} else {
		/*
		 * Nothing unique could be started so try them all.  Once one
		 * of them gets into a reasonable state then we will prune
		 * everything below it (see first part of this conditional).
		 */
		int64_t oldprio = INVALID_PRIORITY_GROUP;
		while (nwamd_ncp_find_next_priority_group(++oldprio, &prio)) {
			nwamd_ncp_activate_priority_group(prio);
			oldprio = prio;
		}
	}
}

/*
 * Event handler thread
 *
 * The complexity in this code comes about from wanting to delay the decision
 * making process until after bursts of events.  Keep roughly polling (waiting
 * for .1s) until we see the queue quiet event and then block.
 */
void
nwamd_event_handler(void)
{
	boolean_t got_shutdown_event = B_FALSE;
	boolean_t check_conditions = B_FALSE;
	boolean_t ncu_check = B_FALSE;
	int queue_quiet_time = 0;
	nwamd_event_t event;

	/*
	 * Dequeue events and process them.  In most cases, events have
	 * an assocated object type, and we use this to retrieve
	 * the function that will process the event.
	 */
	while (!got_shutdown_event) {
		event = nwamd_event_dequeue(queue_quiet_time);
		/* keep pulling events as long as they are close together */
		queue_quiet_time = SEC_TO_NSEC(1)/10;

		/*
		 * This is an event with no associated object.
		 */
		if (event->event_object[0] == '\0') {
			switch (event->event_type) {
			case NWAM_EVENT_TYPE_NOOP:
			case NWAM_EVENT_TYPE_INIT:
				/*
				 * The only action for an INIT event
				 * is to relay it to event listeners,
				 * which is done below.
				 */
				break;
			case NWAM_EVENT_TYPE_PRIORITY_GROUP:
				(void) pthread_mutex_lock(&active_ncp_mutex);
				current_ncu_priority_group =
				    event->event_msg->nwe_data.
				    nwe_priority_group_info.nwe_priority;
				(void) pthread_mutex_unlock(&active_ncp_mutex);
				break;
			case NWAM_EVENT_TYPE_TIMED_CHECK_CONDITIONS:
				if (!shutting_down) {
					nwamd_set_timed_check_all_conditions();
					check_conditions = B_TRUE;
				}
				break;
			case NWAM_EVENT_TYPE_TRIGGERED_CHECK_CONDITIONS:
				if (!shutting_down)
					check_conditions = B_TRUE;
				break;
			case NWAM_EVENT_TYPE_NCU_CHECK:
				if (!shutting_down)
					ncu_check = B_TRUE;
				break;
			case NWAM_EVENT_TYPE_UPGRADE:
				if (!shutting_down) {
					/*
					 * Upgrade events have no associated
					 * object.
					 */
					nwamd_event_run_method(event);
				}
				break;
			case NWAM_EVENT_TYPE_SHUTDOWN:
				got_shutdown_event = B_TRUE;
				break;

			/*
			 * We want to delay processing of condition and ncu
			 * checking until after short bursts of events.  So we
			 * keep track of times we've scheduled checking and
			 * wait for the queue to quiesce.
			 */
			case NWAM_EVENT_TYPE_QUEUE_QUIET:
				queue_quiet_time = 0; /* now we can block */
				if (!shutting_down && check_conditions) {
					nwamd_check_all_conditions();
					check_conditions = B_FALSE;
				}

				if (!shutting_down && ncu_check) {
					nwamd_activate_ncus();
					ncu_check = B_FALSE;
				}
				break;

			default:
				nlog(LOG_ERR,
				    "event %d (%s)had no object associated "
				    "with it", event->event_type,
				    nwamd_event_name(event->event_type));
				break;
			}
		} else {
			/*
			 * Event has an associated object - run event method
			 * for that object type (if any).
			 */
			nwamd_event_run_method(event);
		}
		/*
		 * Send associated message to listeners if event type is
		 * externally visible.
		 */
		if (event->event_send)
			nwamd_event_send(event->event_msg);

		nwamd_event_fini(event);
	}
	/* If we get here, we got a shutdown event. */
	nwamd_event_queue_fini();
	nwamd_object_lists_fini();
}
/*
 * 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.
 */

#ifndef _EVENTS_H
#define	_EVENTS_H

#include <door.h>
#include <libsysevent.h>
#include <libuutil.h>
#include <pthread.h>
#include <ucontext.h>

#include <libnwam.h>
#include <libnwam_priv.h>

struct nwamd_object;
typedef struct nwamd_object *nwamd_object_t;

#include "ncp.h"

/* Define internal-to-nwamd events here */
#define	NWAM_EVENT_TYPE_OBJECT_INIT		NWAM_EVENT_MAX + 1
#define	NWAM_EVENT_TYPE_OBJECT_FINI		NWAM_EVENT_MAX + 2
#define	NWAM_EVENT_TYPE_TIMED_CHECK_CONDITIONS	NWAM_EVENT_MAX + 3
#define	NWAM_EVENT_TYPE_TRIGGERED_CHECK_CONDITIONS NWAM_EVENT_MAX + 4
#define	NWAM_EVENT_TYPE_NCU_CHECK		NWAM_EVENT_MAX + 5
#define	NWAM_EVENT_TYPE_TIMER			NWAM_EVENT_MAX + 6
#define	NWAM_EVENT_TYPE_UPGRADE			NWAM_EVENT_MAX + 7
#define	NWAM_EVENT_TYPE_PERIODIC_SCAN		NWAM_EVENT_MAX + 8
#define	NWAM_EVENT_TYPE_QUEUE_QUIET		NWAM_EVENT_MAX + 9

#define	NEXT_FEW_SECONDS			5

/*
 * Forward definition.
 */
/*
 * Wrapper structure for libnwam event (nwam_events_msg_t),  containing
 * event id (used to uniquely identify events on the event queue),
 * associated object (if any), and uu_list_node.
 */
typedef struct nwamd_event {
	int32_t event_type;
	uint64_t event_id;
	struct timespec event_time;
	char event_object[NWAM_MAX_NAME_LEN];
	nwam_object_type_t event_object_type;
	uu_list_node_t event_node;
	boolean_t event_send;
	nwam_event_t event_msg;
} *nwamd_event_t;

typedef struct nwamd_event_method {
	int32_t event_type;
	void (*event_method)(nwamd_event_t);
} nwamd_event_method_t;

extern sysevent_handle_t *shp;

/* Event generator init/fini code */
extern void nwamd_routing_events_init(void);
extern void nwamd_routing_events_fini(void);
extern void nwamd_sysevent_events_init(void);
extern void nwamd_sysevent_events_fini(void);

/* Event init/enqueueing */
extern void nwamd_event_queue_init(void);
extern void nwamd_event_queue_fini(void);
extern void nwamd_event_sources_init(void);
extern void nwamd_event_sources_fini(void);
extern nwamd_event_t nwamd_event_init(int32_t, nwam_object_type_t, size_t,
    const char *);
extern void nwamd_event_do_not_send(nwamd_event_t);
extern nwamd_event_t nwamd_event_init_object_action(nwam_object_type_t,
    const char *, const char *, nwam_action_t);
extern nwamd_event_t nwamd_event_init_object_state(nwam_object_type_t,
    const char *, nwam_state_t, nwam_aux_state_t);
extern nwamd_event_t nwamd_event_init_priority_group_change(int64_t);
extern nwamd_event_t nwamd_event_init_link_action(const char *, nwam_action_t);
extern nwamd_event_t nwamd_event_init_link_state(const char *, boolean_t);
extern nwamd_event_t nwamd_event_init_if_state(const char *, uint32_t,
    uint32_t, struct sockaddr *, struct sockaddr *);
extern nwamd_event_t nwamd_event_init_wlan(const char *, int32_t, boolean_t,
    nwam_wlan_t *, uint_t);
extern nwamd_event_t nwamd_event_init_ncu_check(void);
extern nwamd_event_t nwamd_event_init_init(void);
extern nwamd_event_t nwamd_event_init_shutdown(void);
extern void nwamd_event_enqueue(nwamd_event_t);
extern void nwamd_event_enqueue_timed(nwamd_event_t, int);
extern void nwamd_event_enqueue_expired_events(void);
extern boolean_t nwamd_event_enqueued(int32_t, nwam_object_type_t,
    const char *);
extern void nwamd_event_send(nwam_event_t);
extern void nwamd_event_fini(nwamd_event_t);
extern void nwamd_event_handler(void);

#endif /* _EVENTS_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 2010 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

# Start by blocking everything.
block in log all
block out log all

# Allow loopback traffic
pass in quick on lo0
pass out quick on lo0

# Allow DHCP: in to client port, out to server port
pass in quick proto udp from any to any port = 68
pass out quick proto udp from any to any port = 67
#
# 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.
#

# Start by blocking everything.
block in log all
block out log all

# Allow loopback traffic
pass in quick on lo0
pass out quick on lo0

# Allow DHCP: in to client port, out to server port
pass in quick proto udp from any to any port = 546
pass out quick proto udp from any to any port = 547

# Allow ICMP for IPv6 for Neighbor advertisements
pass in quick proto ipv6-icmp from any to any
pass out quick proto ipv6-icmp from any to any
/*
 * 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.
 */

#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libdladm.h>
#include <libdllink.h>
#include <libdlwlan.h>
#include <libgen.h>
#include <libnwam.h>

#include "events.h"
#include "known_wlans.h"
#include "ncu.h"
#include "objects.h"
#include "util.h"

/*
 * known_wlans.c - contains routines which handle the known WLAN abstraction.
 */

#define	KNOWN_WIFI_NETS_FILE		"/etc/nwam/known_wifi_nets"

/* enum for parsing each line of /etc/nwam/known_wifi_nets */
typedef enum {
	ESSID = 0,
	BSSID,
	MAX_FIELDS
} known_wifi_nets_fields_t;

/* Structure for one BSSID */
typedef struct bssid {
	struct qelem	bssid_links;
	char		*bssid;
} bssid_t;

/* Structure for an ESSID and its BSSIDs */
typedef struct kw {
	struct qelem	kw_links;
	char		kw_essid[NWAM_MAX_NAME_LEN];
	uint32_t	kw_num_bssids;
	struct qelem	kw_bssids;
} kw_t;

/* Holds the linked-list of ESSIDs to make Known WLANs out of */
static struct qelem kw_list;

/* Used in walking secobjs looking for an ESSID prefix match. */
struct nwamd_secobj_arg {
	char nsa_essid_prefix[DLADM_WLAN_MAX_KEYNAME_LEN];
	char nsa_keyname[DLADM_WLAN_MAX_KEYNAME_LEN];
	dladm_wlan_key_t *nsa_key;
	uint64_t nsa_secmode;
};

static void
kw_list_init(void)
{
	kw_list.q_forw = kw_list.q_back = &kw_list;
}

static void
kw_list_free(void)
{
	kw_t *kw;
	bssid_t *b;

	while (kw_list.q_forw != &kw_list) {
		kw = (kw_t *)kw_list.q_forw;

		/* free kw_bssids */
		while (kw->kw_bssids.q_forw != &kw->kw_bssids) {
			b = (bssid_t *)kw->kw_bssids.q_forw;
			remque(&b->bssid_links);
			free(b->bssid);
			free(b);
		}
		remque(&kw->kw_links);
		free(kw);
	}
}

/* Returns the entry in kw_list for the given ESSID.  NULL if non-existent */
static kw_t *
kw_lookup(const char *essid)
{
	kw_t *kw;

	if (essid == NULL)
		return (NULL);

	for (kw = (kw_t *)kw_list.q_forw;
	    kw != (kw_t *)&kw_list;
	    kw = (kw_t *)kw->kw_links.q_forw) {
		if (strcmp(essid, kw->kw_essid) == 0)
			return (kw);
	}
	return (NULL);
}

/* Adds an ESSID/BSSID combination to kw_list.  Returns B_TRUE on success. */
static boolean_t
kw_add(const char *essid, const char *bssid)
{
	kw_t *kw;
	bssid_t *b;

	if ((b = calloc(1, sizeof (bssid_t))) == NULL) {
		nlog(LOG_ERR, "kw_add: cannot allocate for bssid_t: %m");
		return (B_FALSE);
	}
	if ((kw = calloc(1, sizeof (kw_t))) == NULL) {
		nlog(LOG_ERR, "kw_add: cannot allocate for kw_t: %m");
		free(b);
		return (B_FALSE);
	}
	kw->kw_bssids.q_forw = kw->kw_bssids.q_back = &kw->kw_bssids;

	b->bssid = strdup(bssid);
	(void) strlcpy(kw->kw_essid, essid, sizeof (kw->kw_essid));
	kw->kw_num_bssids = 1;

	insque(&b->bssid_links, kw->kw_bssids.q_back);
	insque(&kw->kw_links, kw_list.q_back);

	nlog(LOG_DEBUG, "kw_add: added Known WLAN %s, BSSID %s", essid, bssid);
	return (B_TRUE);
}

/*
 * Add the BSSID to the given kw.  Since /etc/nwam/known_wifi_nets is
 * populated such that the wifi networks visited later are towards the end
 * of the file, remove the give kw from its current position and append it
 * to the end of kw_list.  This ensures that kw_list is in the reverse
 * order of visited wifi networks.  Returns B_TRUE on success.
 */
static boolean_t
kw_update(kw_t *kw, const char *bssid)
{
	bssid_t *b;

	if ((b = calloc(1, sizeof (bssid_t))) == NULL) {
		nlog(LOG_ERR, "kw_update: cannot allocate for bssid_t: %m");
		return (B_FALSE);
	}

	b->bssid = strdup(bssid);
	insque(&b->bssid_links, kw->kw_bssids.q_back);
	kw->kw_num_bssids++;

	/* remove kw from current position */
	remque(&kw->kw_links);
	/* and insert at end */
	insque(&kw->kw_links, kw_list.q_back);

	nlog(LOG_DEBUG, "kw_update: appended BSSID %s to Known WLAN %s",
	    bssid, kw->kw_essid);
	return (B_TRUE);
}

/*
 * Parses /etc/nwam/known_wifi_nets and populates kw_list, with the oldest
 * wifi networks first in the list.  Returns the number of unique entries
 * in kw_list (to use for priority values).
 */
static int
parse_known_wifi_nets(void)
{
	FILE *fp;
	char line[LINE_MAX];
	char *cp, *tok[MAX_FIELDS];
	int lnum, num_kw = 0;
	kw_t *kw;

	kw_list_init();

	/*
	 * The file format is:
	 * essid\tbssid (essid followed by tab followed by bssid)
	 */
	fp = fopen(KNOWN_WIFI_NETS_FILE, "r");
	if (fp == NULL)
		return (0);
	for (lnum = 1; fgets(line, sizeof (line), fp) != NULL; lnum++) {

		cp = line;
		while (isspace(*cp))
			cp++;
		if (*cp == '#' || *cp == '\0')
			continue;

		if (bufsplit(cp, MAX_FIELDS, tok) != MAX_FIELDS) {
			syslog(LOG_ERR, "%s:%d: wrong number of tokens; "
			    "ignoring entry", KNOWN_WIFI_NETS_FILE, lnum);
			continue;
		}

		if ((kw = kw_lookup(tok[ESSID])) == NULL) {
			if (!kw_add(tok[ESSID], tok[BSSID])) {
				nlog(LOG_ERR,
				    "%s:%d: cannot add entry (%s,%s) to list",
				    KNOWN_WIFI_NETS_FILE, lnum,
				    tok[ESSID], tok[BSSID]);
			} else {
				num_kw++;
			}
		} else {
			if (!kw_update(kw, tok[BSSID])) {
				nlog(LOG_ERR,
				    "%s:%d:cannot update entry (%s,%s) to list",
				    KNOWN_WIFI_NETS_FILE, lnum,
				    tok[ESSID], tok[BSSID]);
			}
		}
		/* next line ... */
	}

	(void) fclose(fp);
	return (num_kw);
}

/*
 * Walk security objects looking for one that matches the essid prefix.
 * Store the key and keyname if a match is found - we use the last match
 * as the key for the known WLAN, since it is the most recently updated.
 */
/* ARGSUSED0 */
static boolean_t
find_secobj_matching_prefix(dladm_handle_t dh, void *arg,
    const char *secobjname)
{
	struct nwamd_secobj_arg *nsa = arg;

	if (strncmp(nsa->nsa_essid_prefix, secobjname,
	    strlen(nsa->nsa_essid_prefix)) == 0) {
		nlog(LOG_DEBUG, "find_secobj_matching_prefix: "
		    "found secobj with prefix %s : %s\n",
		    nsa->nsa_essid_prefix, secobjname);
		/* Free last key found (if any) */
		if (nsa->nsa_key != NULL)
			free(nsa->nsa_key);
		/* Retrive key so we can get security mode */
		nsa->nsa_key = nwamd_wlan_get_key_named(secobjname, 0);
		(void) strlcpy(nsa->nsa_keyname, secobjname,
		    sizeof (nsa->nsa_keyname));
		switch (nsa->nsa_key->wk_class) {
		case DLADM_SECOBJ_CLASS_WEP:
			nsa->nsa_secmode = DLADM_WLAN_SECMODE_WEP;
			nlog(LOG_DEBUG, "find_secobj_matching_prefix: "
			    "got WEP key %s", nsa->nsa_keyname);
			break;
		case DLADM_SECOBJ_CLASS_WPA:
			nsa->nsa_secmode = DLADM_WLAN_SECMODE_WPA;
			nlog(LOG_DEBUG, "find_secobj_matching_prefix: "
			    "got WPA key %s", nsa->nsa_keyname);
			break;
		default:
			/* shouldn't happen */
			nsa->nsa_secmode = DLADM_WLAN_SECMODE_NONE;
			nlog(LOG_ERR, "find_secobj_matching_prefix: "
			    "key class for key %s was invalid",
			    nsa->nsa_keyname);
			break;
		}
	}
	return (B_TRUE);
}


/* Upgrade /etc/nwam/known_wifi_nets file to new libnwam-based config model */
void
upgrade_known_wifi_nets_config(void)
{
	kw_t *kw;
	bssid_t *b;
	nwam_known_wlan_handle_t kwh;
	char **bssids;
	nwam_error_t err;
	uint64_t priority;
	int i, num_kw;
	struct nwamd_secobj_arg nsa;

	nlog(LOG_INFO, "Upgrading %s to Known WLANs", KNOWN_WIFI_NETS_FILE);

	/* Parse /etc/nwam/known_wifi_nets */
	num_kw = parse_known_wifi_nets();

	/* Create Known WLANs for each unique ESSID */
	for (kw = (kw_t *)kw_list.q_forw, priority = num_kw-1;
	    kw != (kw_t *)&kw_list;
	    kw = (kw_t *)kw->kw_links.q_forw, priority--) {
		nwam_value_t priorityval = NULL;
		nwam_value_t bssidsval = NULL;
		nwam_value_t secmodeval = NULL;
		nwam_value_t keynameval = NULL;

		nlog(LOG_DEBUG, "Creating Known WLAN %s", kw->kw_essid);

		if ((err = nwam_known_wlan_create(kw->kw_essid, &kwh))
		    != NWAM_SUCCESS) {
			nlog(LOG_ERR, "upgrade wlan %s: "
			    "could not create known wlan: %s", kw->kw_essid,
			    nwam_strerror(err));
			continue;
		}

		/* priority of this ESSID */
		if ((err = nwam_value_create_uint64(priority, &priorityval))
		    != NWAM_SUCCESS) {
			nlog(LOG_ERR, "upgrade wlan %s: "
			    "could not create priority value: %s", kw->kw_essid,
			    nwam_strerror(err));
			nwam_known_wlan_free(kwh);
			continue;
		}
		err = nwam_known_wlan_set_prop_value(kwh,
		    NWAM_KNOWN_WLAN_PROP_PRIORITY, priorityval);
		nwam_value_free(priorityval);
		if (err != NWAM_SUCCESS) {
			nlog(LOG_ERR, "upgrade wlan %s: "
			    "could not set priority value: %s", kw->kw_essid,
			    nwam_strerror(err));
			nwam_known_wlan_free(kwh);
			continue;
		}

		/* loop through kw->kw_bssids and create an array of bssids */
		bssids = calloc(kw->kw_num_bssids, sizeof (char *));
		if (bssids == NULL) {
			nwam_known_wlan_free(kwh);
			nlog(LOG_ERR, "upgrade wlan %s: "
			    "could not calloc for bssids: %m", kw->kw_essid);
			continue;
		}
		for (b = (bssid_t *)kw->kw_bssids.q_forw, i = 0;
		    b != (bssid_t *)&kw->kw_bssids;
		    b = (bssid_t *)b->bssid_links.q_forw, i++) {
			bssids[i] = strdup(b->bssid);
		}

		/* BSSIDs for this ESSID */
		if ((err = nwam_value_create_string_array(bssids,
		    kw->kw_num_bssids, &bssidsval)) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "upgrade wlan %s: "
			    "could not create bssids value: %s", kw->kw_essid,
			    nwam_strerror(err));
			for (i = 0; i < kw->kw_num_bssids; i++)
				free(bssids[i]);
			free(bssids);
			nwam_known_wlan_free(kwh);
			continue;
		}
		err = nwam_known_wlan_set_prop_value(kwh,
		    NWAM_KNOWN_WLAN_PROP_BSSIDS, bssidsval);
		nwam_value_free(bssidsval);
		for (i = 0; i < kw->kw_num_bssids; i++)
			free(bssids[i]);
		free(bssids);
		if (err != NWAM_SUCCESS) {
			nlog(LOG_ERR, "upgrade wlan %s: "
			    "could not set bssids: %s", kw->kw_essid,
			    nwam_strerror(err));
			nwam_known_wlan_free(kwh);
			continue;
		}

		/*
		 * Retrieve last key matching ESSID prefix if any, and set
		 * the retrieved key name and security mode.
		 */
		nwamd_set_key_name(kw->kw_essid, NULL, nsa.nsa_essid_prefix,
		    sizeof (nsa.nsa_essid_prefix));
		nsa.nsa_key = NULL;
		nsa.nsa_secmode = DLADM_WLAN_SECMODE_NONE;
		(void) dladm_walk_secobj(dld_handle, &nsa,
		    find_secobj_matching_prefix, DLADM_OPT_PERSIST);
		if (nsa.nsa_key != NULL) {
			if ((err = nwam_value_create_string(nsa.nsa_keyname,
			    &keynameval)) == NWAM_SUCCESS) {
				(void) nwam_known_wlan_set_prop_value(kwh,
				    NWAM_KNOWN_WLAN_PROP_KEYNAME, keynameval);
			}
			free(nsa.nsa_key);
			nwam_value_free(keynameval);
		}

		if ((err = nwam_value_create_uint64(nsa.nsa_secmode,
		    &secmodeval)) != NWAM_SUCCESS ||
		    (err = nwam_known_wlan_set_prop_value(kwh,
		    NWAM_KNOWN_WLAN_PROP_SECURITY_MODE, secmodeval))
		    != NWAM_SUCCESS) {
			nlog(LOG_ERR, "upgrade wlan %s: "
			    "could not set security mode: %s",
			    kw->kw_essid, nwam_strerror(err));
			nwam_value_free(secmodeval);
			nwam_known_wlan_free(kwh);
			continue;
		}

		/* commit, no collision checking by libnwam */
		err = nwam_known_wlan_commit(kwh,
		    NWAM_FLAG_KNOWN_WLAN_NO_COLLISION_CHECK);
		nwam_known_wlan_free(kwh);
		if (err != NWAM_SUCCESS) {
			nlog(LOG_ERR, "upgrade wlan %s: "
			    "could not commit wlan: %s", kw->kw_essid,
			    nwam_strerror(err));
		}
		/* next ... */
	}

	kw_list_free();
}

nwam_error_t
known_wlan_get_keyname(const char *essid, char *name)
{
	nwam_known_wlan_handle_t kwh = NULL;
	nwam_value_t keynameval = NULL;
	char *keyname;
	nwam_error_t err;

	if ((err = nwam_known_wlan_read(essid, 0, &kwh)) != NWAM_SUCCESS)
		return (err);
	if ((err = nwam_known_wlan_get_prop_value(kwh,
	    NWAM_KNOWN_WLAN_PROP_KEYNAME, &keynameval)) == NWAM_SUCCESS &&
	    (err = nwam_value_get_string(keynameval, &keyname))
	    == NWAM_SUCCESS) {
		(void) strlcpy(name, keyname, NWAM_MAX_VALUE_LEN);
	}
	if (keynameval != NULL)
		nwam_value_free(keynameval);

	if (kwh != NULL)
		nwam_known_wlan_free(kwh);

	return (err);
}

/* Performs a scan on a wifi link NCU */
/* ARGSUSED */
static int
nwamd_ncu_known_wlan_committed(nwamd_object_t object, void *data)
{
	nwamd_ncu_t *ncu_data = object->nwamd_object_data;

	if (ncu_data->ncu_type != NWAM_NCU_TYPE_LINK)
		return (0);

	/* network selection will be done only if possible */
	if (ncu_data->ncu_link.nwamd_link_media == DL_WIFI)
		(void) nwamd_wlan_scan(ncu_data->ncu_name);
	return (0);
}

/* Handle known WLAN initialization/refresh event */
/* ARGSUSED */
void
nwamd_known_wlan_handle_init_event(nwamd_event_t known_wlan_event)
{
	/*
	 * Since the Known WLAN list has changed, do a rescan so that the
	 * best network is selected.
	 */
	(void) nwamd_walk_objects(NWAM_OBJECT_TYPE_NCU,
	    nwamd_ncu_known_wlan_committed, NULL);
}

void
nwamd_known_wlan_handle_action_event(nwamd_event_t known_wlan_event)
{
	switch (known_wlan_event->event_msg->nwe_data.nwe_object_action.
	    nwe_action) {
	case NWAM_ACTION_ADD:
	case NWAM_ACTION_REFRESH:
		nwamd_known_wlan_handle_init_event(known_wlan_event);
		break;
	case NWAM_ACTION_DESTROY:
		/* Nothing needs to be done for destroy */
		break;
	/* all other events are invalid for known WLANs */
	case NWAM_ACTION_ENABLE:
	case NWAM_ACTION_DISABLE:
	default:
		nlog(LOG_INFO, "nwam_known_wlan_handle_action_event: "
		    "unexpected action");
		break;
	}
}

int
nwamd_known_wlan_action(const char *known_wlan, nwam_action_t action)
{
	nwamd_event_t known_wlan_event = nwamd_event_init_object_action
	    (NWAM_OBJECT_TYPE_KNOWN_WLAN, known_wlan, NULL, action);
	if (known_wlan_event == NULL)
		return (1);
	nwamd_event_enqueue(known_wlan_event);
	return (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 2010 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _KNOWN_WLANS_H
#define	_KNOWN_WLANS_H

#include <libnwam.h>
#include <syslog.h>

void upgrade_known_wifi_nets_config(void);
nwam_error_t known_wlan_get_keyname(const char *, char *);
nwam_error_t known_wlan_get_keyslot(const char *, uint_t *);

#endif /* _KNOWN_WLANS_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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * This file is here for legacy support.
 */

#include <atomic.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <libdllink.h>
#include <libscf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include <libnwam.h>
#include "known_wlans.h"
#include "llp.h"
#include "ncu.h"
#include "util.h"

/*
 * This file formerly contained the routines that manipulate Link Layer
 * Profiles (aka LLPs) and various support functions.  Now only code
 * necessary for parsing the legacy /etc/nwam/llp file on upgrade is included,
 * since this legacy configuration needs to be translated into the User NCP.
 */

#define	OUR_OLD_DHCP_WAIT_TIME_PROP_NAME	"dhcp_wait_time"
#define	OUR_OLD_USE_NET_SVC_PROP_NAME		"use_net_svc"
#define	OUR_OLD_IDLE_TIME_PROP_NAME		"idle_time"

static struct qelem llp_list;

/*
 * Global variable to hold the highest priority.  Need to use the atomic
 * integer arithmetic functions to update it.
 */
static uint32_t llp_highest_pri;

/* Specifies if static address has been configured in /etc/nwam/llp */
static boolean_t static_configured = B_FALSE;

static enum interface_type
find_if_type(const char *name)
{
	uint32_t media;
	enum interface_type type;

	if (name == NULL) {
		nlog(LOG_DEBUG, "find_if_type: no ifname; "
		    "returning IF_UNKNOWN");
		return (IF_UNKNOWN);
	}

	type = IF_WIRED;
	if (dladm_name2info(dld_handle, name, NULL, NULL, NULL, &media) !=
	    DLADM_STATUS_OK) {
		if (strncmp(name, "ip.tun", 6) == 0 ||
		    strncmp(name, "ip6.tun", 7) == 0 ||
		    strncmp(name, "ip.6to4tun", 10) == 0)
			/*
			 * We'll need to update our tunnel detection once
			 * the clearview/tun project is integrated; tunnel
			 * names won't necessarily be ip.tunN.
			 */
			type = IF_TUN;
	} else if (media == DL_WIFI) {
		type = IF_WIRELESS;
	}

	return (type);
}

static void
llp_list_free(void)
{
	llp_t *llp;

	while (llp_list.q_forw != &llp_list) {
		llp = (llp_t *)llp_list.q_forw;
		remque(&llp->llp_links);
		free(llp->llp_ipv6addrstr);
		free(llp->llp_ipv4addrstr);
		free(llp);
	}
}

static void
initialize_llp(void)
{
	llp_list.q_forw = llp_list.q_back = &llp_list;
}

static llp_t *
llp_lookup(const char *link)
{
	llp_t *llp;

	if (link == NULL)
		return (NULL);

	for (llp = (llp_t *)llp_list.q_forw; llp != (llp_t *)&llp_list;
	    llp = (llp_t *)llp->llp_links.q_forw) {
		if (strcmp(link, llp->llp_lname) == 0)
			break;
	}
	if (llp == (llp_t *)&llp_list)
		llp = NULL;
	return (llp);
}

/*
 * Create the named LLP with default settings.  Called only in main thread.
 */
static llp_t *
llp_add(const char *name)
{
	llp_t *llp;

	if ((llp = calloc(1, sizeof (llp_t))) == NULL) {
		nlog(LOG_ERR, "llp_add: cannot allocate LLP: %m");
		return (NULL);
	}

	if (strlcpy(llp->llp_lname, name, sizeof (llp->llp_lname)) >=
	    sizeof (llp->llp_lname)) {
		nlog(LOG_ERR, "llp_add: linkname '%s' too long; ignoring entry",
		    name);
		free(llp);
		return (NULL);
	}

	llp->llp_fileorder = llp->llp_pri =
	    atomic_add_32_nv(&llp_highest_pri, 1);
	llp->llp_ipv4src = IPV4SRC_DHCP;
	llp->llp_type = find_if_type(llp->llp_lname);
	llp->llp_ipv6onlink = B_TRUE;

	/*
	 * should be a no-op, but for now, make sure we only
	 * create llps for wired and wireless interfaces.
	 */
	if (llp->llp_type != IF_WIRED && llp->llp_type != IF_WIRELESS) {
		nlog(LOG_ERR, "llp_add: wrong type of interface for %s", name);
		free(llp);
		return (NULL);
	}
	insque(&llp->llp_links, llp_list.q_back);

	nlog(LOG_DEBUG, "llp_add: "
	    "created llp for link %s, priority %d", llp->llp_lname,
	    llp->llp_pri);
	return (llp);
}

static int
parse_llp_config(void)
{
	static const char STATICSTR[] = "static";
	static const char DHCP[] = "dhcp";
	static const char IPV6[] = "ipv6";
	static const char NOIPV6[] = "noipv6";
	static const char PRIORITY[] = "priority";
	FILE *fp;
	char line[LINE_MAX];
	char *cp, *lasts, *lstr, *srcstr, *addrstr;
	int lnum;
	llp_t *llp;

	initialize_llp();

	fp = fopen(LLPFILE, "r+");
	if (fp == NULL) {
		if (errno == ENOENT)
			return (errno);
		nlog(LOG_ERR, "parse_llp_config: "
		    "open legacy LLP config file: %m");
		return (-1);
	}

	for (lnum = 1; fgets(line, sizeof (line), fp) != NULL; lnum++) {
		if (line[strlen(line) - 1] == '\n')
			line[strlen(line) - 1] = '\0';

		cp = line;
		while (isspace(*cp))
			cp++;

		if (*cp == '#' || *cp == '\0')
			continue;

		nlog(LOG_DEBUG, "parse_llp_config: "
		    "parsing legacy LLP conf file line %d...", lnum);

		if (((lstr = strtok_r(cp, " \t", &lasts)) == NULL) ||
		    ((srcstr = strtok_r(NULL, " \t", &lasts)) == NULL)) {
			nlog(LOG_ERR, "parse_llp_config: line %d: "
			    "not enough tokens; ignoring entry", lnum);
			continue;
		}

		if ((llp = llp_lookup(lstr)) == NULL &&
		    (llp = llp_add(lstr)) == NULL) {
			nlog(LOG_ERR, "parse_llp_config: line %d: "
			    "cannot add entry", lnum);
			continue;
		}

		if (strcasecmp(srcstr, STATICSTR) == 0) {
			if ((addrstr = strtok_r(NULL, " \t", &lasts)) == NULL ||
			    atoi(addrstr) == 0) { /* crude check for number */
				nlog(LOG_ERR, "parse_llp_config: line %d: "
				    "missing ipaddr for static config", lnum);
			} else if ((addrstr = strdup(addrstr)) == NULL) {
				nlog(LOG_ERR, "parse_llp_config: line %d: "
				    "cannot save address", lnum);
			} else {
				free(llp->llp_ipv4addrstr);
				llp->llp_ipv4src = IPV4SRC_STATIC;
				llp->llp_ipv4addrstr = addrstr;
			}

		} else if (strcasecmp(srcstr, DHCP) == 0) {
			llp->llp_ipv4src = IPV4SRC_DHCP;

		} else if (strcasecmp(srcstr, IPV6) == 0) {
			llp->llp_ipv6onlink = B_TRUE;
			if ((addrstr = strtok_r(NULL, " \t", &lasts)) == NULL) {
				(void) 0;
			} else if ((addrstr = strdup(addrstr)) == NULL) {
				nlog(LOG_ERR, "parse_llp_config: line %d: "
				    "cannot save address", lnum);
			} else {
				free(llp->llp_ipv6addrstr);
				llp->llp_ipv6addrstr = addrstr;
			}

		} else if (strcasecmp(srcstr, NOIPV6) == 0) {
			llp->llp_ipv6onlink = B_FALSE;

		} else if (strcasecmp(srcstr, PRIORITY) == 0) {
			if ((addrstr = strtok_r(NULL, " \t", &lasts)) == NULL) {
				nlog(LOG_ERR,
				    "parse_llp_config: line %d: "
				    "missing priority value", lnum);
			} else {
				llp->llp_pri = atoi(addrstr);
			}

		} else {
			nlog(LOG_ERR, "parse_llp_config: line %d: "
			    "unrecognized field '%s'", lnum, srcstr);
		}
	}

	(void) fclose(fp);
	return (0);
}

/*
 * Translate legacy LLP config into the user NCP.
 */
static int
upgrade_llp_config(void)
{
	llp_t *wp;
	nwam_ncp_handle_t user_ncp;
	nwam_ncu_handle_t phys_ncu = NULL, ip_ncu = NULL;
	nwam_error_t err;
	uint64_t uintval;
	char *strval;
	const char *prop;

	switch (parse_llp_config()) {
	case -1:
		return (0);
	case ENOENT:
		return (ENOENT);
	default:
		break;
	}

	err = nwam_ncp_create(NWAM_NCP_NAME_USER, 0, &user_ncp);
	switch (err) {
	case NWAM_SUCCESS:
		break;
	case NWAM_ERROR_BIND:
	case NWAM_ERROR_INTERNAL:
		nlog(LOG_ERR, "upgrade_llp_config: "
		    "could not create User NCP: %s", nwam_strerror(err));
		llp_list_free();
		return (EAGAIN);
	default:
		nlog(LOG_ERR, "upgrade_llp_config: error creating User NCP: %s",
		    nwam_strerror(err));
		llp_list_free();
		return (0);
	}

	nlog(LOG_DEBUG, "upgrade_llp_config: walking llp list");

	for (wp = (llp_t *)llp_list.q_forw; wp != (llp_t *)&llp_list;
	    wp = (llp_t *)wp->llp_links.q_forw) {

		nlog(LOG_DEBUG, "upgrade_llp_config: "
		    "upgrading llp %s", wp->llp_lname);

		if (nwam_ncu_create(user_ncp, wp->llp_lname,
		    NWAM_NCU_TYPE_INTERFACE, NWAM_NCU_CLASS_IP, &ip_ncu)
		    != NWAM_SUCCESS ||
		    nwam_ncu_create(user_ncp, wp->llp_lname, NWAM_NCU_TYPE_LINK,
		    NWAM_NCU_CLASS_PHYS, &phys_ncu) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "upgrade_llp_config: llp %s: "
			    "could not create NCUs: %s", wp->llp_lname,
			    nwam_strerror(err));
			break;
		}

		/* Link NCU properties */
		prop = NWAM_NCU_PROP_ACTIVATION_MODE;
		uintval = NWAM_ACTIVATION_MODE_PRIORITIZED;
		if ((err = nwamd_set_ncu_uint(phys_ncu, &uintval, 1, prop))
		    != NWAM_SUCCESS)
			break;

		prop = NWAM_NCU_PROP_PRIORITY_MODE;
		uintval = NWAM_PRIORITY_MODE_EXCLUSIVE;
		if ((err = nwamd_set_ncu_uint(phys_ncu, &uintval, 1, prop))
		    != NWAM_SUCCESS)
			break;

		prop = NWAM_NCU_PROP_PRIORITY_GROUP;
		uintval = wp->llp_pri;
		if ((err = nwamd_set_ncu_uint(phys_ncu, &uintval, 1, prop))
		    != NWAM_SUCCESS)
			break;

		/* IP NCU properties */
		if (wp->llp_ipv4addrstr != NULL) {
			/* Set v4 address and specify static addrsrc */
			prop = NWAM_NCU_PROP_IPV4_ADDRSRC;
			uintval = NWAM_ADDRSRC_STATIC;
			if ((err = nwamd_set_ncu_uint(ip_ncu, &uintval, 1,
			    prop)) != NWAM_SUCCESS)
				break;

			prop = NWAM_NCU_PROP_IPV4_ADDR;
			strval = wp->llp_ipv4addrstr;
			if ((err = nwamd_set_ncu_string(ip_ncu, &strval, 1,
			    prop)) != NWAM_SUCCESS)
				break;

			static_configured = B_TRUE;
		}

		if (wp->llp_ipv6addrstr != NULL) {
			/* Set v6 address and specify static addrsrc */
			prop = NWAM_NCU_PROP_IPV6_ADDRSRC;
			uintval = NWAM_ADDRSRC_STATIC;
			if ((err = nwamd_set_ncu_uint(ip_ncu, &uintval, 1,
			    prop)) != NWAM_SUCCESS)
				break;

			prop = NWAM_NCU_PROP_IPV6_ADDR;
			strval = wp->llp_ipv6addrstr;
			if ((err = nwamd_set_ncu_string(ip_ncu, &strval, 1,
			    prop)) != NWAM_SUCCESS)
				break;

			static_configured = B_TRUE;
		}

		if (!wp->llp_ipv6onlink) {
			prop = NWAM_NCU_PROP_IP_VERSION;
			uintval = IPV4_VERSION;
			if ((err = nwamd_set_ncu_uint(ip_ncu, &uintval, 1,
			    prop)) != NWAM_SUCCESS)
				break;
		}

		if ((err = nwam_ncu_commit(ip_ncu, 0)) != NWAM_SUCCESS ||
		    (err = nwam_ncu_commit(phys_ncu, 0)) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "upgrade_llp_config: llp %s: "
			    "could not commit NCUs: %s", wp->llp_lname,
			    nwam_strerror(err));
			/* Schedule a retry - root filesystem may be readonly */
			llp_list_free();
			nwam_ncu_free(ip_ncu);
			nwam_ncu_free(phys_ncu);
			(void) nwam_ncp_destroy(user_ncp, 0);
			return (EAGAIN);
		}
	}

	if (err != NWAM_SUCCESS) {
		nlog(LOG_ERR, "upgrade_llp_config: llp %s: "
		    "could not set value for property %s: %s", wp->llp_lname,
		    prop, nwam_strerror(err));
	}
	llp_list_free();
	nwam_ncu_free(ip_ncu);
	nwam_ncu_free(phys_ncu);
	nwam_ncp_free(user_ncp);
	return (0);
}

/*
 * Upgrade legacy llp and known_wifi_nets files. Note - it is possible that
 * the root filesystem is not writable at this point, so we need to schedule
 * a retry of the upgrade operation in the event that committing the new
 * config fails.
 */
/* ARGSUSED0 */
void
nwamd_handle_upgrade(nwamd_event_t event)
{
	nwamd_event_t upgrade_event;
	uint64_t dhcp_wait_time, idle_time;
	boolean_t use_net_svc;

	switch (upgrade_llp_config()) {
	case -1:
	case ENOENT:
		/* Nothing readable to upgrade */
		break;
	case EAGAIN:
		/*
		 * Schedule retry in NWAMD_READONLY_RETRY_INTERVAL seconds
		 * as root fs may be readonly.
		 *
		 * The upgrade event is of type NCU, but has no associated
		 * object (we use the event type to map to the appropriate
		 * event/method mappings, so to find the NCU upgrade event
		 * method we specify type NCU while not specifying an
		 * object since all NCUs have to be upgraded.
		 */
		upgrade_event = nwamd_event_init(NWAM_EVENT_TYPE_UPGRADE,
		    NWAM_OBJECT_TYPE_NCP, 0, NULL);
		if (upgrade_event == NULL) {
			nlog(LOG_ERR, "nwamd_handle_upgrade: "
			    "could not create retry event to upgrade "
			    "%s configuration", LLPFILE);
			return;
		}
		nwamd_event_enqueue_timed(upgrade_event,
		    NWAMD_READONLY_RETRY_INTERVAL);
		return;
	default:
		break;
	}

	/*
	 * If static_configured is set, then at least one static address is
	 * configured in /etc/nwam/llp.  Enable the User NCP in this case.
	 */
	if (static_configured) {
		nlog(LOG_DEBUG, "nwamd_handle_upgrade: "
		    "static address configured, enabling User NCP");
		(void) pthread_mutex_lock(&active_ncp_mutex);
		(void) strlcpy(active_ncp, NWAM_NCP_NAME_USER,
		    NWAM_MAX_NAME_LEN);
		(void) pthread_mutex_unlock(&active_ncp_mutex);
	}

	/* upgrade /etc/nwam/known_wifi_nets */
	upgrade_known_wifi_nets_config();

	/*
	 * SMF property nwamd/dhcp_wait_time in Phase 0/0.5 has been
	 * replaced by nwamd/ncu_wait_time property.  If the dhcp_wait_time
	 * property exists (which means it has been changed by the user),
	 * set its value to ncu_wait_time and remove the property.
	 */
	if (nwamd_lookup_count_property(OUR_FMRI, OUR_PG,
	    OUR_OLD_DHCP_WAIT_TIME_PROP_NAME, &dhcp_wait_time) == 0) {
		(void) nwamd_set_count_property(OUR_FMRI, OUR_PG,
		    OUR_NCU_WAIT_TIME_PROP_NAME, dhcp_wait_time);
		(void) nwamd_delete_scf_property(OUR_FMRI, OUR_PG,
		    OUR_OLD_DHCP_WAIT_TIME_PROP_NAME);
		nlog(LOG_DEBUG, "nwamd_handle_upgrade: "
		    "converted '%s' to '%s' with value of %lld",
		    OUR_OLD_DHCP_WAIT_TIME_PROP_NAME,
		    OUR_NCU_WAIT_TIME_PROP_NAME, dhcp_wait_time);
	}

	/*
	 * If the user has changed Phase 0/0.5 properties that don't exist in
	 * Phase 1, manifest-import reports a warning; but those properties are
	 * not removed.  nwamd/use_net_svc and nwamd/idle_time are two
	 * properties that don't exist in Phase 1.  If they exist, remove them.
	 */
	if (nwamd_lookup_count_property(OUR_FMRI, OUR_PG,
	    OUR_OLD_IDLE_TIME_PROP_NAME, &idle_time) == 0) {
		(void) nwamd_delete_scf_property(OUR_FMRI, OUR_PG,
		    OUR_OLD_IDLE_TIME_PROP_NAME);
	}
	if (nwamd_lookup_boolean_property(OUR_FMRI, OUR_PG,
	    OUR_OLD_USE_NET_SVC_PROP_NAME, &use_net_svc) == 0) {
		(void) nwamd_delete_scf_property(OUR_FMRI, OUR_PG,
		    OUR_OLD_USE_NET_SVC_PROP_NAME);
	}

	nlog(LOG_DEBUG, "nwamd_handle_upgrade: "
	    "creating version property, setting to 1\n");
	(void) nwamd_set_count_property(OUR_FMRI, OUR_PG,
	    OUR_VERSION_PROP_NAME, 1U);
	(void) smf_refresh_instance(OUR_FMRI);
}
/*
 * 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.
 */

#ifndef _LLP_H
#define	_LLP_H

#include <search.h>
#include <libnwam.h>
#include <syslog.h>

#include "events.h"

/*
 * This file is here for legacy support.
 */

#define	LLPDIR		"/etc/nwam"
#define	LLPFILE		LLPDIR"/llp"

enum interface_type {
    IF_UNKNOWN, IF_WIRED, IF_WIRELESS, IF_TUN
};

typedef enum {
	IPV4SRC_STATIC,
	IPV4SRC_DHCP
} ipv4src_t;

/*
 * This structure contains a representation of legacy LLP configuration
 * which previously represented the intended configuration of the system as
 * differentiated from the actual IPv4 configuration of the system represented
 * by the interface structures.
 *
 * llp structures are held on the list llp_head.
 */
typedef struct llp {
	struct qelem llp_links;
	char	llp_lname[LIFNAMSIZ];
	uint32_t llp_pri;		/* lower number => higher priority */
	int	llp_fileorder;
	enum interface_type llp_type;
	ipv4src_t llp_ipv4src;
	char	*llp_ipv4addrstr;	/* if ipsrc is STATIC */
	char	*llp_ipv6addrstr;	/* if the user provided a static addr */
	boolean_t llp_ipv6onlink;	/* true if we plumb up a v6 interface */
} llp_t;

extern llp_t *link_layer_profile;

void nwamd_handle_upgrade(nwamd_event_t);

#endif /* _LLP_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.
 */

#include <arpa/inet.h>
#include <errno.h>
#include <inet/ip.h>
#include <libdladm.h>
#include <libdllink.h>
#include <libdlwlan.h>
#include <libscf.h>
#include <limits.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>

#include <libnwam.h>
#include "conditions.h"
#include "events.h"
#include "objects.h"
#include "util.h"

/*
 * loc.c - contains routines which handle location abstraction.
 */

pthread_mutex_t active_loc_mutex = PTHREAD_MUTEX_INITIALIZER;
char active_loc[NWAM_MAX_NAME_LEN];

static int
loc_create_init_fini_event(nwam_loc_handle_t loch, void *data)
{
	boolean_t *init = data;
	char *name;
	nwamd_event_t event;

	if (nwam_loc_get_name(loch, &name) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "loc_init_fini: could not get loc name");
		return (0);
	}

	event = nwamd_event_init(*init ?
	    NWAM_EVENT_TYPE_OBJECT_INIT : NWAM_EVENT_TYPE_OBJECT_FINI,
	    NWAM_OBJECT_TYPE_LOC, 0, name);
	if (event != NULL)
		nwamd_event_enqueue(event);
	free(name);

	return (0);
}

/*
 * Walk all locs, creating init events for each.
 */
void
nwamd_init_locs(void)
{
	boolean_t init = B_TRUE;

	/* Unset active location */
	(void) pthread_mutex_lock(&active_loc_mutex);
	active_loc[0] = '\0';
	(void) pthread_mutex_unlock(&active_loc_mutex);
	(void) nwam_walk_locs(loc_create_init_fini_event, &init, 0, NULL);
}

/*
 * Walk all locs, creating fini events for each.
 */
void
nwamd_fini_locs(void)
{
	boolean_t init = B_FALSE;

	(void) nwam_walk_locs(loc_create_init_fini_event, &init, 0, NULL);
}

static boolean_t
loc_is_enabled(nwam_loc_handle_t loch)
{
	nwam_value_t enabledval;
	boolean_t enabled = B_FALSE;

	if (nwam_loc_get_prop_value(loch, NWAM_LOC_PROP_ENABLED,
	    &enabledval) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "loc_is_enabled: could not retrieve "
		    "enabled value");
		return (B_FALSE);
	}
	if (nwam_value_get_boolean(enabledval, &enabled)
	    != NWAM_SUCCESS) {
		nlog(LOG_ERR, "loc_is_enabled: could not retrieve "
		    "enabled value");
		nwam_value_free(enabledval);
		return (B_FALSE);
	}
	nwam_value_free(enabledval);
	return (enabled);
}

static int64_t
loc_get_activation_mode(nwam_loc_handle_t loch)
{
	nwam_error_t err;
	uint64_t activation;
	nwam_value_t activationval;

	if (nwam_loc_get_prop_value(loch, NWAM_LOC_PROP_ACTIVATION_MODE,
	    &activationval)  != NWAM_SUCCESS) {
		nlog(LOG_ERR, "loc_get_activation_mode: could not retrieve "
		    "activation mode value");
		return (-1);
	}
	err = nwam_value_get_uint64(activationval, &activation);
	nwam_value_free(activationval);
	if (err != NWAM_SUCCESS) {
		nlog(LOG_ERR, "loc_get_activation_mode: could not retrieve "
		    "activation mode value");
		return (-1);
	}

	return ((int64_t)activation);
}

/* Enables the location. */
static void
nwamd_loc_activate(const char *object_name)
{
	char *enabled;

	nlog(LOG_DEBUG, "nwamd_loc_activate: activating loc %s",
	    object_name);

	/*
	 * Find currently enabled location and change its state to disabled
	 * if it is a manual location, or offline (if it is not).
	 * Only manual locations reach disabled, since conditional and
	 * system locations which are manually disabled simply revert to
	 * their conditions for activation.
	 */
	if ((enabled = malloc(NWAM_MAX_NAME_LEN)) != NULL &&
	    nwamd_lookup_string_property(NET_LOC_FMRI, NET_LOC_PG,
	    NET_LOC_SELECTED_PROP, enabled, NWAM_MAX_NAME_LEN) == 0) {
		/* Only change state if current != new */
		if (strcmp(enabled, object_name) != 0) {
			boolean_t do_disable = B_FALSE;
			nwamd_object_t eobj = nwamd_object_find
			    (NWAM_OBJECT_TYPE_LOC, enabled);
			if (eobj == NULL) {
				nlog(LOG_INFO, "nwamd_loc_activate: could not "
				    "find old location %s", enabled);
				goto skip_disable;
			}
			/*
			 * Disable if the old location was manual, since the
			 * only way a manual location can deactivate is if
			 * it is disabled.
			 */
			do_disable =
			    (loc_get_activation_mode(eobj->nwamd_object_handle)
			    == (int64_t)NWAM_ACTIVATION_MODE_MANUAL);
			nwamd_object_release(eobj);

			if (do_disable) {
				nlog(LOG_DEBUG, "nwamd_loc_activate: "
				    "disable needed for old location %s",
				    enabled);
				nwamd_object_set_state
				    (NWAM_OBJECT_TYPE_LOC, enabled,
				    NWAM_STATE_DISABLED,
				    NWAM_AUX_STATE_MANUAL_DISABLE);
			} else {
				nlog(LOG_DEBUG, "nwamd_loc_activate: "
				    "offline needed for old location %s",
				    enabled);
				nwamd_object_set_state
				    (NWAM_OBJECT_TYPE_LOC, enabled,
				    NWAM_STATE_OFFLINE,
				    NWAM_AUX_STATE_CONDITIONS_NOT_MET);
			}
		}
	}
skip_disable:
	free(enabled);

	if (nwamd_set_string_property(NET_LOC_FMRI, NET_LOC_PG,
	    NET_LOC_SELECTED_PROP, object_name) == 0) {
		char *state = smf_get_state(NET_LOC_FMRI);
		nlog(LOG_INFO, "nwamd_loc_activate: set %s/%s to %s; "
		    "service is in %s state", NET_LOC_PG, NET_LOC_SELECTED_PROP,
		    object_name, state == NULL ? "unknown" : state);
		free(state);
		(void) smf_restore_instance(NET_LOC_FMRI);
		if (smf_refresh_instance(NET_LOC_FMRI) == 0) {
			(void) pthread_mutex_lock(&active_loc_mutex);
			(void) strlcpy(active_loc, object_name,
			    sizeof (active_loc));
			(void) pthread_mutex_unlock(&active_loc_mutex);
			nwamd_object_set_state(NWAM_OBJECT_TYPE_LOC,
			    object_name,
			    NWAM_STATE_ONLINE, NWAM_AUX_STATE_ACTIVE);
		} else {
			nlog(LOG_ERR, "nwamd_loc_activate: "
			    "%s could not be refreshed", NET_LOC_FMRI);
			nwamd_object_set_state(NWAM_OBJECT_TYPE_LOC,
			    object_name,
			    NWAM_STATE_MAINTENANCE,
			    NWAM_AUX_STATE_METHOD_FAILED);
		}
	}
}

struct nwamd_loc_check_walk_arg {
	nwamd_object_t winning_object;
	uint64_t winning_rating;
};

/*
 * Determine which location should be activated.
 */
static int
nwamd_loc_check(nwamd_object_t object, void *data)
{
	struct nwamd_loc_check_walk_arg *wa = data;
	nwam_loc_handle_t loch = object->nwamd_object_handle;
	nwam_value_t conditionval;
	int64_t lactivation;
	uint64_t rating, activation;
	boolean_t satisfied;
	char **conditions;
	uint_t nelem;

	lactivation = loc_get_activation_mode(object->nwamd_object_handle);

	if (lactivation == -1)
		return (0);

	activation = (uint64_t)lactivation;
	switch (activation) {
	case NWAM_ACTIVATION_MODE_MANUAL:
		if (loc_is_enabled(loch)) {
			/* Manually enabled locations should always win out. */
			nlog(LOG_DEBUG, "nwamd_loc_check: %s is enabled",
			    object->nwamd_object_name);
			wa->winning_object = object;
			wa->winning_rating = UINT64_MAX;
		} else {
			nlog(LOG_DEBUG, "nwamd_loc_check: %s is disabled",
			    object->nwamd_object_name);
			if (object->nwamd_object_state != NWAM_STATE_DISABLED) {
				nwamd_object_set_state(NWAM_OBJECT_TYPE_LOC,
				    object->nwamd_object_name,
				    NWAM_STATE_DISABLED,
				    NWAM_AUX_STATE_MANUAL_DISABLE);
			}
		}

		return (0);

	case NWAM_ACTIVATION_MODE_CONDITIONAL_ANY:
	case NWAM_ACTIVATION_MODE_CONDITIONAL_ALL:
		if (loc_is_enabled(loch)) {
			/* Manually enabled locations should always win out. */
			nlog(LOG_DEBUG, "nwamd_loc_check: %s is enabled",
			    object->nwamd_object_name);
			wa->winning_object = object;
			wa->winning_rating = UINT64_MAX;
		}

		if (nwam_loc_get_prop_value(loch,
		    NWAM_LOC_PROP_CONDITIONS, &conditionval) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "nwamd_loc_check: could not retrieve "
			    "condition value");
			return (0);
		}
		if (nwam_value_get_string_array(conditionval,
		    &conditions, &nelem) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "nwamd_loc_check: could not retrieve "
			    "condition value");
			nwam_value_free(conditionval);
			return (0);
		}
		satisfied = nwamd_check_conditions(activation, conditions,
		    nelem);

		if (satisfied) {
			rating = nwamd_rate_conditions(activation,
			    conditions, nelem);
			if (rating > wa->winning_rating) {
				wa->winning_object = object;
				wa->winning_rating = rating;
			}
		}
		nwam_value_free(conditionval);
		return (0);

	case NWAM_ACTIVATION_MODE_SYSTEM:
		if (loc_is_enabled(loch)) {
			/* Manually enabled locations should always win out. */
			nlog(LOG_DEBUG, "nwamd_loc_check: %s is enabled",
			    object->nwamd_object_name);
			wa->winning_object = object;
			wa->winning_rating = UINT64_MAX;
		}

		/* Either NoNet, Automatic or Legacy location, so skip. */

		return (0);
	default:
		return (0);
	}
	/*NOTREACHED*/
	return (0);
}

static int
nwamd_ncu_online_check(nwamd_object_t object, void *data)
{
	boolean_t *online = data;
	nwamd_ncu_t *ncu_data = object->nwamd_object_data;

	if (ncu_data->ncu_type != NWAM_NCU_TYPE_INTERFACE)
		return (0);

	if (object->nwamd_object_state == NWAM_STATE_ONLINE) {
		/* An online IP NCU found, stop walk */
		*online = B_TRUE;
		return (1);
	}
	return (0);
}

void
nwamd_loc_check_conditions(void)
{
	struct nwamd_loc_check_walk_arg wa = { NULL, 0 };
	const char *winning_loc;
	boolean_t ncu_online = B_FALSE;
	boolean_t is_active;

	/*
	 * Walk the NCUs to find out if at least one IP NCU is online.  If so,
	 * check the activation-mode and conditions.  If not, enable the NoNet
	 * location.
	 */
	(void) nwamd_walk_objects(NWAM_OBJECT_TYPE_NCU, nwamd_ncu_online_check,
	    &ncu_online);

	if (!ncu_online) {
		winning_loc = NWAM_LOC_NAME_NO_NET;
	} else {
		(void) nwamd_walk_objects(NWAM_OBJECT_TYPE_LOC, nwamd_loc_check,
		    &wa);
		if (wa.winning_object != NULL)
			winning_loc = wa.winning_object->nwamd_object_name;
		else
			winning_loc = NWAM_LOC_NAME_AUTOMATIC;
	}
	nlog(LOG_DEBUG, "nwamd_loc_check_conditions: winning loc is %s",
	    winning_loc);

	/* If the winning location is already active, do nothing */
	(void) pthread_mutex_lock(&active_loc_mutex);
	is_active = (strcmp(active_loc, winning_loc) == 0);
	(void) pthread_mutex_unlock(&active_loc_mutex);
	if (is_active)
		return;

	nwamd_object_set_state(NWAM_OBJECT_TYPE_LOC, winning_loc,
	    NWAM_STATE_OFFLINE_TO_ONLINE, NWAM_AUX_STATE_METHOD_RUNNING);
}

int
nwamd_loc_action(const char *loc, nwam_action_t action)
{
	nwamd_event_t event = nwamd_event_init_object_action
	    (NWAM_OBJECT_TYPE_LOC, loc, NULL, action);
	if (event == NULL)
		return (1);
	nwamd_event_enqueue(event);
	return (0);
}

/*
 * Event handling functions.
 */

/* Handle loc initialization/refresh event */
void
nwamd_loc_handle_init_event(nwamd_event_t event)
{
	nwamd_object_t object;
	nwam_loc_handle_t loch;
	nwam_error_t err;
	boolean_t new_enabled, old_enabled = B_FALSE;
	nwam_state_t state;

	if ((err = nwam_loc_read(event->event_object, 0, &loch))
	    != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_loc_handle_init_event: could not "
		    "read object '%s': %s", event->event_object,
		    nwam_strerror(err));
		nwamd_event_do_not_send(event);
		return;
	}
	if ((object = nwamd_object_find(NWAM_OBJECT_TYPE_LOC,
	    event->event_object)) != NULL) {
		old_enabled = loc_is_enabled(object->nwamd_object_handle);
		nwam_loc_free(object->nwamd_object_handle);
		object->nwamd_object_handle = loch;
	} else {
		object = nwamd_object_init(NWAM_OBJECT_TYPE_LOC,
		    event->event_object, loch, NULL);
		object->nwamd_object_state = NWAM_STATE_OFFLINE;
		object->nwamd_object_aux_state =
		    NWAM_AUX_STATE_CONDITIONS_NOT_MET;
	}
	new_enabled = loc_is_enabled(loch);
	state = object->nwamd_object_state;
	nwamd_object_release(object);

	/*
	 * If this location is ONLINE and the value of the "enabled" property
	 * has not changed, then this location is getting refreshed because it
	 * was committed with changes.  Change states to re-activate itself.
	 * If the "enabled" property has changed, then this location is
	 * getting refreshed as part of a enable/disable action and there is
	 * no need to change states here.
	 */
	if (state == NWAM_STATE_ONLINE && old_enabled == new_enabled) {
		nwamd_object_set_state(NWAM_OBJECT_TYPE_LOC,
		    event->event_object, NWAM_STATE_OFFLINE_TO_ONLINE,
		    NWAM_AUX_STATE_METHOD_RUNNING);
	}
}

/* Handle loc finish event */
void
nwamd_loc_handle_fini_event(nwamd_event_t event)
{
	nwamd_object_t object;

	nlog(LOG_DEBUG, "nwamd_loc_handle_fini_event(%s)",
	    event->event_object);

	/* Don't disable the location, as this can enable the Automatic loc */
	if ((object = nwamd_object_find(NWAM_OBJECT_TYPE_LOC,
	    event->event_object)) == NULL) {
		nlog(LOG_INFO, "nwamd_loc_handle_fini_event: "
		    "loc %s not found", event->event_object);
		nwamd_event_do_not_send(event);
		return;
	}
	nwamd_object_release_and_destroy(object);
}

void
nwamd_loc_handle_action_event(nwamd_event_t event)
{
	nwamd_object_t object;

	switch (event->event_msg->nwe_data.nwe_object_action.nwe_action) {
	case NWAM_ACTION_ENABLE:
		object = nwamd_object_find(NWAM_OBJECT_TYPE_LOC,
		    event->event_object);
		if (object == NULL) {
			nlog(LOG_ERR, "nwamd_loc_handle_action_event: "
			    "could not find location %s", event->event_object);
			nwamd_event_do_not_send(event);
			return;
		}
		if (object->nwamd_object_state == NWAM_STATE_ONLINE) {
			nlog(LOG_DEBUG, "nwamd_loc_handle_action_event: "
			    "location %s already online, nothing to do",
			    event->event_object);
			nwamd_object_release(object);
			return;
		}
		nwamd_object_release(object);

		nwamd_object_set_state(NWAM_OBJECT_TYPE_LOC,
		    event->event_object, NWAM_STATE_OFFLINE_TO_ONLINE,
		    NWAM_AUX_STATE_METHOD_RUNNING);
		break;
	case NWAM_ACTION_DISABLE:
		object = nwamd_object_find(NWAM_OBJECT_TYPE_LOC,
		    event->event_object);
		if (object == NULL) {
			nlog(LOG_ERR, "nwamd_loc_handle_action_event: "
			    "could not find location %s", event->event_object);
			nwamd_event_do_not_send(event);
			return;
		}
		if (object->nwamd_object_state == NWAM_STATE_DISABLED) {
			nlog(LOG_DEBUG, "nwamd_loc_handle_action_event: "
			    "location %s already disabled, nothing to do",
			    event->event_object);
			nwamd_object_release(object);
			return;
		}
		nwamd_object_release(object);

		nwamd_object_set_state(NWAM_OBJECT_TYPE_LOC,
		    event->event_object, NWAM_STATE_ONLINE_TO_OFFLINE,
		    NWAM_AUX_STATE_MANUAL_DISABLE);
		break;
	case NWAM_ACTION_ADD:
	case NWAM_ACTION_REFRESH:
		nwamd_loc_handle_init_event(event);
		break;
	case NWAM_ACTION_DESTROY:
		nwamd_loc_handle_fini_event(event);
		break;
	default:
		nlog(LOG_INFO, "nwam_loc_handle_action_event: "
		    "unexpected action");
		break;
	}
}

void
nwamd_loc_handle_state_event(nwamd_event_t event)
{
	nwamd_object_t object;
	nwam_state_t new_state;
	nwam_aux_state_t new_aux_state;

	if ((object = nwamd_object_find(NWAM_OBJECT_TYPE_LOC,
	    event->event_object)) == NULL) {
		nlog(LOG_INFO, "nwamd_loc_handle_state_event: "
		    "state event for nonexistent loc %s", event->event_object);
		nwamd_event_do_not_send(event);
		return;
	}
	new_state = event->event_msg->nwe_data.nwe_object_state.nwe_state;
	new_aux_state =
	    event->event_msg->nwe_data.nwe_object_state.nwe_aux_state;

	if (new_state == object->nwamd_object_state &&
	    new_aux_state == object->nwamd_object_aux_state) {
		nlog(LOG_DEBUG, "nwamd_loc_handle_state_event: "
		    "loc %s already in state (%s , %s)",
		    object->nwamd_object_name,
		    nwam_state_to_string(new_state),
		    nwam_aux_state_to_string(new_aux_state));
		nwamd_object_release(object);
		return;
	}

	object->nwamd_object_state = new_state;
	object->nwamd_object_aux_state = new_aux_state;

	nlog(LOG_DEBUG, "nwamd_loc_handle_state_event: changing state for loc "
	    "%s to (%s , %s)", object->nwamd_object_name,
	    nwam_state_to_string(object->nwamd_object_state),
	    nwam_aux_state_to_string(object->nwamd_object_aux_state));

	nwamd_object_release(object);

	/*
	 * State machine for location.
	 */
	switch (new_state) {
	case NWAM_STATE_OFFLINE_TO_ONLINE:
		nwamd_loc_activate(event->event_object);
		break;
	case NWAM_STATE_ONLINE_TO_OFFLINE:
		/*
		 * Don't need to deactivate current location - condition check
		 * will activate another.  If the currently active location is
		 * being deactivated, then it is being manually deactivated;
		 * so also clear active_loc so condition checking is not
		 * confused.
		 */
		(void) pthread_mutex_lock(&active_loc_mutex);
		if (strcmp(event->event_object, active_loc) == 0)
			active_loc[0] = '\0';
		(void) pthread_mutex_unlock(&active_loc_mutex);
		nwamd_loc_check_conditions();
		break;
	case NWAM_STATE_DISABLED:
	case NWAM_STATE_OFFLINE:
	case NWAM_STATE_UNINITIALIZED:
	case NWAM_STATE_MAINTENANCE:
	case NWAM_STATE_DEGRADED:
	default:
		/* do nothing */
		break;
	}
}
/*
 * 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.
 */

#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>

#include "util.h"

/*
 * logging.c - contains various logging functions.
 */

boolean_t debug = B_TRUE;

/*
 * This idea for having this function is so that you can drop a dtrace probe
 * here and trace complete strings (not just those containing formatting).  Its
 * important that we actually format the debug strings so we could trace them
 * even if we choose not to send them to syslog.
 */
static void
log_out(int severity, const char *str)
{
	if (severity == LOG_DEBUG && !debug)
		return;

	syslog(severity, str);
}

static void
log_format(int severity, const char *fmt, va_list ap, char *buf, int bufsize)
{
	int offset;
	char vbuf[256];

	if (buf == NULL) {
		buf = vbuf;
		bufsize = sizeof (vbuf);
	}

	offset = snprintf(buf, bufsize, "%d: ", pthread_self());
	(void) vsnprintf(buf + offset, bufsize - offset, fmt, ap);

	log_out(severity, buf);
}

/*
 * This function takes a syslog severity and uses it to determine what to do
 * with the message (currently send it to syslog).
 */
void
nlog(int severity, const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	log_format(severity, fmt, ap, NULL, 0);
	va_end(ap);
}

void
pfail(const char *fmt, ...)
{
	char *msg;
	va_list ap;

	msg = malloc(256);

	va_start(ap, fmt);
	log_format(LOG_ERR, fmt, ap, msg, 256);
	va_end(ap);

	if (msg == NULL)
		msg = "ran out of memory exiting.  see log.";

	(void) puts(msg);
	exit(EXIT_FAILURE);
}
/*
 * 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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#include <errno.h>
#include <fcntl.h>
#include <libdllink.h>
#include <libintl.h>
#include <libnwam.h>
#include <locale.h>
#include <priv.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <libnwam.h>
#include "conditions.h"
#include "events.h"
#include "llp.h"
#include "ncp.h"
#include "objects.h"
#include "util.h"

/*
 * nwamd - NetWork Auto-Magic Daemon
 */

boolean_t fg = B_FALSE;
dladm_handle_t dld_handle = NULL;
ipadm_handle_t ipadm_handle = NULL;
boolean_t shutting_down = B_FALSE;

sigset_t original_sigmask;
static sigset_t sigwaitset;

static void nwamd_refresh(void);
static void graceful_shutdown(void);

/*
 * nwamd
 *
 * This is the Network Auto-Magic daemon.  For further high level information
 * see the Network Auto-Magic project and the Approachability communities
 * on opensolaris.org, nwamd(8), and the README in the source directory.
 *
 * The general structure of the code is as a set of event source threads
 * which feed events into the event handling thread. Some of these events
 * are internal-only (e.g UPGRADE), but some also involve propogation
 * to external listeners (who register via a door call into the daemon).
 *
 * signal management
 * Due to being threaded, a simple set of signal handlers would not work
 * very well for nwamd.  Instead nwamd blocks signals in all but the
 * signal handling thread at startup.
 *
 */

/*
 * In this file there are several utility functions which might otherwise
 * belong in util.c, but since they are only called from main(), they can
 * live here as static functions:
 * - nlog set-up
 * - daemonizing
 * - looking up smf(7) properties
 * - signal handling
 * - managing privileges(7)
 */

static void
start_logging(void)
{
	openlog("nwamd", LOG_PID | LOG_NDELAY, LOG_DAEMON);
}

static void
daemonize(void)
{
	pid_t pid;

	/*
	 * A little bit of magic here.  By the first fork+setsid, we
	 * disconnect from our current controlling terminal and become
	 * a session group leader.  By forking again without calling
	 * setsid again, we make certain that we are not the session
	 * group leader and can never reacquire a controlling terminal.
	 */
	if ((pid = fork()) == (pid_t)-1)
		pfail("fork 1 failed");
	if (pid != 0) {
		(void) wait(NULL);
		nlog(LOG_DEBUG, "child %ld exited, daemonizing", pid);
		_exit(0);
	}
	if (setsid() == (pid_t)-1)
		pfail("setsid");
	if ((pid = fork()) == (pid_t)-1)
		pfail("fork 2 failed");
	if (pid != 0) {
		_exit(0);
	}
	(void) chdir("/");
	(void) umask(022);
}

/* ARGSUSED */
static void *
sighandler(void *arg)
{
	int sig;

	while (!shutting_down) {
		sig = sigwait(&sigwaitset);
		nlog(LOG_DEBUG, "signal %s caught", strsignal(sig));

		switch (sig) {
		case SIGTHAW:
		case SIGHUP:
			/*
			 * Resumed from suspend or refresh.  Clear up all
			 * objects so their states start from scratch;
			 * then refresh().
			 */
			nwamd_fini_enms();
			nwamd_fini_ncus();
			nwamd_fini_locs();
			nwamd_refresh();
			break;
		case SIGUSR1:
			/*
			 * Undocumented "log ncu list" signal.
			 */
			nwamd_log_ncus();
			break;
		case SIGTERM:
			nlog(LOG_DEBUG, "%s received, shutting down",
			    strsignal(sig));
			graceful_shutdown();
			break;
		default:
			nlog(LOG_DEBUG, "unexpected signal %s received, "
			    "ignoring", strsignal(sig));
			break;
		}
	}
	return (NULL);
}

static void
init_signalhandling(void)
{
	pthread_attr_t attr;
	pthread_t sighand;
	int err;

	(void) pthread_attr_init(&attr);
	(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	if (err = pthread_create(&sighand, &attr, sighandler, NULL)) {
		nlog(LOG_ERR, "pthread_create system: %s", strerror(err));
		exit(EXIT_FAILURE);
	} else {
		nlog(LOG_DEBUG, "signal handler thread: %d", sighand);
	}
	(void) pthread_attr_destroy(&attr);
}

/*
 * Construct the set of signals that we explicitly want to deal with.
 * We block these while we're still single-threaded; this block will
 * be inherited by all the threads we create.  When we are ready to
 * start handling signals, we will start the signal handling thread,
 * which will sigwait() this same set of signals, and will thus receive
 * and handle any that are sent to the process.
 */
static void
block_signals(void)
{
	(void) sigemptyset(&sigwaitset);
	(void) sigaddset(&sigwaitset, SIGHUP);
	(void) sigaddset(&sigwaitset, SIGUSR1);
	(void) sigaddset(&sigwaitset, SIGUSR2);
	(void) sigaddset(&sigwaitset, SIGTERM);
	(void) sigaddset(&sigwaitset, SIGTHAW);
	(void) pthread_sigmask(SIG_BLOCK, &sigwaitset, &original_sigmask);
}

/*
 * Look up nwamd property values and set daemon variables appropriately.
 * This function will be called on startup and via the signal handling
 * thread on receiving a HUP (which occurs when the nwam service is
 * refreshed).
 */
static void
lookup_daemon_properties(void)
{
	char *active_ncp_tmp;
	char *scan_level_tmp;

	(void) nwamd_lookup_boolean_property(OUR_FMRI, OUR_PG,
	    OUR_DEBUG_PROP_NAME, &debug);
	(void) nwamd_lookup_boolean_property(OUR_FMRI, OUR_PG,
	    OUR_AUTOCONF_PROP_NAME, &wireless_autoconf);
	(void) nwamd_lookup_boolean_property(OUR_FMRI, OUR_PG,
	    OUR_STRICT_BSSID_PROP_NAME, &wireless_strict_bssid);

	(void) pthread_mutex_lock(&active_ncp_mutex);
	if ((active_ncp_tmp = malloc(NWAM_MAX_NAME_LEN)) == NULL ||
	    nwamd_lookup_string_property(OUR_FMRI, OUR_PG,
	    OUR_ACTIVE_NCP_PROP_NAME, active_ncp_tmp, NWAM_MAX_NAME_LEN) != 0) {
		(void) strlcpy(active_ncp, NWAM_NCP_NAME_AUTOMATIC,
		    NWAM_MAX_NAME_LEN);
	} else {
		(void) strlcpy(active_ncp, active_ncp_tmp, NWAM_MAX_NAME_LEN);
	}
	(void) pthread_mutex_unlock(&active_ncp_mutex);
	free(active_ncp_tmp);

	if (nwamd_lookup_count_property(OUR_FMRI, OUR_PG,
	    OUR_CONDITION_CHECK_INTERVAL_PROP_NAME,
	    &condition_check_interval) != 0)
		condition_check_interval = CONDITION_CHECK_INTERVAL_DEFAULT;

	if ((scan_level_tmp = malloc(NWAM_MAX_NAME_LEN)) == NULL ||
	    nwamd_lookup_string_property(OUR_FMRI, OUR_PG,
	    OUR_WIRELESS_SCAN_LEVEL_PROP_NAME, scan_level_tmp,
	    NWAM_MAX_NAME_LEN) != 0) {
		wireless_scan_level = WIRELESS_SCAN_LEVEL_DEFAULT;
	} else {
		if (dladm_wlan_str2strength(scan_level_tmp,
		    &wireless_scan_level) != DLADM_STATUS_OK)
			wireless_scan_level = DLADM_WLAN_STRENGTH_VERY_WEAK;
	}
	free(scan_level_tmp);

	if (nwamd_lookup_count_property(OUR_FMRI, OUR_PG,
	    OUR_WIRELESS_SCAN_INTERVAL_PROP_NAME, &wireless_scan_interval) != 0)
		wireless_scan_interval = WIRELESS_SCAN_INTERVAL_DEFAULT;

	if (nwamd_lookup_count_property(OUR_FMRI, OUR_PG,
	    OUR_NCU_WAIT_TIME_PROP_NAME, &ncu_wait_time) != 0)
		ncu_wait_time = NCU_WAIT_TIME_DEFAULT;

	nlog(LOG_DEBUG, "Read daemon configuration properties.");
}

/*
 * Re-read the SMF properties.
 * Reset ncu priority group (since the NCUs will have to walk
 *   through their state machines again) and schedule a check
 * Re-read objects from libnwam.
 * Also, run condition checking for locations and ENMs.
 */
static void
nwamd_refresh(void)
{
	lookup_daemon_properties();

	(void) pthread_mutex_lock(&active_ncp_mutex);
	current_ncu_priority_group = INVALID_PRIORITY_GROUP;
	(void) pthread_mutex_unlock(&active_ncp_mutex);

	nwamd_init_ncus();
	nwamd_init_enms();
	nwamd_init_locs();

	nwamd_create_ncu_check_event(0);
	nwamd_create_triggered_condition_check_event(0);
}

static void
graceful_shutdown(void)
{
	nwamd_event_t event;

	shutting_down = B_TRUE;
	nwamd_event_sources_fini();
	nwamd_door_fini();
	nwamd_fini_enms();
	nwamd_fini_ncus();
	nwamd_fini_locs();

	event = nwamd_event_init_shutdown();
	if (event == NULL)
		pfail("nwamd could not create shutdown event, exiting");
	nwamd_event_enqueue(event);
}

int
main(int argc, char *argv[])
{
	int c;
	uint64_t version;
	nwamd_event_t event;
	dladm_status_t drc;
	ipadm_status_t irc;
	uid_t uid = getuid();

	/*
	 * Block the signals we care about (and which might cause us to
	 * exit based on default disposition) until we're ready to start
	 * handling them properly...see init_signalhandling() below.
	 */
	block_signals();

	if (uid != UID_NETADM && uid != 0) {
		/*
		 * This shouldn't happen normally.  On upgrade the service might
		 * need reloading.
		 */
		pfail("nwamd should run as uid %d, not uid %d\n", UID_NETADM,
		    uid);
	}

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

	start_logging();
	nlog(LOG_INFO, "nwamd pid %d started", getpid());

	while ((c = getopt(argc, argv, "fs:")) != -1) {
		switch (c) {
			case 'f':
				fg = B_TRUE;
				break;
			default:
				nlog(LOG_ERR, "unrecognized option %c",
				    optopt);
				break;
		}
	}

	lookup_daemon_properties();

	if (!fg)
		daemonize();

	/*
	 * The dladm handle *must* be opened before privileges are dropped.
	 * The device privilege requirements, which are stored in
	 * /etc/security/device_policy, may not be loaded yet, as that's
	 * done by svc:/system/filesystem/root.  If they are not loaded,
	 * then one must have *all* privs in order to open /dev/dld, which
	 * is one of the steps performed in dladm_open().
	 */
	drc = dladm_open(&dld_handle);
	if (drc != DLADM_STATUS_OK) {
		char status_str[DLADM_STRSIZE];
		pfail("failed to open dladm handle: %s",
		    dladm_status2str(drc, status_str));
	}

	irc = ipadm_open(&ipadm_handle, 0);
	if (irc != IPADM_SUCCESS)
		pfail("failed to open ipadm handle: %s", ipadm_status2str(irc));

	/*
	 * Create the event queue before starting event sources, including
	 * signal handling, so we are ready to handle incoming events.  Also
	 * start before attempting to upgrade, in case there's a problem
	 * upgrading and we need to retry (in which case we schedule an event
	 * to do so).
	 */
	nwamd_event_queue_init();

	/*
	 * Handle upgrade of legacy config.  Absence of version property
	 * (which did not exist in phase 0 or 0.5) is the indication that
	 * we need to upgrade to phase 1 (version 1).
	 */
	if (nwamd_lookup_count_property(OUR_FMRI, OUR_PG, OUR_VERSION_PROP_NAME,
	    &version) != 0)
		nwamd_handle_upgrade(NULL);

	/*
	 * Initialize lists handling internal representations of objects.
	 */
	nwamd_object_lists_init();

	init_signalhandling();

	/* Enqueue init event */
	event = nwamd_event_init_init();
	if (event == NULL)
		pfail("nwamd could not create init event, exiting");
	nwamd_event_enqueue(event);

	/*
	 * Collect initial user configuration.
	 */

	/*
	 * Walk the physical interfaces and update the Automatic NCP to
	 * contain the IP and link NCUs for the interfaces that exist in
	 * the system.
	 */
	nwamd_walk_physical_configuration();

	/*
	 * We should initialize the door at the point that we can respond to
	 * user requests about the system but before we start actually process
	 * state changes or effecting the system.
	 */
	nwamd_door_init();

	/*
	 * Initialize data objects.
	 *
	 * Enabling an NCP involves refreshing nwam, which initializes the
	 * objects (ncu, enm, loc, known wlan).  Thus, no need to
	 * explicitly initialize these objects here.  The refresh also
	 * enqueues and NCU activation checking event.  Location and ENM
	 * condition checking are triggered by changes in NCU states.
	 */
	(void) pthread_mutex_lock(&active_ncp_mutex);
	if (nwamd_ncp_action(active_ncp, NWAM_ACTION_ENABLE) != 0)
		pfail("Initial enable failed for active NCP %s", active_ncp);
	(void) pthread_mutex_unlock(&active_ncp_mutex);

	/*
	 * Enqueue an event to start periodic checking of activation conditions.
	 */
	nwamd_create_timed_condition_check_event();

	/*
	 * These two routines safely minimize our privilege set.  They
	 * use reference counting to be safe in a threaded program.  It is
	 * gross that we escalate/deescalate to initialize this functionality
	 * but a real fix is to add functionality to do fine grained privs
	 * (and if necessary set uid to 0) in this threaded daemon.
	 */
	nwamd_escalate();
	nwamd_deescalate();

	/*
	 * Start the various agents (hooks on fds, threads) which collect events
	 */
	nwamd_event_sources_init();

	/*
	 * nwamd_event_handler() only returns on shutdown.
	 */
	nwamd_event_handler();

	ipadm_close(ipadm_handle);
	dladm_close(dld_handle);

	return (EXIT_SUCCESS);
}
/*
 * 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.
 */

#include <arpa/inet.h>
#include <assert.h>
#include <libdllink.h>
#include <libdlstat.h>
#include <libnwam.h>
#include <libscf.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <values.h>

#include "conditions.h"
#include "events.h"
#include "objects.h"
#include "ncp.h"
#include "ncu.h"
#include "util.h"

/*
 * ncp.c - handles NCP actions.
 */

char active_ncp[NWAM_MAX_NAME_LEN];
nwam_ncp_handle_t active_ncph = NULL;
int64_t current_ncu_priority_group = INVALID_PRIORITY_GROUP;
/*
 * active_ncp_mutex protects active_ncp, active_ncph and
 * current_ncu_priority_group.
 */
pthread_mutex_t active_ncp_mutex = PTHREAD_MUTEX_INITIALIZER;

/*
 * The variable ncu_wait_time specifies how long to wait to obtain a
 * DHCP lease before giving up on that NCU and moving on to the next/lower
 * priority-group.
 */
uint64_t ncu_wait_time = NCU_WAIT_TIME_DEFAULT;

/*
 * Specifies if this is the first time the NCP has been enabled. True
 * on startup so that we can differentiate between when we start up
 * with a given NCP versus when we are asked to reenable it.
 */
boolean_t initial_ncp_enable = B_TRUE;

/*
 * nwamd_ncp_handle_enable_event() should be called in the event handling
 * loop in response to an _ENABLE event, triggered as a result of an
 * nwam_ncp_enable() call from a libnwam consumer.  To enable the new NCP,
 * we first call nwamd_fini_ncus() on the old NCP.  This results in enqueueing
 * of a set of _FINI events for each NCU.  These events are handled and in
 * order to tear down config, (online*, uninitialized) state change events
 * are created and consumed directly by the fini event handler (these events
 * are not enqueued as this would result in state events for the old NCP
 * appearing after the new NCP has been enabled.  After the _FINI events are
 * enqueued, we enqueue an NCP _OBJECT_STATE event for the new NCP.  Since
 * it is enqueued after the _FINI events, we are guaranteed no events for the
 * old NCP will appear after the new NCP is activated.
 */
void
nwamd_ncp_handle_enable_event(nwamd_event_t event)
{
	char *new_ncp = event->event_object;
	nwam_ncp_handle_t new_ncph;
	nwam_error_t err;

	if (new_ncp[0] == '\0')
		return;

	(void) pthread_mutex_lock(&active_ncp_mutex);
	if (strcmp(active_ncp, new_ncp) == 0 && !initial_ncp_enable) {
		nlog(LOG_DEBUG, "nwamd_ncp_handle_enable_event: "
		    "%s is already active", new_ncp);
		(void) pthread_mutex_unlock(&active_ncp_mutex);
		return;
	}
	(void) pthread_mutex_unlock(&active_ncp_mutex);

	nlog(LOG_DEBUG, "nwamd_ncp_handle_enable_event: activating NCP %s",
	    new_ncp);

	/*
	 * To activate new NCP, run nwamd_fini_ncus(), reset the active
	 * priority-group, set the active_ncp property and refresh the
	 * daemon.  The refresh action will trigger a re-read of the NCUs
	 * for the activated NCP.
	 */

	nwamd_fini_ncus();

	if ((err = nwam_ncp_read(new_ncp, 0, &new_ncph))
	    == NWAM_ENTITY_NOT_FOUND) {
		err = nwam_ncp_create(new_ncp, 0, &new_ncph);
	}

	if (err == NWAM_SUCCESS) {
		nwam_ncp_free(new_ncph);
		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCP, new_ncp,
		    NWAM_STATE_ONLINE, NWAM_AUX_STATE_ACTIVE);
	} else if (initial_ncp_enable) {
		/*
		 * We weren't able to enable the NCP when nwamd starts up,
		 * retry in a few seconds.
		 */
		nwamd_event_t retry_event = nwamd_event_init_object_action
		    (NWAM_OBJECT_TYPE_NCP, new_ncp, NULL, NWAM_ACTION_ENABLE);
		if (retry_event == NULL) {
			nlog(LOG_ERR, "nwamd_ncp_handle_enable_event: "
			    "could not create retry event to enable %s NCP",
			    new_ncp);
			return;
		}

		nlog(LOG_ERR, "nwamd_ncp_handle_enable_event: "
		    "failed to enable %s NCP, retrying in %d seconds",
		    new_ncp, NWAMD_READONLY_RETRY_INTERVAL);
		nwamd_event_enqueue_timed(retry_event,
		    NWAMD_READONLY_RETRY_INTERVAL);
	} else {
		nlog(LOG_ERR, "nwamd_ncp_handle_enable_event: error %s",
		    nwam_strerror(err));
		return;
	}
}

void
nwamd_ncp_handle_action_event(nwamd_event_t event)
{
	switch (event->event_msg->nwe_data.nwe_object_action.nwe_action) {
	case NWAM_ACTION_ENABLE:
		nwamd_ncp_handle_enable_event(event);
		break;
	case NWAM_ACTION_ADD:
	case NWAM_ACTION_DESTROY:
		/* nothing to do */
		break;
	default:
		nlog(LOG_INFO, "nwam_ncp_handle_action_event: "
		    "unexpected action");
		nwamd_event_do_not_send(event);
		break;
	}
}

/*
 * The only state events we create are (online, active) events which are
 * generated as part of an NCP enable action (see above).
 */
void
nwamd_ncp_handle_state_event(nwamd_event_t event)
{
	char *new_ncp = event->event_object;
	nwam_ncp_handle_t new_ncph, old_ncph;
	nwam_error_t err;

	/* The NCP to be activated should always exist. */
	if ((err = nwam_ncp_read(new_ncp, 0, &new_ncph)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_ncp_handle_state_event: "
		    "cannot read NCP %s: : %s", new_ncp, nwam_strerror(err));
		nwamd_event_do_not_send(event);
		return;
	}

	/*
	 * To activate new NCP, reset the active priority-group, set the
	 * active_ncp property and refresh the daemon.  The refresh action will
	 * trigger a re-read of the NCUs for the activated NCP.
	 */
	(void) pthread_mutex_lock(&active_ncp_mutex);
	old_ncph = active_ncph;
	active_ncph = new_ncph;
	nwam_ncp_free(old_ncph);
	current_ncu_priority_group = INVALID_PRIORITY_GROUP;
	(void) strlcpy(active_ncp, event->event_object,
	    sizeof (active_ncp));
	(void) pthread_mutex_unlock(&active_ncp_mutex);
	(void) nwamd_set_string_property(OUR_FMRI, OUR_PG,
	    OUR_ACTIVE_NCP_PROP_NAME, new_ncp);
	(void) smf_refresh_instance(OUR_FMRI);
	initial_ncp_enable = B_FALSE;
}

int
nwamd_ncp_action(const char *ncp, nwam_action_t action)
{
	nwamd_event_t event = nwamd_event_init_object_action
	    (NWAM_OBJECT_TYPE_NCP, ncp, NULL, action);
	if (event == NULL)
		return (1);
	nwamd_event_enqueue(event);
	return (0);
}

/*
 * Below this point are routines handling NCU prioritization
 * policy for the active NCP.
 */

struct priority_group_cbarg {
	uint64_t minpriority;
	uint64_t currpriority;
	boolean_t found;
};

/* Callback used to find next pg in NCP that is >= start_pg */
static int
find_next_priority_group_cb(nwamd_object_t object, void *data)
{
	struct priority_group_cbarg *cbarg = data;
	uint64_t priority;
	nwamd_ncu_t *ncu = object->nwamd_object_data;

	if (ncu->ncu_link.nwamd_link_activation_mode !=
	    NWAM_ACTIVATION_MODE_PRIORITIZED)
		return (0);

	priority = ncu->ncu_link.nwamd_link_priority_group;

	if (priority >= cbarg->minpriority && priority < cbarg->currpriority) {
		cbarg->found = B_TRUE;
		cbarg->currpriority = priority;
	}
	return (0);
}

/* Set current_pg to next pg in NCP that is >= start_pg */
boolean_t
nwamd_ncp_find_next_priority_group(int64_t minpriority,
    int64_t *nextpriorityp)
{
	struct priority_group_cbarg cbarg;

	cbarg.minpriority = minpriority;
	cbarg.currpriority = MAXINT;
	cbarg.found = B_FALSE;

	(void) nwamd_walk_objects(NWAM_OBJECT_TYPE_NCU,
	    find_next_priority_group_cb, &cbarg);

	if (cbarg.found) {
		nlog(LOG_DEBUG, "nwamd_ncp_find_next_priority_group: "
		    "next priority group >= %lld is %lld",
		    minpriority, cbarg.currpriority);
		*nextpriorityp = cbarg.currpriority;
		return (B_TRUE);
	} else {
		nlog(LOG_DEBUG, "nwamd_ncp_find_next_priority_group: "
		    "no priority groups >= %lld exist", minpriority);
		return (B_FALSE);
	}
}

/*
 * Struct for walking NCUs in the selected priority group.  We count
 * how many of the exclusive, all and shared NCUs are online, and
 * if activate_or_deactivate is true, we either activate or deactivate
 * (depending on the value of activate) offline/online NCUs.
 */
struct nwamd_ncu_check_walk_arg {
	boolean_t manual;	/* enable manual NCUs only */
	int64_t priority_group; /* interested priority-group for this walk */
	uint64_t exclusive_ncus;
	uint64_t exclusive_online_ncus;
	uint64_t shared_ncus;
	uint64_t shared_online_ncus;
	uint64_t all_ncus;
	uint64_t all_online_ncus;
	boolean_t activate_or_deactivate;
	boolean_t activate;
};

/*
 * This function serves a number of purposes:
 * - it supports activation/deactivation of manual NCUs in the current NCP
 * (when wa->manual is true, wa->activate determines if we activate or
 * deactivate the current NCU)
 * - it supports checking/activation of a particular priority group in
 * the active NCP. This works as follows:
 *
 * Count up numbers of exclusive, shared and all NCUs, and how many of each
 * are online.  If an NCU is waiting for IP address to be assigned, it is
 * also considered online.  If activate_or_deactivate is true, we also
 * either activate (if activate is true) or deactivate prioritized NCUs
 * that are offline or online.
 */
static int
nwamd_ncu_check_or_activate(nwamd_object_t object, void *data)
{
	struct nwamd_ncu_check_walk_arg *wa = data;
	nwamd_ncu_t *ncu;
	uint64_t priority_group, priority_mode;
	nwamd_object_t if_obj;
	nwam_state_t state, if_state;
	nwam_aux_state_t aux_state, if_aux_state;
	char *name;

	state = object->nwamd_object_state;
	aux_state = object->nwamd_object_aux_state;
	name = object->nwamd_object_name;
	ncu = object->nwamd_object_data;

	/* skip NCUs in UNINITIALIZED state */
	if (state == NWAM_STATE_UNINITIALIZED) {
		nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
		    "skipping uninitialized ncu %s", name);
		return (0);
	}
	if (!wa->manual && wa->priority_group == INVALID_PRIORITY_GROUP)
		return (0);

	if (ncu->ncu_type != NWAM_NCU_TYPE_LINK) {
		nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
		    "skipping interface NCU %s", name);
		return (0);
	}
	if (!wa->manual && ncu->ncu_link.nwamd_link_activation_mode !=
	    NWAM_ACTIVATION_MODE_PRIORITIZED) {
		nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
		    "skipping non-prioritized NCU %s", name);
		return (0);
	}
	if (wa->manual && ncu->ncu_link.nwamd_link_activation_mode !=
	    NWAM_ACTIVATION_MODE_MANUAL) {
		nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
		    "skipping non-manual NCU %s", name);
		return (0);
	}

	priority_group = ncu->ncu_link.nwamd_link_priority_group;
	priority_mode = ncu->ncu_link.nwamd_link_priority_mode;
	/* Only work with NCUs in the requested priority-group */
	if (!wa->manual && priority_group != wa->priority_group) {
		nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
		    "skipping NCU %s in different priority-group", name);
		return (0);
	}
	/* Get the state of the corresponding interface NCU */
	if ((if_obj = nwamd_ncu_object_find(NWAM_NCU_TYPE_INTERFACE,
	    ncu->ncu_name)) == NULL) {
		nlog(LOG_ERR, "nwamd_ncu_check_or_activate: "
		    "interface NCU of %s not found, skipping", name);
		return (0);
	}
	if_state = if_obj->nwamd_object_state;
	if_aux_state = if_obj->nwamd_object_aux_state;
	nwamd_object_release(if_obj);

	nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: %s ncu %s",
	    wa->activate_or_deactivate ?
	    (wa->activate ? "activating" : "deactivating") :
	    "checking", name);

	if (wa->manual) {
		if (wa->activate_or_deactivate && wa->activate) {
			if (state == NWAM_STATE_OFFLINE && ncu->ncu_enabled) {
				nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
				    "moving NCU %s to offline* from offline",
				    name);
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    name, NWAM_STATE_OFFLINE_TO_ONLINE,
				    NWAM_AUX_STATE_INITIALIZED);
			}
			if (state != NWAM_STATE_DISABLED &&
			    !ncu->ncu_enabled) {
				nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
				    "moving NCU %s to online* (disabling)",
				    name);
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    name, NWAM_STATE_ONLINE_TO_OFFLINE,
				    NWAM_AUX_STATE_MANUAL_DISABLE);
			}
		}
		return (0);
	}
	switch (priority_mode) {
	case NWAM_PRIORITY_MODE_EXCLUSIVE:
		wa->exclusive_ncus++;
		if (state == NWAM_STATE_ONLINE &&
		    (if_state == NWAM_STATE_ONLINE ||
		    if_aux_state == NWAM_AUX_STATE_IF_WAITING_FOR_ADDR))
			wa->exclusive_online_ncus++;

		/*
		 * For exclusive NCUs, we activate offline NCUs as long
		 * as no other exclusive NCUs are active.
		 */
		if (wa->activate_or_deactivate && wa->activate) {
			if (state == NWAM_STATE_OFFLINE &&
			    wa->exclusive_online_ncus == 0) {
				nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
				    "moving NCU %s to offline* from offline",
				    name);
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    name, NWAM_STATE_OFFLINE_TO_ONLINE,
				    NWAM_AUX_STATE_INITIALIZED);
			}
		}
		if (wa->activate_or_deactivate && !wa->activate) {
			if (aux_state != NWAM_AUX_STATE_CONDITIONS_NOT_MET) {
				nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
				    "deactivating NCU %s", name);
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    name, NWAM_STATE_ONLINE_TO_OFFLINE,
				    NWAM_AUX_STATE_CONDITIONS_NOT_MET);
			}
		}
		/*
		 * If we are activating or checking the priority group and
		 * too many exclusive NCUs are online, take this NCU down.
		 */
		if ((wa->activate_or_deactivate && wa->activate) ||
		    !wa->activate_or_deactivate) {
			if (state == NWAM_STATE_ONLINE &&
			    if_state == NWAM_STATE_ONLINE &&
			    wa->exclusive_online_ncus > 1) {
				nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
				    "moving NCU %s to online* since another "
				    "NCU is already active",
				    name);
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    name, NWAM_STATE_ONLINE_TO_OFFLINE,
				    NWAM_AUX_STATE_CONDITIONS_NOT_MET);
			}
		}
		break;
	case NWAM_PRIORITY_MODE_SHARED:
		wa->shared_ncus++;
		if (state == NWAM_STATE_ONLINE &&
		    (if_state == NWAM_STATE_ONLINE ||
		    if_aux_state == NWAM_AUX_STATE_IF_WAITING_FOR_ADDR))
			wa->shared_online_ncus++;

		if (wa->activate_or_deactivate && wa->activate) {
			if (state == NWAM_STATE_OFFLINE) {
				nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
				    "activating NCU %s", name);
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    name, NWAM_STATE_OFFLINE_TO_ONLINE,
				    NWAM_AUX_STATE_INITIALIZED);
			}
		}
		if (wa->activate_or_deactivate && !wa->activate) {
			if (aux_state != NWAM_AUX_STATE_CONDITIONS_NOT_MET) {
				nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
				    "deactivating NCU %s", name);
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    name, NWAM_STATE_ONLINE_TO_OFFLINE,
				    NWAM_AUX_STATE_CONDITIONS_NOT_MET);
			}
		}
		break;
	case NWAM_PRIORITY_MODE_ALL:
		wa->all_ncus++;
		if (state == NWAM_STATE_ONLINE &&
		    (if_state == NWAM_STATE_ONLINE ||
		    if_aux_state == NWAM_AUX_STATE_IF_WAITING_FOR_ADDR))
			wa->all_online_ncus++;

		/*
		 * For "all" NCUs, activate/deactivate all offline/online
		 * NCUs.
		 */
		if (wa->activate_or_deactivate && wa->activate) {
			if (state == NWAM_STATE_OFFLINE) {
				nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
				    "activating NCU %s", name);
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    name, NWAM_STATE_OFFLINE_TO_ONLINE,
				    NWAM_AUX_STATE_INITIALIZED);
			}
		}
		if (wa->activate_or_deactivate && !wa->activate) {
			if (aux_state != NWAM_AUX_STATE_CONDITIONS_NOT_MET) {
				nlog(LOG_DEBUG, "nwamd_ncu_check_or_activate: "
				    "deactivating NCU %s", name);
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    name, NWAM_STATE_ONLINE_TO_OFFLINE,
				    NWAM_AUX_STATE_CONDITIONS_NOT_MET);
			}
		}

		break;
	default:
		nlog(LOG_ERR, "nwamd_ncu_check_or_activate: "
		    "invalid priority-mode");
		break;
	}

	return (0);
}

void
nwamd_ncp_activate_priority_group(int64_t priority)
{
	struct nwamd_ncu_check_walk_arg wa;
	nwamd_event_t check_event, priority_event;

	if (priority == INVALID_PRIORITY_GROUP)
		return;

	(void) pthread_mutex_lock(&active_ncp_mutex);
	if (priority == current_ncu_priority_group) {
		(void) pthread_mutex_unlock(&active_ncp_mutex);
		return;
	}
	(void) pthread_mutex_unlock(&active_ncp_mutex);

	nlog(LOG_DEBUG, "nwamd_ncp_activate_priority_group: "
	    "activating priority group %lld", priority);

	wa.manual = B_FALSE;
	wa.priority_group = priority;
	wa.exclusive_ncus = 0;
	wa.exclusive_online_ncus = 0;
	wa.shared_ncus = 0;
	wa.shared_online_ncus = 0;
	wa.all_ncus = 0;
	wa.all_online_ncus = 0;
	wa.activate_or_deactivate = B_TRUE;
	wa.activate = B_TRUE;

	if (nwamd_walk_objects(NWAM_OBJECT_TYPE_NCU,
	    nwamd_ncu_check_or_activate, &wa) != 0) {
		nlog(LOG_ERR, "nwamd_ncp_activate_priority_group: "
		    "nwamd_walk_objects() failed");
		return;
	}

	/*
	 * Enqueue event to update current_ncu_priority_group and send to
	 * any event listeners.
	 */
	priority_event = nwamd_event_init_priority_group_change(priority);
	if (priority_event == NULL)
		return;
	nwamd_event_enqueue(priority_event);

	/*
	 * Now we've activated a new priority group, enqueue an event
	 * to check up on the state of this priority group.
	 */
	check_event = nwamd_event_init_ncu_check();
	if (check_event == NULL)
		return;
	nwamd_event_enqueue_timed(check_event, ncu_wait_time);
}

void
nwamd_ncp_deactivate_priority_group(int64_t priority)
{
	struct nwamd_ncu_check_walk_arg wa;

	if (priority == INVALID_PRIORITY_GROUP)
		return;

	nlog(LOG_DEBUG, "nwamd_ncp_deactivate_priority_group: "
	    "deactivating priority group %lld", priority);

	wa.manual = B_FALSE;
	wa.priority_group = priority;
	wa.exclusive_ncus = 0;
	wa.exclusive_online_ncus = 0;
	wa.shared_ncus = 0;
	wa.shared_online_ncus = 0;
	wa.all_ncus = 0;
	wa.all_online_ncus = 0;
	wa.activate_or_deactivate = B_TRUE;
	wa.activate = B_FALSE;

	if (nwamd_walk_objects(NWAM_OBJECT_TYPE_NCU,
	    nwamd_ncu_check_or_activate, &wa) != 0) {
		nlog(LOG_ERR, "nwamd_ncp_deactivate_priority_group: "
		    "nwamd_walk_objects() failed");
		return;
	}
}

/*
 * This function deactivates all priority groups at level 'priority' and lower
 * (which is, numerically, all priorities >= priority).
 */
void
nwamd_ncp_deactivate_priority_group_all(int64_t priority)
{
	if (priority == INVALID_PRIORITY_GROUP)
		return;

	nlog(LOG_DEBUG, "nwamd_ncp_deactivate_priority_group_all: "
	    "deactivating priority group less than or equal to %lld", priority);

	do {
		nwamd_ncp_deactivate_priority_group(priority);
	} while (nwamd_ncp_find_next_priority_group(priority + 1, &priority));
}

/*
 * Returns 'true' if it found the highest priority group no higher then what
 * is passed that should be activated and sets *priority to that.
 */
boolean_t
nwamd_ncp_check_priority_group(int64_t *priority)
{
	struct nwamd_ncu_check_walk_arg wa;
	boolean_t conditions_met = B_FALSE;

	nlog(LOG_DEBUG, "nwamd_ncp_check_priority_group: "
	    "checking priority group %lld", *priority);

	if (*priority == INVALID_PRIORITY_GROUP) {
		if (!nwamd_ncp_find_next_priority_group(0, priority))
			return (B_FALSE);
	}

	while (!conditions_met) {
		(void) memset(&wa, 0, sizeof (wa));
		wa.manual = B_FALSE;
		wa.priority_group = *priority;
		wa.activate_or_deactivate = B_FALSE;

		if (nwamd_walk_objects(NWAM_OBJECT_TYPE_NCU,
		    nwamd_ncu_check_or_activate, &wa) != 0) {
			nlog(LOG_ERR, "nwamd_ncp_check_priority_group: "
			    "nwamd_walk_objects() failed");
			return (B_FALSE);
		}

		/*
		 * Are activation conditons satisifed? In other words:
		 * - exactly one of the exclusive NCUs is online
		 * - 1 or more shared NCUs are online
		 * - all of the all NCUs are online.
		 * If any of these is untrue, conditions are not satisfied.
		 */
		conditions_met = B_TRUE;
		if (wa.exclusive_ncus > 0 && wa.exclusive_online_ncus != 1)
			conditions_met = B_FALSE;
		if (wa.shared_ncus > 0 && wa.shared_online_ncus == 0)
			conditions_met = B_FALSE;
		if (wa.all_ncus > 0 && wa.all_ncus != wa.all_online_ncus)
			conditions_met = B_FALSE;
		if (wa.exclusive_online_ncus == 0 &&
		    wa.shared_online_ncus == 0 && wa.all_online_ncus == 0)
			conditions_met = B_FALSE;

		if (conditions_met) {
			return (B_TRUE);
		} else {
			/*
			 * If there is a next pg, activate it. If not, do
			 * nothing - we're stuck here unless an event occurs
			 * for our or a higher pg.
			 */
			if (!nwamd_ncp_find_next_priority_group
			    (wa.priority_group + 1, priority)) {
				nlog(LOG_DEBUG, "ran out of prio groups");
				return (B_FALSE);
			}
		}
	}
	return (B_FALSE);
}

void
nwamd_ncp_activate_manual_ncus(void)
{
	struct nwamd_ncu_check_walk_arg wa;

	nlog(LOG_DEBUG, "nwamd_ncp_activate_manual_ncus: activating NCUs");

	wa.manual = B_TRUE;
	wa.activate_or_deactivate = B_TRUE;
	wa.activate = B_TRUE;

	if (nwamd_walk_objects(NWAM_OBJECT_TYPE_NCU,
	    nwamd_ncu_check_or_activate, &wa) != 0) {
		nlog(LOG_ERR, "nwamd_ncp_activate_manual_ncus: "
		    "nwamd_walk_objects() failed");
		return;
	}
}

void
nwamd_create_ncu_check_event(uint64_t when)
{
	nwamd_event_t check_event = nwamd_event_init_ncu_check();
	if (check_event != NULL)
		nwamd_event_enqueue_timed(check_event, when);
}
/*
 * 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.
 */

#ifndef _NCP_H
#define	_NCP_H

#include <libdladm.h>
#include <libdlpi.h>
#include <libdlwlan.h>
#include <libnwam.h>
#include <libuutil.h>
#include <pthread.h>

/* Time between NCU checks */
#define	NCU_WAIT_TIME_DEFAULT		120

/* Value of priority-group at start and reset */
#define	INVALID_PRIORITY_GROUP		-1LL

extern char active_ncp[];
extern nwam_ncp_handle_t active_ncph;
extern int64_t current_ncu_priority_group;
extern uint64_t ncu_wait_time;

boolean_t nwamd_ncp_find_next_priority_group(int64_t, int64_t *);
void nwamd_ncp_activate_priority_group(int64_t);
void nwamd_ncp_deactivate_priority_group(int64_t);
void nwamd_ncp_deactivate_priority_group_all(int64_t);
boolean_t nwamd_ncp_check_priority_group(int64_t *);
void nwamd_ncp_activate_manual_ncus(void);

/* Create ncu check event */
void nwamd_create_ncu_check_event(uint64_t);

#endif /* _NCP_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 (c) 2016, Chris Fraire <cfraire@me.com>.
 */

#include <arpa/inet.h>
#include <assert.h>
#include <libdlaggr.h>
#include <libdllink.h>
#include <libdlstat.h>
#include <libnwam.h>
#include <libscf.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <values.h>
#include <zone.h>

#include "conditions.h"
#include "events.h"
#include "objects.h"
#include "ncp.h"
#include "util.h"

/*
 * ncu.c - handles various NCU tasks - intialization/refresh, state machine
 * for NCUs etc.
 */

#define	VBOX_IFACE_PREFIX	"vboxnet"

static void populate_ip_ncu_properties(nwam_ncu_handle_t, nwamd_ncu_t *);

/*
 * Find ncu of specified type for link/interface name.
 */
nwamd_object_t
nwamd_ncu_object_find(nwam_ncu_type_t type, const char *name)
{
	nwam_error_t err;
	char *object_name;
	nwamd_object_t ncu_obj = NULL;

	if ((err = nwam_ncu_name_to_typed_name(name, type, &object_name))
	    != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_ncu_find: nwam_ncu_name_to_typed_name "
		    "returned %s", nwam_strerror(err));
		return (NULL);
	}
	ncu_obj = nwamd_object_find(NWAM_OBJECT_TYPE_NCU, object_name);

	free(object_name);
	return (ncu_obj);
}

nwam_error_t
nwamd_set_ncu_string(nwam_ncu_handle_t ncuh, char **strval, uint_t cnt,
    const char *prop)
{
	nwam_error_t err;
	nwam_value_t val;

	if ((err = nwam_value_create_string_array(strval, cnt, &val))
	    != NWAM_SUCCESS)
		return (err);
	err = nwam_ncu_set_prop_value(ncuh, prop, val);
	nwam_value_free(val);
	return (err);
}

nwam_error_t
nwamd_set_ncu_uint(nwam_ncu_handle_t ncuh, uint64_t *uintval, uint_t cnt,
    const char *prop)
{
	nwam_error_t err;
	nwam_value_t val;

	if ((err = nwam_value_create_uint64_array(uintval, cnt, &val))
	    != NWAM_SUCCESS)
		return (err);
	err = nwam_ncu_set_prop_value(ncuh, prop, val);
	nwam_value_free(val);
	return (err);
}

nwam_error_t
nwamd_get_ncu_string(nwam_ncu_handle_t ncuh, nwam_value_t *val, char ***strval,
    uint_t *cnt, const char *prop)
{
	nwam_error_t err;

	if ((err = nwam_ncu_get_prop_value(ncuh, prop, val)) != NWAM_SUCCESS)
		return (err);
	return (nwam_value_get_string_array(*val, strval, cnt));
}

nwam_error_t
nwamd_get_ncu_uint(nwam_ncu_handle_t ncuh, nwam_value_t *val,
    uint64_t **uintval, uint_t *cnt, const char *prop)
{
	nwam_error_t err;

	if ((err = nwam_ncu_get_prop_value(ncuh, prop, val)) != NWAM_SUCCESS)
		return (err);
	return (nwam_value_get_uint64_array(*val, uintval, cnt));
}

nwam_error_t
nwamd_get_ncu_boolean(nwam_ncu_handle_t ncuh, nwam_value_t *val,
    boolean_t **boolval, uint_t *cnt, const char *prop)
{
	nwam_error_t err;

	if ((err = nwam_ncu_get_prop_value(ncuh, prop, val)) != NWAM_SUCCESS)
		return (err);
	return (nwam_value_get_boolean_array(*val, boolval, cnt));
}

/*
 * Run link/interface state machine in response to a state change
 * or enable/disable action event.
 */
static void
nwamd_ncu_state_machine(const char *object_name)
{
	nwamd_object_t object;
	nwamd_ncu_t *ncu;
	link_state_t link_state;
	nwamd_event_t event;
	nwam_wlan_t key_wlan, connected_wlan;
	nwamd_link_t *link;
	char linkname[NWAM_MAX_NAME_LEN];
	boolean_t up;

	if ((object = nwamd_object_find(NWAM_OBJECT_TYPE_NCU, object_name))
	    == NULL) {
		nlog(LOG_ERR, "nwamd_ncu_state_machine: "
		    "request for nonexistent NCU %s", object_name);
		return;
	}

	ncu = object->nwamd_object_data;
	link = &ncu->ncu_link;

	switch (object->nwamd_object_aux_state) {
	case NWAM_AUX_STATE_INITIALIZED:
		if (ncu->ncu_type == NWAM_NCU_TYPE_LINK) {
			/*
			 * For wired/wireless links, need to get link
			 * up/down events and even if these are not supported,
			 * dlpi_open()ing the link prevents the driver from
			 * being unloaded.
			 */
			nwamd_dlpi_add_link(object);

			if (link->nwamd_link_media == DL_WIFI) {
				/*
				 * First, if we're unexpectedly connected,
				 * disconnect.
				 */
				if (!link->nwamd_link_wifi_connected &&
				    nwamd_wlan_connected(object)) {
					nlog(LOG_DEBUG,
					    "nwamd_ncu_state_machine: "
					    "WiFi unexpectedly connected, "
					    "disconnecting...");
					(void) dladm_wlan_disconnect(dld_handle,
					    link->nwamd_link_id);
					nwamd_set_selected_connected(ncu,
					    B_FALSE, B_FALSE);
				}
				/* move to scanning aux state */
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    object_name, object->nwamd_object_state,
				    NWAM_AUX_STATE_LINK_WIFI_SCANNING);
			} else {
				/*
				 * If initial wired link state is unknown, we
				 * will need to assume the link is up, since
				 * we won´t get DL_NOTE_LINK_UP/DOWN events.
				 */
				link_state = nwamd_get_link_state
				    (ncu->ncu_name);
				if (link_state == LINK_STATE_UP ||
				    link_state == LINK_STATE_UNKNOWN) {
					nwamd_object_set_state
					    (NWAM_OBJECT_TYPE_NCU,
					    object_name, NWAM_STATE_ONLINE,
					    NWAM_AUX_STATE_UP);
				} else {
					nwamd_object_set_state
					    (NWAM_OBJECT_TYPE_NCU,
					    object_name,
					    NWAM_STATE_ONLINE_TO_OFFLINE,
					    NWAM_AUX_STATE_DOWN);
				}
			}
		} else {
			/*
			 * In the current implementation, initialization has to
			 * start from scratch since the complexity of minimizing
			 * configuration change is considerable (e.g. if we
			 * refresh and had DHCP running on the physical
			 * interface, and now have changed to static assignment,
			 * we need to remove DHCP etc).  To avoid all this,
			 * unplumb before re-plumbing the protocols and
			 * addresses we wish to configure.  In the future, it
			 * would be good to try and minimize configuration
			 * changes.
			 */
			nwamd_unplumb_interface(ncu, AF_INET);
			nwamd_unplumb_interface(ncu, AF_INET6);

			/*
			 * We may be restarting the state machine.  Re-read
			 * the IP NCU properties as the ipadm_addrobj_t in
			 * nwamd_if_address should not be reused.
			 */
			populate_ip_ncu_properties(object->nwamd_object_handle,
			    ncu);

			/*
			 * Enqueue a WAITING_FOR_ADDR aux state change so that
			 * we are eligible to receive the IF_STATE events
			 * associated with static, DHCP, DHCPv6 and autoconf
			 * address assignment.  The latter two can happen
			 * quite quickly after plumbing so we need to be ready.
			 */
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    object_name, NWAM_STATE_OFFLINE_TO_ONLINE,
			    NWAM_AUX_STATE_IF_WAITING_FOR_ADDR);

			if (ncu->ncu_if.nwamd_if_ipv4)
				nwamd_plumb_interface(ncu, AF_INET);

			if (ncu->ncu_if.nwamd_if_ipv6)
				nwamd_plumb_interface(ncu, AF_INET6);

			/* Configure addresses */
			nwamd_configure_interface_addresses(ncu);
		}
		break;

	case NWAM_AUX_STATE_IF_DHCP_TIMED_OUT:
	case NWAM_AUX_STATE_IF_WAITING_FOR_ADDR:
		/*
		 * nothing to do here - RTM_NEWADDRs will trigger IF_STATE
		 * events to move us online.
		 */
		break;

	case NWAM_AUX_STATE_LINK_WIFI_SCANNING:
		/* launch scan thread */
		(void) strlcpy(linkname, ncu->ncu_name, sizeof (linkname));
		(void) nwamd_wlan_scan(linkname);
		/* Create periodic scan event */
		nwamd_ncu_create_periodic_scan_event(object);
		break;

	case NWAM_AUX_STATE_LINK_WIFI_NEED_SELECTION:
		/* send "need choice" event */
		event = nwamd_event_init_wlan
		    (ncu->ncu_name, NWAM_EVENT_TYPE_WLAN_NEED_CHOICE, B_FALSE,
		    link->nwamd_link_wifi_scan.nwamd_wifi_scan_curr,
		    link->nwamd_link_wifi_scan.nwamd_wifi_scan_curr_num);
		if (event == NULL)
			break;
		nwamd_event_enqueue(event);
		nwamd_set_selected_connected(ncu, B_FALSE, B_FALSE);
		break;

	case NWAM_AUX_STATE_LINK_WIFI_NEED_KEY:
		/*
		 * Send "need key" event.  Set selected to true, connected
		 * and have_key to false.  Do not fill in WLAN details as
		 * multiple WLANs may match the ESSID name, and each may
		 * have a different speed and channel.
		 */
		bzero(&key_wlan, sizeof (key_wlan));
		(void) strlcpy(key_wlan.nww_essid, link->nwamd_link_wifi_essid,
		    sizeof (key_wlan.nww_essid));
		(void) strlcpy(key_wlan.nww_bssid, link->nwamd_link_wifi_bssid,
		    sizeof (key_wlan.nww_bssid));
		key_wlan.nww_security_mode =
		    link->nwamd_link_wifi_security_mode;
		key_wlan.nww_selected = B_TRUE;
		key_wlan.nww_connected = B_FALSE;
		key_wlan.nww_have_key = B_FALSE;
		event = nwamd_event_init_wlan
		    (ncu->ncu_name, NWAM_EVENT_TYPE_WLAN_NEED_KEY, B_FALSE,
		    &key_wlan, 1);
		if (event == NULL)
			break;
		nwamd_event_enqueue(event);
		break;

	case NWAM_AUX_STATE_LINK_WIFI_CONNECTING:
		(void) strlcpy(linkname, ncu->ncu_name, sizeof (linkname));
		nwamd_wlan_connect(linkname);
		break;

	case NWAM_AUX_STATE_UP:
	case NWAM_AUX_STATE_DOWN:
		up = (object->nwamd_object_aux_state == NWAM_AUX_STATE_UP);
		if (ncu->ncu_type == NWAM_NCU_TYPE_LINK) {
			if (link->nwamd_link_media == DL_WIFI) {
				/*
				 * Connected/disconnected - send WLAN
				 * connection report.
				 */
				link->nwamd_link_wifi_connected = up;
				nwamd_set_selected_connected(ncu, B_TRUE, up);

				(void) strlcpy(connected_wlan.nww_essid,
				    link->nwamd_link_wifi_essid,
				    sizeof (connected_wlan.nww_essid));
				(void) strlcpy(connected_wlan.nww_bssid,
				    link->nwamd_link_wifi_bssid,
				    sizeof (connected_wlan.nww_bssid));
				connected_wlan.nww_security_mode =
				    link->nwamd_link_wifi_security_mode;
				event = nwamd_event_init_wlan
				    (ncu->ncu_name,
				    NWAM_EVENT_TYPE_WLAN_CONNECTION_REPORT, up,
				    &connected_wlan, 1);
				if (event == NULL)
					break;
				nwamd_event_enqueue(event);

				/*
				 * If disconnected, restart the state machine
				 * for the WiFi link (WiFi is always trying
				 * to connect).
				 *
				 * If connected, start signal strength
				 * monitoring thread.
				 */
				if (!up && ncu->ncu_enabled) {
					nlog(LOG_DEBUG,
					    "nwamd_ncu_state_machine: "
					    "wifi disconnect - start over "
					    "after %dsec interval",
					    WIRELESS_RETRY_INTERVAL);
					link->nwamd_link_wifi_connected =
					    B_FALSE;
					/* propogate down event to IP NCU */
					nwamd_propogate_link_up_down_to_ip
					    (ncu->ncu_name, B_FALSE);
					nwamd_object_set_state_timed
					    (NWAM_OBJECT_TYPE_NCU, object_name,
					    NWAM_STATE_OFFLINE_TO_ONLINE,
					    NWAM_AUX_STATE_INITIALIZED,
					    WIRELESS_RETRY_INTERVAL);
				} else {
					nlog(LOG_DEBUG,
					    "nwamd_ncu_state_machine: "
					    "wifi connected, start monitoring");
					(void) strlcpy(linkname, ncu->ncu_name,
					    sizeof (linkname));
					nwamd_wlan_monitor_signal(linkname);
				}
			}
		}

		/* If not in ONLINE/OFFLINE state yet, change state */
		if ((up && object->nwamd_object_state != NWAM_STATE_ONLINE) ||
		    (!up && object->nwamd_object_state != NWAM_STATE_OFFLINE)) {
			nlog(LOG_DEBUG, "nwamd_ncu_state_machine: "
			    "%s is moving %s", object_name,
			    up ? "online" : "offline");
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    object_name,
			    up ? NWAM_STATE_ONLINE : NWAM_STATE_OFFLINE,
			    up ? NWAM_AUX_STATE_UP : NWAM_AUX_STATE_DOWN);

			if (ncu->ncu_type == NWAM_NCU_TYPE_INTERFACE) {
				if (up) {
					/*
					 * Moving online, add v4/v6 default
					 * routes (if any).
					 */
					nwamd_add_default_routes(ncu);
				} else {
					/*
					 * If this is an interface NCU and we
					 * got a down event, it is a consequence
					 * of NCU refresh, so reapply addresses
					 * by reinitializing.
					 */
					nwamd_object_set_state
					    (NWAM_OBJECT_TYPE_NCU, object_name,
					    NWAM_STATE_OFFLINE_TO_ONLINE,
					    NWAM_AUX_STATE_INITIALIZED);
				}
			}
		} else {
			nlog(LOG_DEBUG, "nwamd_ncu_state_machine: "
			    "%s is %s", object_name,
			    up ? "online" : "offline");
		}
		/*
		 * NCU is UP or DOWN, trigger all condition checking, even if
		 * the NCU is already in the ONLINE state - an ENM may depend
		 * on NCU activity.
		 */
		nwamd_create_triggered_condition_check_event(NEXT_FEW_SECONDS);
		break;

	case NWAM_AUX_STATE_CONDITIONS_NOT_MET:
		/*
		 * Link/interface is moving offline.  Nothing to do except
		 * for WiFi, where we disconnect.  Don't unplumb IP on
		 * a link since it may be a transient change.
		 */
		if (ncu->ncu_type == NWAM_NCU_TYPE_LINK) {
			if (link->nwamd_link_media == DL_WIFI) {
				(void) dladm_wlan_disconnect(dld_handle,
				    link->nwamd_link_id);
				link->nwamd_link_wifi_connected = B_FALSE;
				nwamd_set_selected_connected(ncu, B_FALSE,
				    B_FALSE);
			}
		} else {
			/*
			 * Unplumb here. In the future we may elaborate on
			 * the approach used and not unplumb for WiFi
			 * until we reconnect to a different WLAN (i.e. with
			 * a different ESSID).
			 */
			nwamd_unplumb_interface(ncu, AF_INET);
			nwamd_unplumb_interface(ncu, AF_INET6);
		}
		if (object->nwamd_object_state != NWAM_STATE_OFFLINE) {
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    object_name, NWAM_STATE_OFFLINE,
			    NWAM_AUX_STATE_CONDITIONS_NOT_MET);
		}
		break;

	case NWAM_AUX_STATE_MANUAL_DISABLE:
		/* Manual disable, set enabled state appropriately. */
		ncu->ncu_enabled = B_FALSE;
		/* FALLTHROUGH */
	case NWAM_AUX_STATE_UNINITIALIZED:
	case NWAM_AUX_STATE_NOT_FOUND:
		/*
		 * Link/interface NCU has been disabled/deactivated/removed.
		 * For WiFi links disconnect, and for IP interfaces we unplumb.
		 */
		if (ncu->ncu_type == NWAM_NCU_TYPE_LINK) {
			if (link->nwamd_link_media == DL_WIFI) {
				(void) dladm_wlan_disconnect(dld_handle,
				    link->nwamd_link_id);
				link->nwamd_link_wifi_connected = B_FALSE;
				nwamd_set_selected_connected(ncu, B_FALSE,
				    B_FALSE);
			}
			nwamd_dlpi_delete_link(object);
		} else {
			/* Unplumb here. */
			if (ncu->ncu_if.nwamd_if_ipv4) {
				nwamd_unplumb_interface(ncu, AF_INET);
			}
			if (ncu->ncu_if.nwamd_if_ipv6) {
				nwamd_unplumb_interface(ncu, AF_INET6);
			}
			/* trigger location condition checking */
			nwamd_create_triggered_condition_check_event(0);
		}

		switch (object->nwamd_object_aux_state) {
		case NWAM_AUX_STATE_MANUAL_DISABLE:
			/* Change state to DISABLED if manually disabled */
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    object_name, NWAM_STATE_DISABLED,
			    NWAM_AUX_STATE_MANUAL_DISABLE);
			/* Note that NCU has been disabled */
			ncu->ncu_enabled = B_FALSE;
			break;
		case NWAM_AUX_STATE_NOT_FOUND:
			/* Change state to UNINITIALIZED for device removal */
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    object_name, NWAM_STATE_UNINITIALIZED,
			    NWAM_AUX_STATE_NOT_FOUND);
			break;
		default:
			break;
		}
		break;
	default:
		nlog(LOG_ERR, "nwamd_ncu_state_machine: unexpected state");
		break;
	}

	nwamd_object_release(object);
}

static int
ncu_create_init_fini_event(nwam_ncu_handle_t ncuh, void *data)
{
	boolean_t *init = data;
	char *name, *typedname;
	nwam_error_t err;
	nwam_value_t typeval = NULL;
	uint64_t *type;
	uint_t numvalues;
	nwamd_event_t ncu_event;

	if (nwam_ncu_get_name(ncuh, &name) != NWAM_SUCCESS) {
		nlog(LOG_ERR,
		    "ncu_create_init_fini_event: could not get NCU name");
		return (0);
	}

	nlog(LOG_DEBUG, "ncu_create_init_fini_event(%s, %p)", name, data);

	if ((err = nwamd_get_ncu_uint(ncuh, &typeval, &type, &numvalues,
	    NWAM_NCU_PROP_TYPE)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "ncu_create_init_fini_event: "
		    "could not get NCU type: %s", nwam_strerror(err));
		free(name);
		nwam_value_free(typeval);
		return (0);
	}

	/* convert name to typedname for event */
	if ((err = nwam_ncu_name_to_typed_name(name, *type, &typedname))
	    != NWAM_SUCCESS) {
		nlog(LOG_ERR, "ncu_create_init_fini_event: "
		    "NCU name translation failed: %s", nwam_strerror(err));
		free(name);
		return (0);
	}
	free(name);
	nwam_value_free(typeval);

	ncu_event = nwamd_event_init(*init ?
	    NWAM_EVENT_TYPE_OBJECT_INIT : NWAM_EVENT_TYPE_OBJECT_FINI,
	    NWAM_OBJECT_TYPE_NCU, 0, typedname);
	if (ncu_event != NULL)
		nwamd_event_enqueue(ncu_event);
	free(typedname);

	return (0);
}

/*
 * Initialization - walk the NCUs, creating initialization events for each
 * NCU.  nwamd_ncu_handle_init_event() will check if the associated
 * physical link exists or not.
 */
void
nwamd_init_ncus(void)
{
	boolean_t init = B_TRUE;

	(void) pthread_mutex_lock(&active_ncp_mutex);
	if (active_ncph != NULL) {
		nlog(LOG_DEBUG, "nwamd_init_ncus: "
		    "(re)intializing NCUs for NCP %s", active_ncp);
		(void) nwam_ncp_walk_ncus(active_ncph,
		    ncu_create_init_fini_event, &init, NWAM_FLAG_NCU_TYPE_ALL,
		    NULL);
	}
	(void) pthread_mutex_unlock(&active_ncp_mutex);
}

void
nwamd_fini_ncus(void)
{
	boolean_t init = B_FALSE;

	/* We may not have an active NCP on initialization, so skip fini */
	(void) pthread_mutex_lock(&active_ncp_mutex);
	if (active_ncph != NULL) {
		nlog(LOG_DEBUG, "nwamd_fini_ncus: deinitializing NCUs for %s",
		    active_ncp);
		(void) nwam_ncp_walk_ncus(active_ncph,
		    ncu_create_init_fini_event, &init, NWAM_FLAG_NCU_TYPE_ALL,
		    NULL);
	}
	(void) pthread_mutex_unlock(&active_ncp_mutex);
}

/*
 * Most properties of this type don't need to be cached locally.  Only those
 * interesting to the daemon are stored in an nwamd_ncu_t.
 */
static void
populate_common_ncu_properties(nwam_ncu_handle_t ncuh, nwamd_ncu_t *ncu_data)
{
	nwam_value_t ncu_prop;
	nwam_error_t err;
	boolean_t enablevalue;
	uint_t numvalues;
	char **parent;

	if ((err = nwam_ncu_get_prop_value(ncuh, NWAM_NCU_PROP_ENABLED,
	    &ncu_prop)) != NWAM_SUCCESS) {
		char *name;
		(void) nwam_ncu_name_to_typed_name(ncu_data->ncu_name,
		    ncu_data->ncu_type, &name);
		nlog(LOG_ERR, "nwam_ncu_get_prop_value %s ENABLED failed: %s",
		    name, nwam_strerror(err));
		free(name);
		ncu_data->ncu_enabled = B_TRUE;
	} else {
		if ((err = nwam_value_get_boolean(ncu_prop, &enablevalue)) !=
		    NWAM_SUCCESS) {
			nlog(LOG_ERR, "nwam_value_get_boolean ENABLED failed: "
			    "%s", nwam_strerror(err));
		} else {
			ncu_data->ncu_enabled = enablevalue;
		}
		nwam_value_free(ncu_prop);
	}

	if ((err = nwamd_get_ncu_string(ncuh, &ncu_prop, &parent,
	    &numvalues, NWAM_NCU_PROP_PARENT_NCP)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwam_ncu_get_prop_value %s PARENT failed: %s",
		    ncu_data->ncu_name, nwam_strerror(err));
	} else {
		(void) strlcpy(ncu_data->ncu_parent, parent[0],
		    sizeof (ncu_data->ncu_parent));
		nwam_value_free(ncu_prop);
	}
}

/*
 * Read in link properties.
 */
static void
populate_link_ncu_properties(nwam_ncu_handle_t ncuh, nwamd_ncu_t *ncu_data)
{
	nwam_value_t ncu_prop;
	nwam_error_t err;
	char **mac_addr;
	uint64_t *uintval;
	uint_t numvalues;

	/* activation-mode */
	if ((err = nwamd_get_ncu_uint(ncuh, &ncu_prop, &uintval, &numvalues,
	    NWAM_NCU_PROP_ACTIVATION_MODE)) != NWAM_SUCCESS) {
		nlog(LOG_ERR,
		    "populate_link_ncu_properties: could not get %s value: %s",
		    NWAM_NCU_PROP_ACTIVATION_MODE, nwam_strerror(err));
	} else {
		ncu_data->ncu_link.nwamd_link_activation_mode = uintval[0];
		nwam_value_free(ncu_prop);
	}

	/* priority-group and priority-mode for prioritized activation */
	if (ncu_data->ncu_link.nwamd_link_activation_mode ==
	    NWAM_ACTIVATION_MODE_PRIORITIZED) {
		/* ncus with prioritized activation are always enabled */
		ncu_data->ncu_enabled = B_TRUE;
		if ((err = nwamd_get_ncu_uint(ncuh, &ncu_prop, &uintval,
		    &numvalues, NWAM_NCU_PROP_PRIORITY_MODE))
		    != NWAM_SUCCESS) {
			nlog(LOG_ERR, "populate_link_ncu_properties: "
			    "could not get %s value: %s",
			    NWAM_NCU_PROP_PRIORITY_MODE, nwam_strerror(err));
		} else {
			ncu_data->ncu_link.nwamd_link_priority_mode =
			    uintval[0];
			nwam_value_free(ncu_prop);
		}

		if ((err = nwamd_get_ncu_uint(ncuh, &ncu_prop, &uintval,
		    &numvalues, NWAM_NCU_PROP_PRIORITY_GROUP))
		    != NWAM_SUCCESS) {
			nlog(LOG_ERR, "populate_link_ncu_properties: "
			    "could not get %s value: %s",
			    NWAM_NCU_PROP_PRIORITY_GROUP, nwam_strerror(err));
		} else {
			ncu_data->ncu_link.nwamd_link_priority_group =
			    uintval[0];
			nwam_value_free(ncu_prop);
		}
	}

	/* link-mac-addr */
	if ((err = nwamd_get_ncu_string(ncuh, &ncu_prop, &mac_addr, &numvalues,
	    NWAM_NCU_PROP_LINK_MAC_ADDR)) != NWAM_SUCCESS) {
		nlog(LOG_DEBUG,
		    "populate_link_ncu_properties: could not get %s value: %s",
		    NWAM_NCU_PROP_LINK_MAC_ADDR, nwam_strerror(err));
		ncu_data->ncu_link.nwamd_link_mac_addr = NULL;
	} else {
		ncu_data->ncu_link.nwamd_link_mac_addr = strdup(*mac_addr);
		ncu_data->ncu_link.nwamd_link_mac_addr_len = strlen(*mac_addr);
		nwam_value_free(ncu_prop);
	}

	/* link-mtu */
	if ((err = nwamd_get_ncu_uint(ncuh, &ncu_prop, &uintval, &numvalues,
	    NWAM_NCU_PROP_LINK_MTU)) != NWAM_SUCCESS) {
		nlog(LOG_DEBUG,
		    "populate_link_ncu_properties: could not get %s value: %s",
		    NWAM_NCU_PROP_LINK_MTU, nwam_strerror(err));
		ncu_data->ncu_link.nwamd_link_mtu = 0;
	} else {
		ncu_data->ncu_link.nwamd_link_mtu = uintval[0];
		nwam_value_free(ncu_prop);
	}

	/* link-autopush */
	if ((err = nwamd_get_ncu_string(ncuh, &ncu_prop,
	    &ncu_data->ncu_link.nwamd_link_autopush,
	    &ncu_data->ncu_link.nwamd_link_num_autopush,
	    NWAM_NCU_PROP_LINK_AUTOPUSH)) != NWAM_SUCCESS) {
		nlog(LOG_DEBUG,
		    "populate_link_ncu_properties: could not get %s value: %s",
		    NWAM_NCU_PROP_LINK_AUTOPUSH, nwam_strerror(err));
		ncu_data->ncu_link.nwamd_link_num_autopush = 0;
	}
}

static void
populate_ip_ncu_properties(nwam_ncu_handle_t ncuh, nwamd_ncu_t *ncu_data)
{
	nwamd_if_t *nif = &ncu_data->ncu_if;
	struct nwamd_if_address **nifa, *nifai, *nifait;
	boolean_t static_addr = B_FALSE, *boolvalue, dhcp_primary = B_FALSE;
	uint64_t *addrsrcvalue;
	nwam_value_t ncu_prop;
	nwam_error_t err;
	ipadm_addrobj_t ipaddr;
	ipadm_status_t ipstatus;
	char **addrvalue, ipreqhost[MAXNAMELEN];
	uint_t numvalues;
	uint64_t *ipversion;
	int i;

	nif->nwamd_if_ipv4 = B_FALSE;
	nif->nwamd_if_ipv6 = B_FALSE;
	nif->nwamd_if_dhcp_requested = B_FALSE;
	nif->nwamd_if_stateful_requested = B_FALSE;
	nif->nwamd_if_stateless_requested = B_FALSE;
	nif->nwamd_if_ipv4_default_route_set = B_FALSE;
	nif->nwamd_if_ipv6_default_route_set = B_FALSE;

	/* ip-version */
	if ((err = nwamd_get_ncu_uint(ncuh, &ncu_prop, &ipversion, &numvalues,
	    NWAM_NCU_PROP_IP_VERSION)) != NWAM_SUCCESS) {
		nlog(LOG_ERR,
		    "populate_ip_ncu_properties: could not get %s value: %s",
		    NWAM_NCU_PROP_IP_VERSION, nwam_strerror(err));
	} else {
		for (i = 0; i < numvalues; i++) {
			switch (ipversion[i]) {
			case IPV4_VERSION:
				nif->nwamd_if_ipv4 = B_TRUE;
				break;
			case IPV6_VERSION:
				nif->nwamd_if_ipv6 = B_TRUE;
				break;
			default:
				nlog(LOG_ERR, "bogus ip version %lld",
				    ipversion[i]);
				break;
			}
		}
		nwam_value_free(ncu_prop);
	}

	/* ip-primary */
	if ((err = nwamd_get_ncu_boolean(ncuh, &ncu_prop, &boolvalue,
	    &numvalues, NWAM_NCU_PROP_IP_PRIMARY)) != NWAM_SUCCESS) {
		/* ip-primary is optional, so do not LOG_ERR */
		nlog(LOG_DEBUG, "populate_ip_ncu_properties: "
		    "could not get %s value: %s",
		    NWAM_NCU_PROP_IP_PRIMARY, nwam_strerror(err));
	} else {
		if (numvalues > 0)
			dhcp_primary = boolvalue[0];
		nwam_value_free(ncu_prop);
	}

	/* ip-reqhost */
	*ipreqhost = '\0';

	if ((err = nwamd_get_ncu_string(ncuh, &ncu_prop, &addrvalue,
	    &numvalues, NWAM_NCU_PROP_IP_REQHOST)) != NWAM_SUCCESS) {
		/* ip-reqhost is optional, so do not LOG_ERR */
		nlog(LOG_DEBUG, "populate_ip_ncu_properties: "
		    "could not get %s value: %s",
		    NWAM_NCU_PROP_IP_REQHOST, nwam_strerror(err));
	} else {
		if (numvalues > 0 && strlcpy(ipreqhost, addrvalue[0],
		    sizeof (ipreqhost)) >= sizeof (ipreqhost)) {
			nlog(LOG_WARNING, "populate_ip_ncu_properties: "
			    "too long %s value: %s",
			    NWAM_NCU_PROP_IP_REQHOST, addrvalue[0]);
			*ipreqhost = '\0';
		}
		nwam_value_free(ncu_prop);
	}

	/* Free the old list. */
	for (nifai = nif->nwamd_if_list; nifai != NULL; nifai = nifait) {
		nifait = nifai->next;
		nifai->next = NULL;
		ipadm_destroy_addrobj(nifai->ipaddr);
		free(nifai);
	}
	nif->nwamd_if_list = NULL;
	nifa = &(nif->nwamd_if_list);

	if (!nif->nwamd_if_ipv4)
		goto skip_ipv4;

	/* ipv4-addrsrc */
	if ((err = nwamd_get_ncu_uint(ncuh, &ncu_prop, &addrsrcvalue,
	    &numvalues, NWAM_NCU_PROP_IPV4_ADDRSRC)) != NWAM_SUCCESS) {
		nlog(nif->nwamd_if_ipv4 ? LOG_ERR : LOG_DEBUG,
		    "populate_ip_ncu_properties: could not get %s value: %s",
		    NWAM_NCU_PROP_IPV4_ADDRSRC, nwam_strerror(err));
	} else {
		for (i = 0; i < numvalues; i++) {
			switch (addrsrcvalue[i]) {
			case NWAM_ADDRSRC_DHCP:
				nif->nwamd_if_dhcp_requested = B_TRUE;
				break;
			case NWAM_ADDRSRC_STATIC:
				static_addr = B_TRUE;
				break;
			default:
				break;
			}
		}
		nwam_value_free(ncu_prop);
	}
	if (nif->nwamd_if_dhcp_requested) {
		ipstatus = ipadm_create_addrobj(IPADM_ADDR_DHCP,
		    ncu_data->ncu_name, &ipaddr);
		if (ipstatus != IPADM_SUCCESS) {
			nlog(LOG_ERR, "populate_ip_ncu_properties: "
			    "ipadm_create_addrobj failed for v4 dhcp: %s",
			    ipadm_status2str(ipstatus));
			goto skip_ipv4_dhcp;
		}

		ipstatus = ipadm_set_wait_time(ipaddr, ncu_wait_time);
		if (ipstatus != IPADM_SUCCESS) {
			nlog(LOG_ERR, "populate_ip_ncu_properties: "
			    "ipadm_set_wait_time failed for v4 dhcp: %s",
			    ipadm_status2str(ipstatus));
			ipadm_destroy_addrobj(ipaddr);
			goto skip_ipv4_dhcp;
		}
		ipstatus = ipadm_set_primary(ipaddr, dhcp_primary);
		if (ipstatus != IPADM_SUCCESS) {
			nlog(LOG_ERR, "populate_ip_ncu_properties: "
			    "ipadm_set_primary failed for v4 dhcp: %s",
			    ipadm_status2str(ipstatus));
			ipadm_destroy_addrobj(ipaddr);
			goto skip_ipv4_dhcp;
		}
		ipstatus = ipadm_set_reqhost(ipaddr, ipreqhost);
		if (ipstatus != IPADM_SUCCESS) {
			nlog(LOG_ERR, "populate_ip_ncu_properties: "
			    "ipadm_set_reqhost failed for v4 dhcp: %s",
			    ipadm_status2str(ipstatus));
			ipadm_destroy_addrobj(ipaddr);
			goto skip_ipv4_dhcp;
		}
		if ((*nifa = calloc(sizeof (**nifa), 1)) != NULL) {
			(*nifa)->family = AF_INET;
			(*nifa)->ipaddr_atype = IPADM_ADDR_DHCP;
			(*nifa)->ipaddr = ipaddr;
			nifa = &((*nifa)->next);
			*nifa = NULL;
		} else {
			nlog(LOG_ERR, "populate_ip_ncu_properties: "
			    "couldn't allocate nwamd address for v4 dhcp: %s",
			    strerror(errno));
			ipadm_destroy_addrobj(ipaddr);
		}
	}

skip_ipv4_dhcp:
	/* ipv4-addr */
	if (static_addr) {
		if ((err = nwamd_get_ncu_string(ncuh, &ncu_prop, &addrvalue,
		    &numvalues, NWAM_NCU_PROP_IPV4_ADDR)) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "populate_ip_ncu_properties: "
			    "could not get %s value: %s",
			    NWAM_NCU_PROP_IPV4_ADDR, nwam_strerror(err));
		} else {
			for (i = 0; i < numvalues; i++) {
				ipstatus = ipadm_create_addrobj(
				    IPADM_ADDR_STATIC, ncu_data->ncu_name,
				    &ipaddr);
				if (ipstatus != IPADM_SUCCESS) {
					nlog(LOG_ERR,
					    "populate_ip_ncu_properties: "
					    "ipadm_create_addrobj failed "
					    "for %s: %s", addrvalue[i],
					    ipadm_status2str(ipstatus));
					continue;
				}
				/* ipadm_set_addr takes <addr>[/<mask>] */
				ipstatus = ipadm_set_addr(ipaddr, addrvalue[i],
				    AF_INET);
				if (ipstatus != IPADM_SUCCESS) {
					nlog(LOG_ERR,
					    "populate_ip_ncu_properties: "
					    "ipadm_set_addr failed for %s: %s",
					    addrvalue[i],
					    ipadm_status2str(ipstatus));
					ipadm_destroy_addrobj(ipaddr);
					continue;
				}

				if ((*nifa = calloc(sizeof (**nifa), 1))
				    != NULL) {
					(*nifa)->family = AF_INET;
					(*nifa)->ipaddr_atype =
					    IPADM_ADDR_STATIC;
					(*nifa)->ipaddr = ipaddr;
					nifa = &((*nifa)->next);
				} else {
					nlog(LOG_ERR,
					    "populate_ip_ncu_properties: "
					    "couldn't allocate nwamd address "
					    "for %s: %s", addrvalue[i],
					    strerror(errno));
					ipadm_destroy_addrobj(ipaddr);
				}
			}
			*nifa = NULL;

			nwam_value_free(ncu_prop);
		}
	}

	/* get default route, if any */
	if ((err = nwamd_get_ncu_string(ncuh, &ncu_prop, &addrvalue,
	    &numvalues, NWAM_NCU_PROP_IPV4_DEFAULT_ROUTE)) == NWAM_SUCCESS) {
		/* Only one default route is allowed. */
		nif->nwamd_if_ipv4_default_route.sin_family = AF_INET;
		(void) inet_pton(AF_INET, addrvalue[0],
		    &(nif->nwamd_if_ipv4_default_route.sin_addr));
		nif->nwamd_if_ipv4_default_route_set = B_TRUE;
		nwam_value_free(ncu_prop);
	}

skip_ipv4:
	if (!nif->nwamd_if_ipv6)
		goto skip_ipv6;

	/* ipv6-addrsrc */
	static_addr = B_FALSE;
	if ((err = nwamd_get_ncu_uint(ncuh, &ncu_prop, &addrsrcvalue,
	    &numvalues, NWAM_NCU_PROP_IPV6_ADDRSRC)) != NWAM_SUCCESS) {
		nlog(nif->nwamd_if_ipv6 ? LOG_ERR : LOG_DEBUG,
		    "populate_ip_ncu_properties: could not get %s value: %s",
		    NWAM_NCU_PROP_IPV6_ADDRSRC, nwam_strerror(err));
	} else {
		for (i = 0; i < numvalues; i++) {
			switch (addrsrcvalue[i]) {
			case NWAM_ADDRSRC_DHCP:
				nif->nwamd_if_stateful_requested = B_TRUE;
				break;
			case NWAM_ADDRSRC_AUTOCONF:
				nif->nwamd_if_stateless_requested = B_TRUE;
				break;
			case NWAM_ADDRSRC_STATIC:
				static_addr = B_TRUE;
				break;
			default:
				break;
			}
		}
		nwam_value_free(ncu_prop);
	}
	/*
	 * Both stateful and stateless share the same nwamd_if_address because
	 * only one ipaddr for both of these addresses can be created.
	 * ipadm_create_addr() adds both addresses from the same ipaddr.
	 */
	if (nif->nwamd_if_stateful_requested ||
	    nif->nwamd_if_stateless_requested) {
		ipstatus = ipadm_create_addrobj(IPADM_ADDR_IPV6_ADDRCONF,
		    ncu_data->ncu_name, &ipaddr);
		if (ipstatus != IPADM_SUCCESS) {
			nlog(LOG_ERR, "populate_ip_ncu_properties: "
			    "ipadm_create_addrobj failed for v6 "
			    "stateless/stateful: %s",
			    ipadm_status2str(ipstatus));
			goto skip_ipv6_addrconf;
		}
		/* create_addrobj sets both stateless and stateful to B_TRUE */
		if (!nif->nwamd_if_stateful_requested) {
			ipstatus = ipadm_set_stateful(ipaddr, B_FALSE);
			if (ipstatus != IPADM_SUCCESS) {
				nlog(LOG_ERR, "populate_ip_ncu_properties: "
				    "ipadm_set_stateful failed for v6: %s",
				    ipadm_status2str(ipstatus));
				ipadm_destroy_addrobj(ipaddr);
				goto skip_ipv6_addrconf;
			}
		}
		if (!nif->nwamd_if_stateless_requested) {
			ipstatus = ipadm_set_stateless(ipaddr, B_FALSE);
			if (ipstatus != IPADM_SUCCESS) {
				nlog(LOG_ERR, "populate_ip_ncu_properties: "
				    "ipadm_set_stateless failed for v6: %s",
				    ipadm_status2str(ipstatus));
				ipadm_destroy_addrobj(ipaddr);
				goto skip_ipv6_addrconf;
			}
		}
		if ((*nifa = calloc(sizeof (**nifa), 1)) != NULL) {
			(*nifa)->family = AF_INET6;
			(*nifa)->ipaddr_atype = IPADM_ADDR_IPV6_ADDRCONF;
			(*nifa)->ipaddr = ipaddr;
			nifa = &((*nifa)->next);
			*nifa = NULL;
		} else {
			nlog(LOG_ERR, "populate_ip_ncu_properties: "
			    "couldn't allocate nwamd address for "
			    "v6 stateless/stateful: %s", strerror(errno));
			ipadm_destroy_addrobj(ipaddr);
		}
	}

skip_ipv6_addrconf:
	/* ipv6-addr */
	if (static_addr) {
		if ((err = nwamd_get_ncu_string(ncuh, &ncu_prop, &addrvalue,
		    &numvalues, NWAM_NCU_PROP_IPV6_ADDR)) != NWAM_SUCCESS) {
			nlog(LOG_ERR, "populate_ip_ncu_properties: "
			    "could not get %s value: %s",
			    NWAM_NCU_PROP_IPV6_ADDR, nwam_strerror(err));
		} else {
			for (i = 0; i < numvalues; i++) {
				ipstatus = ipadm_create_addrobj(
				    IPADM_ADDR_STATIC, ncu_data->ncu_name,
				    &ipaddr);
				if (ipstatus != IPADM_SUCCESS) {
					nlog(LOG_ERR,
					    "populate_ip_ncu_properties: "
					    "ipadm_create_addrobj failed "
					    "for %s: %s", addrvalue[i],
					    ipadm_status2str(ipstatus));
					continue;
				}
				/* ipadm_set_addr takes <addr>[/<mask>] */
				ipstatus = ipadm_set_addr(ipaddr, addrvalue[i],
				    AF_INET6);
				if (ipstatus != IPADM_SUCCESS) {
					nlog(LOG_ERR,
					    "populate_ip_ncu_properties: "
					    "ipadm_set_addr failed for %s: %s",
					    addrvalue[i],
					    ipadm_status2str(ipstatus));
					ipadm_destroy_addrobj(ipaddr);
					continue;
				}

				if ((*nifa = calloc(sizeof (**nifa), 1))
				    != NULL) {
					(*nifa)->family = AF_INET6;
					(*nifa)->ipaddr_atype =
					    IPADM_ADDR_STATIC;
					(*nifa)->ipaddr = ipaddr;
					nifa = &((*nifa)->next);
				} else {
					nlog(LOG_ERR,
					    "populate_ip_ncu_properties: "
					    "couldn't allocate nwamd address "
					    "for %s: %s", addrvalue[i],
					    strerror(errno));
					ipadm_destroy_addrobj(ipaddr);
				}
			}
			*nifa = NULL;

			nwam_value_free(ncu_prop);
		}
	}

	/* get default route, if any */
	if ((err = nwamd_get_ncu_string(ncuh, &ncu_prop, &addrvalue,
	    &numvalues, NWAM_NCU_PROP_IPV6_DEFAULT_ROUTE)) == NWAM_SUCCESS) {
		/* Only one default route is allowed. */
		nif->nwamd_if_ipv6_default_route.sin6_family = AF_INET6;
		(void) inet_pton(AF_INET6, addrvalue[0],
		    &(nif->nwamd_if_ipv6_default_route.sin6_addr));
		nif->nwamd_if_ipv6_default_route_set = B_TRUE;
		nwam_value_free(ncu_prop);
	}

skip_ipv6:
	;
}

static nwamd_ncu_t *
nwamd_ncu_init(nwam_ncu_type_t ncu_type, const char *name)
{
	nwamd_ncu_t *rv;

	nlog(LOG_DEBUG, "nwamd_ncu_init(%d, %s)", ncu_type, name);

	if ((rv = calloc(1, sizeof (*rv))) == NULL)
		return (NULL);

	rv->ncu_type = ncu_type;
	rv->ncu_name = strdup(name);
	rv->ncu_enabled = B_FALSE;

	/* Initialize link/interface-specific data */
	if (rv->ncu_type == NWAM_NCU_TYPE_LINK) {
		(void) bzero(&rv->ncu_link, sizeof (nwamd_link_t));
		(void) dladm_name2info(dld_handle, name,
		    &rv->ncu_link.nwamd_link_id, NULL, NULL,
		    &rv->ncu_link.nwamd_link_media);
		(void) pthread_mutex_init(
		    &rv->ncu_link.nwamd_link_wifi_mutex, NULL);
		rv->ncu_link.nwamd_link_wifi_priority = MAXINT;
	} else {
		(void) bzero(&rv->ncu_if, sizeof (nwamd_if_t));
	}

	return (rv);
}

void
nwamd_ncu_free(nwamd_ncu_t *ncu)
{
	if (ncu != NULL) {
		assert(ncu->ncu_type == NWAM_NCU_TYPE_LINK ||
		    ncu->ncu_type == NWAM_NCU_TYPE_INTERFACE);
		if (ncu->ncu_type == NWAM_NCU_TYPE_LINK) {
			struct nwamd_link *l = &ncu->ncu_link;
			int i;

			free(l->nwamd_link_wifi_key);
			free(l->nwamd_link_mac_addr);
			for (i = 0; i < l->nwamd_link_num_autopush; i++)
				free(l->nwamd_link_autopush[i]);
		} else if (ncu->ncu_type == NWAM_NCU_TYPE_INTERFACE) {
			struct nwamd_if_address *nifa;

			nifa = ncu->ncu_if.nwamd_if_list;
			while (nifa != NULL) {
				struct nwamd_if_address *n;

				n = nifa;
				nifa = nifa->next;
				ipadm_destroy_addrobj(n->ipaddr);
				free(n);
			}
		}
		free(ncu->ncu_name);
		free(ncu);
	}
}

static int
nwamd_ncu_display(nwamd_object_t ncu_obj, void *data)
{
	nwamd_ncu_t *ncu = (nwamd_ncu_t *)ncu_obj->nwamd_object_data;
	data = data;
	nlog(LOG_DEBUG, "NCU (%p) %s state %s, %s",
	    (void *)ncu, ncu_obj->nwamd_object_name,
	    nwam_state_to_string(ncu_obj->nwamd_object_state),
	    nwam_aux_state_to_string(ncu_obj->nwamd_object_aux_state));
	return (0);
}

void
nwamd_log_ncus(void)
{
	nlog(LOG_DEBUG, "NCP %s", active_ncp);
	(void) nwamd_walk_objects(NWAM_OBJECT_TYPE_NCU, nwamd_ncu_display,
	    NULL);
}

int
nwamd_ncu_action(const char *ncu, const char *parent, nwam_action_t action)
{
	nwamd_event_t ncu_event = nwamd_event_init_object_action
	    (NWAM_OBJECT_TYPE_NCU, ncu, parent, action);
	if (ncu_event == NULL)
		return (1);
	nwamd_event_enqueue(ncu_event);
	return (0);
}

static void
add_phys_ncu_to_ncp(nwam_ncp_handle_t ncph, const char *name)
{
	dladm_status_t dlrtn;
	uint32_t media;
	boolean_t is_wireless;
	nwam_error_t err;
	nwam_ncu_handle_t ncuh;
	uint64_t uintval;

	if ((dlrtn = dladm_name2info(dld_handle, name, NULL, NULL, NULL,
	    &media)) != DLADM_STATUS_OK) {
		char errmsg[DLADM_STRSIZE];
		nlog(LOG_ERR, "failed to get media type for %s: %s", name,
		    dladm_status2str(dlrtn, errmsg));
		return;
	}
	is_wireless = (media == DL_WIFI);

	if ((err = nwam_ncu_create(ncph, name, NWAM_NCU_TYPE_LINK,
	    NWAM_NCU_CLASS_PHYS, &ncuh)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "failed to create link ncu for %s: %s", name,
		    nwam_strerror(err));
		if (err == NWAM_ENTITY_READ_ONLY) {
			nwamd_event_t retry_event;

			/*
			 * Root filesystem may be read-only, retry in
			 * a few seconds.
			 */
			nlog(LOG_DEBUG, "Retrying addition of phys ncu for %s",
			    name);
			retry_event = nwamd_event_init_link_action(name,
			    NWAM_ACTION_ADD);
			if (retry_event != NULL) {
				nwamd_event_enqueue_timed(retry_event,
				    NWAMD_READONLY_RETRY_INTERVAL);
			}
		}
		return;
	}

	uintval = NWAM_ACTIVATION_MODE_PRIORITIZED;
	if ((err = nwamd_set_ncu_uint(ncuh, &uintval, 1,
	    NWAM_NCU_PROP_ACTIVATION_MODE)) != NWAM_SUCCESS) {
		goto finish;
	}

	uintval = is_wireless ? 1 : 0;
	if ((err = nwamd_set_ncu_uint(ncuh, &uintval, 1,
	    NWAM_NCU_PROP_PRIORITY_GROUP)) != NWAM_SUCCESS) {
		goto finish;
	}

	uintval = is_wireless ? NWAM_PRIORITY_MODE_EXCLUSIVE :
	    NWAM_PRIORITY_MODE_SHARED;
	if ((err = nwamd_set_ncu_uint(ncuh, &uintval, 1,
	    NWAM_NCU_PROP_PRIORITY_MODE)) != NWAM_SUCCESS) {
		goto finish;
	}

	err = nwam_ncu_commit(ncuh, 0);

finish:
	nwam_ncu_free(ncuh);
	if (err != NWAM_SUCCESS) {
		nlog(LOG_ERR,
		    "failed to create automatic link ncu for %s: %s",
		    name, nwam_strerror(err));
	}
}

static void
add_ip_ncu_to_ncp(nwam_ncp_handle_t ncph, const char *name)
{
	nwam_error_t err;
	nwam_ncu_handle_t ncuh;

	if ((err = nwam_ncu_create(ncph, name, NWAM_NCU_TYPE_INTERFACE,
	    NWAM_NCU_CLASS_IP, &ncuh)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "failed to create ip ncu for %s: %s", name,
		    nwam_strerror(err));
		/*
		 * Root filesystem may be read-only, but no need to
		 * retry here since add_phys_ncu_to_ncp() enqueues
		 * a retry event which will lead to add_ip_ncu_to_ncp()
		 * being called.
		 */
		return;
	}

	/* IP NCU has the default values, so nothing else to do */
	err = nwam_ncu_commit(ncuh, 0);

	nwam_ncu_free(ncuh);
	if (err != NWAM_SUCCESS) {
		nlog(LOG_ERR,
		    "failed to create ip ncu for %s: %s", name,
		    nwam_strerror(err));
	}
}

static void
remove_ncu_from_ncp(nwam_ncp_handle_t ncph, const char *name,
    nwam_ncu_type_t type)
{
	nwam_error_t err;
	nwam_ncu_handle_t ncuh;

	if ((err = nwam_ncu_read(ncph, name, type, 0, &ncuh)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "failed to read automatic ncu %s: %s", name,
		    nwam_strerror(err));
		return;
	}

	err = nwam_ncu_destroy(ncuh, 0);
	if (err != NWAM_SUCCESS) {
		nlog(LOG_ERR, "failed to delete automatic ncu %s: %s", name,
		    nwam_strerror(err));
	}
}

/*
 * Device represented by NCU has been added or removed for the active
 * User NCP.  If an associated NCU of the given type is found, transition it
 * to the appropriate state.
 */
void
ncu_action_change_state(nwam_action_t action, nwam_ncu_type_t type,
    const char *name)
{
	nwamd_object_t ncu_obj = NULL;
	nwamd_ncu_t *ncu;

	if ((ncu_obj = nwamd_ncu_object_find(type, name)) == NULL)
		return;

	ncu = ncu_obj->nwamd_object_data;

	/*
	 * If device has been added, transition from uninitialized to offline.
	 * If device has been removed, transition to uninitialized (via online*
	 * if the NCU is currently enabled in order to tear down config).
	 */
	if (action == NWAM_ACTION_ADD) {
		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
		    ncu_obj->nwamd_object_name,
		    NWAM_STATE_OFFLINE, NWAM_AUX_STATE_CONDITIONS_NOT_MET);
	} else {
		if (ncu->ncu_enabled) {
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    ncu_obj->nwamd_object_name,
			    NWAM_STATE_ONLINE_TO_OFFLINE,
			    NWAM_AUX_STATE_NOT_FOUND);
		} else {
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    ncu_obj->nwamd_object_name,
			    NWAM_STATE_UNINITIALIZED,
			    NWAM_AUX_STATE_NOT_FOUND);
		}
	}
	nwamd_object_release(ncu_obj);
}

/*
 * Called with hotplug sysevent or when nwam is started and walking the
 * physical interfaces.  Add/remove both link and interface NCUs from the
 * Automatic NCP.  Assumes that both link and interface NCUs don't exist.
 */
void
nwamd_ncu_handle_link_action_event(nwamd_event_t event)
{
	nwam_ncp_handle_t ncph;
	nwam_ncu_type_t type;
	nwam_action_t action =
	    event->event_msg->nwe_data.nwe_link_action.nwe_action;
	nwam_error_t err;
	char *name;
	boolean_t automatic_ncp_active = B_FALSE;

	if (action != NWAM_ACTION_ADD && action != NWAM_ACTION_REMOVE) {
		nlog(LOG_ERR, "nwamd_ncu_handle_link_action_event: "
		    "invalid link action %s", nwam_action_to_string(action));
		nwamd_event_do_not_send(event);
		return;
	}

	nlog(LOG_DEBUG, "nwamd_ncu_handle_link_action_event: "
	    "link action '%s' event on %s", nwam_action_to_string(action),
	    event->event_object[0] == 0 ? "n/a" : event->event_object);

	if ((err = nwam_ncu_typed_name_to_name(event->event_object, &type,
	    &name)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_ncu_handle_link_action_event: "
		    "translation from typedname error: %s", nwam_strerror(err));
		nwamd_event_do_not_send(event);
		return;
	}

	(void) pthread_mutex_lock(&active_ncp_mutex);
	if (strcmp(active_ncp, NWAM_NCP_NAME_AUTOMATIC) == 0 &&
	    active_ncph != NULL) {
		automatic_ncp_active = B_TRUE;
	}
	(void) pthread_mutex_unlock(&active_ncp_mutex);

	/*
	 * We could use active_ncph for cases where the Automatic NCP is active,
	 * but that would involve holding the active_ncp_mutex for too long.
	 */
	if ((err = nwam_ncp_read(NWAM_NCP_NAME_AUTOMATIC, 0, &ncph))
	    == NWAM_ENTITY_NOT_FOUND) {
		/* Automatic NCP doesn't exist, create it */
		err = nwam_ncp_create(NWAM_NCP_NAME_AUTOMATIC, 0, &ncph);
	}
	if (err != NWAM_SUCCESS)
		goto fail;

	/* add or remove NCUs from Automatic NCP */
	if (action == NWAM_ACTION_ADD) {
		add_phys_ncu_to_ncp(ncph, name);
		add_ip_ncu_to_ncp(ncph, name);
	} else {
		/*
		 * Order is important here, remove IP NCU first to prevent
		 * propogation of down event from link to IP.  No need to
		 * create REFRESH or DESTROY events.  They are generated by
		 * nwam_ncu_commit() and nwam_ncu_destroy().
		 */
		remove_ncu_from_ncp(ncph, name, NWAM_NCU_TYPE_INTERFACE);
		remove_ncu_from_ncp(ncph, name, NWAM_NCU_TYPE_LINK);
	}
	nwam_ncp_free(ncph);

	/*
	 * If the Automatic NCP is not active, and the associated NCUs
	 * exist, they must be moved into the appropriate states given the
	 * action that has occurred.
	 */
	if (!automatic_ncp_active) {
		ncu_action_change_state(action, NWAM_NCU_TYPE_INTERFACE, name);
		ncu_action_change_state(action, NWAM_NCU_TYPE_LINK, name);
	}

	/* Need NCU check to evaluate state in light of added/removed NCUs */
	if (!nwamd_event_enqueued(NWAM_EVENT_TYPE_NCU_CHECK,
	    NWAM_OBJECT_TYPE_NCP, NULL)) {
		nwamd_create_ncu_check_event(NEXT_FEW_SECONDS);
	}

fail:
	free(name);
	if (err != NWAM_SUCCESS) {
		nwamd_event_t retry_event = nwamd_event_init_link_action(name,
		    action);
		if (retry_event == NULL) {
			nlog(LOG_ERR, "nwamd_ncu_handle_link_action_event: "
			    "could not create retry event to read/create "
			    "%s NCP", NWAM_NCP_NAME_AUTOMATIC);
			return;
		}

		nlog(LOG_ERR, "nwamd_ncu_handle_link_action_event: "
		    "could not read/create %s NCP, retrying in %d seconds",
		    NWAM_NCP_NAME_AUTOMATIC, NWAMD_READONLY_RETRY_INTERVAL);
		nwamd_event_enqueue_timed(retry_event,
		    NWAMD_READONLY_RETRY_INTERVAL);
	}
}

/*
 * Figure out if this link is part of an aggregation.  This is fairly
 * inefficient since we generate this list for every query and search
 * linearly.  A better way would be to generate the list of links in an
 * aggregation once and then check each link against it.
 */
struct link_aggr_search_data {
	datalink_id_t linkid;
	boolean_t under;
};

static int
ncu_aggr_search(const char *name, void *data)
{
	struct link_aggr_search_data *lasd = data;
	dladm_aggr_grp_attr_t ginfo;
	datalink_id_t linkid;
	int i;

	if (dladm_name2info(dld_handle, name, &linkid, NULL, NULL, NULL) !=
	    DLADM_STATUS_OK)
		return (DLADM_WALK_CONTINUE);
	if (dladm_aggr_info(dld_handle, linkid, &ginfo, DLADM_OPT_ACTIVE)
	    != DLADM_STATUS_OK || ginfo.lg_nports == 0)
		return (DLADM_WALK_CONTINUE);

	for (i = 0; i < ginfo.lg_nports; i++) {
		if (lasd->linkid == ginfo.lg_ports[i].lp_linkid) {
			lasd->under = B_TRUE;
			return (DLADM_WALK_TERMINATE);
		}
	}
	free(ginfo.lg_ports);
	return (DLADM_WALK_CONTINUE);
}

static boolean_t
nwamd_link_belongs_to_an_aggr(const char *name)
{
	struct link_aggr_search_data lasd;

	if (dladm_name2info(dld_handle, name, &lasd.linkid, NULL, NULL, NULL)
	    != DLADM_STATUS_OK)
		return (B_FALSE);
	lasd.under = B_FALSE;
	(void) dladm_walk(ncu_aggr_search, dld_handle, &lasd,
	    DATALINK_CLASS_AGGR, DATALINK_ANY_MEDIATYPE, DLADM_OPT_ACTIVE);
	return (lasd.under);
}

/*
 * If NCU doesn't exist for interface with given name, enqueue a ADD
 * LINK_ACTION event.
 */
static int
ncu_create_link_action_event(const char *name, void *data)
{
	nwam_ncp_handle_t ncph = data;
	nwam_ncu_handle_t ncuh;
	nwamd_event_t link_event;

	/* Do not generate an event if this is a VirtualBox interface. */
	if (strncmp(name, VBOX_IFACE_PREFIX, strlen(VBOX_IFACE_PREFIX)) == 0)
		return (DLADM_WALK_CONTINUE);

	/* Do not generate an event if this link belongs to another zone. */
	if (!nwamd_link_belongs_to_this_zone(name))
		return (DLADM_WALK_CONTINUE);

	/* Do not generate an event if this link belongs to an aggregation. */
	if (nwamd_link_belongs_to_an_aggr(name)) {
		return (DLADM_WALK_CONTINUE);
	}

	/* Don't create an event if the NCU already exists. */
	if (ncph != NULL && nwam_ncu_read(ncph, name, NWAM_NCU_TYPE_LINK, 0,
	    &ncuh) == NWAM_SUCCESS) {
		nwam_ncu_free(ncuh);
		return (DLADM_WALK_CONTINUE);
	}

	nlog(LOG_DEBUG, "ncu_create_link_action_event: adding ncus for %s",
	    name);

	link_event = nwamd_event_init_link_action(name, NWAM_ACTION_ADD);
	if (link_event != NULL)
		nwamd_event_enqueue(link_event);

	return (DLADM_WALK_CONTINUE);
}

/*
 * Check if interface exists for this NCU. If not, enqueue a REMOVE
 * LINK_ACTION event.
 */
/* ARGSUSED */
static int
nwamd_destroy_ncu(nwam_ncu_handle_t ncuh, void *data)
{
	char *name;
	uint32_t flags;
	nwamd_event_t link_event;

	if (nwam_ncu_get_name(ncuh, &name) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_destroy_ncu: could not get NCU name");
		return (0);
	}

	/* Interfaces that exist return DLADM_OPT_ACTIVE flag */
	if ((dladm_name2info(dld_handle, name, NULL, &flags, NULL, NULL)
	    == DLADM_STATUS_OK && (flags & DLADM_OPT_ACTIVE)) &&
	    !nwamd_link_belongs_to_an_aggr(name)) {
		free(name);
		return (0);
	}

	nlog(LOG_DEBUG, "nwamd_destroy_ncu: destroying ncus for %s", name);

	link_event = nwamd_event_init_link_action(name, NWAM_ACTION_REMOVE);
	if (link_event != NULL)
		nwamd_event_enqueue(link_event);
	free(name);
	return (0);
}

/*
 * Called when nwamd is starting up.
 *
 * Walk all NCUs and destroy any NCU from the Automatic NCP without an
 * underlying interface (assumption here is that the interface was removed
 * when nwam was disabled).
 *
 * Walk the physical interfaces and create ADD LINK_ACTION event, which
 * will create appropriate interface and link NCUs in the Automatic NCP.
 */
void
nwamd_walk_physical_configuration(void)
{
	nwam_ncp_handle_t ncph;
	datalink_class_t dlclass = DATALINK_CLASS_PHYS;
	zoneid_t zoneid = getzoneid();

	(void) pthread_mutex_lock(&active_ncp_mutex);
	if (strcmp(active_ncp, NWAM_NCP_NAME_AUTOMATIC) == 0 &&
	    active_ncph != NULL) {
		ncph = active_ncph;
	} else {
		if (nwam_ncp_read(NWAM_NCP_NAME_AUTOMATIC, 0, &ncph)
		    != NWAM_SUCCESS) {
			ncph = NULL;
		}
	}

	/* destroy NCUs for interfaces that don't exist */
	if (ncph != NULL) {
		(void) nwam_ncp_walk_ncus(ncph, nwamd_destroy_ncu, NULL,
		    NWAM_FLAG_NCU_TYPE_LINK, NULL);
	}

	/* In non-global zones NWAM can support VNICs */
	if (zoneid != GLOBAL_ZONEID)
		dlclass |= DATALINK_CLASS_VNIC;

	/* create NCUs for interfaces without NCUs */
	(void) dladm_walk(ncu_create_link_action_event, dld_handle, ncph,
	    dlclass, DATALINK_ANY_MEDIATYPE, DLADM_OPT_ACTIVE);

	if (strcmp(active_ncp, NWAM_NCP_NAME_AUTOMATIC) != 0 ||
	    active_ncph == NULL) {
		nwam_ncp_free(ncph);
	}
	(void) pthread_mutex_unlock(&active_ncp_mutex);
}

/*
 * Handle NCU initialization/refresh event.
 */
void
nwamd_ncu_handle_init_event(nwamd_event_t event)
{
	nwamd_object_t object = NULL;
	nwam_ncu_handle_t ncuh;
	nwamd_ncu_t *ncu = NULL;
	nwam_error_t err;
	nwam_ncu_type_t type;
	char *name;
	uint32_t flags;
	boolean_t new = B_TRUE;

	nlog(LOG_DEBUG, "nwamd_ncu_handle_init_event(%s)",
	    event->event_object);

	/* Get base linkname rather than interface:linkname or link:linkname */
	err = nwam_ncu_typed_name_to_name(event->event_object,
	    &type, &name);
	if (err != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_ncu_handle_init_event: "
		    "nwam_ncu_typed_name_to_name returned %s",
		    nwam_strerror(err));
		nwamd_event_do_not_send(event);
		return;
	}

	(void) pthread_mutex_lock(&active_ncp_mutex);
	if (active_ncph == NULL) {
		nlog(LOG_DEBUG,
		    "nwamd_ncu_handle_init_event: active NCP handle NULL");
		nwamd_event_do_not_send(event);
		free(name);
		(void) pthread_mutex_unlock(&active_ncp_mutex);
		return;
	}
	err = nwam_ncu_read(active_ncph, event->event_object,
	    type, 0, &ncuh);
	(void) pthread_mutex_unlock(&active_ncp_mutex);
	if (err != NWAM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_ncu_handle_init_event: "
		    "could not read object '%s': %s",
		    event->event_object, nwam_strerror(err));
		free(name);
		nwamd_event_do_not_send(event);
		return;
	}

	if ((object = nwamd_object_find(NWAM_OBJECT_TYPE_NCU,
	    event->event_object)) != NULL)
		new = B_FALSE;

	/*
	 * For new NCUs, or interface NCUs, we (re)initialize data from scratch.
	 * For link NCUs, we want to retain object data.
	 */
	switch (type) {
	case NWAM_NCU_TYPE_LINK:
		if (new) {
			ncu = nwamd_ncu_init(type, name);
		} else {
			ncu = object->nwamd_object_data;
			nwam_ncu_free(object->nwamd_object_handle);
		}
		populate_common_ncu_properties(ncuh, ncu);
		populate_link_ncu_properties(ncuh, ncu);
		break;
	case NWAM_NCU_TYPE_INTERFACE:
		if (!new) {
			nwam_ncu_free(object->nwamd_object_handle);
			nwamd_ncu_free(object->nwamd_object_data);
		}
		ncu = nwamd_ncu_init(type, name);
		populate_common_ncu_properties(ncuh, ncu);
		populate_ip_ncu_properties(ncuh, ncu);
		break;
	default:
		nlog(LOG_ERR, "unknown ncu type %d", type);
		free(name);
		nwam_ncu_free(ncuh);
		nwamd_event_do_not_send(event);
		nwamd_object_release(object);
		return;
	}

	if (new) {
		nlog(LOG_DEBUG, "nwamd_ncu_handle_init_event: didn't find "
		    "ncu so create it %s", name);
		object = nwamd_object_init(NWAM_OBJECT_TYPE_NCU,
		    event->event_object, ncuh, ncu);
	} else {
		nlog(LOG_DEBUG, "nwamd_ncu_handle_init_event: refreshing "
		    "ncu %s", name);
		object->nwamd_object_data = ncu;
		object->nwamd_object_handle = ncuh;
	}

	/*
	 * If the physical link for this NCU doesn't exist in the system,
	 * the state should be UNINITIALIZED/NOT_FOUND.  Interfaces that
	 * exist return DLADM_OPT_ACTIVE flag.
	 */
	if (dladm_name2info(dld_handle, name, NULL, &flags, NULL, NULL)
	    != DLADM_STATUS_OK || !(flags & DLADM_OPT_ACTIVE)) {
		nlog(LOG_DEBUG, "nwam_ncu_handle_init_event: "
		    "interface for NCU %s doesn't exist",
		    event->event_object);
		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
		    object->nwamd_object_name, NWAM_STATE_UNINITIALIZED,
		    NWAM_AUX_STATE_NOT_FOUND);
		free(name);
		nwamd_object_release(object);
		return;
	}

	/*
	 * If NCU is being initialized (rather than refreshed), the
	 * object_state is INITIALIZED (from nwamd_object_init()).
	 */
	if (object->nwamd_object_state == NWAM_STATE_INITIALIZED) {
		/*
		 * If the NCU is disabled, initial state should be DISABLED.
		 *
		 * Otherwise, the initial state will be
		 * OFFLINE/CONDITIONS_NOT_MET, and the link selection
		 * algorithm will do the rest.
		 */
		if (!ncu->ncu_enabled) {
			object->nwamd_object_state = NWAM_STATE_DISABLED;
			object->nwamd_object_aux_state =
			    NWAM_AUX_STATE_MANUAL_DISABLE;
		} else {
			object->nwamd_object_state = NWAM_STATE_OFFLINE;
			object->nwamd_object_aux_state =
			    NWAM_AUX_STATE_CONDITIONS_NOT_MET;
		}
	} else {
		nwamd_link_t *link = &ncu->ncu_link;

		/*
		 * Refresh NCU.  Deal with disabled cases first, moving NCUs
		 * that are not disabled - but have the enabled value set - to
		 * the disabled state.  Then handle cases where the NCU was
		 * disabled but is no longer.  Finally,  deal with refresh of
		 * link and interface NCUs, as these are handled differently.
		 */
		if (!ncu->ncu_enabled) {
			if (object->nwamd_object_state != NWAM_STATE_DISABLED) {
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    object->nwamd_object_name,
				    NWAM_STATE_ONLINE_TO_OFFLINE,
				    NWAM_AUX_STATE_MANUAL_DISABLE);
			}
			goto done;
		} else {
			if (object->nwamd_object_state == NWAM_STATE_DISABLED) {
				int64_t c;

				/*
				 * Try to activate the NCU if manual or
				 * prioritized (when priority <= current).
				 */
				(void) pthread_mutex_lock(&active_ncp_mutex);
				c = current_ncu_priority_group;
				(void) pthread_mutex_unlock(&active_ncp_mutex);
				if (link->nwamd_link_activation_mode ==
				    NWAM_ACTIVATION_MODE_MANUAL ||
				    (link->nwamd_link_activation_mode ==
				    NWAM_ACTIVATION_MODE_PRIORITIZED &&
				    link->nwamd_link_priority_mode <= c)) {
					nwamd_object_set_state
					    (NWAM_OBJECT_TYPE_NCU,
					    object->nwamd_object_name,
					    NWAM_STATE_OFFLINE_TO_ONLINE,
					    NWAM_AUX_STATE_INITIALIZED);
				} else {
					nwamd_object_set_state
					    (NWAM_OBJECT_TYPE_NCU,
					    object->nwamd_object_name,
					    NWAM_STATE_OFFLINE_TO_ONLINE,
					    NWAM_AUX_STATE_INITIALIZED);
				}
				goto done;
			}
		}

		switch (type) {
		case NWAM_NCU_TYPE_LINK:
			if (ncu->ncu_link.nwamd_link_media == DL_WIFI) {
				/*
				 * Do rescan.  If the current state and the
				 * active priority-group do not allow wireless
				 * network selection, then it won't happen.
				 */
				(void) nwamd_wlan_scan(ncu->ncu_name);
			}
			break;
		case NWAM_NCU_TYPE_INTERFACE:
			/*
			 * If interface NCU is offline*, online or in
			 * maintenance, mark it down (from there, it will be
			 * reinitialized to reapply addresses).
			 */
			if (object->nwamd_object_state != NWAM_STATE_OFFLINE) {
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    object->nwamd_object_name,
				    NWAM_STATE_ONLINE_TO_OFFLINE,
				    NWAM_AUX_STATE_DOWN);
			} else {
				object->nwamd_object_state = NWAM_STATE_OFFLINE;
				object->nwamd_object_aux_state =
				    NWAM_AUX_STATE_CONDITIONS_NOT_MET;
			}
			break;
		}
	}

done:
	if (type == NWAM_NCU_TYPE_LINK &&
	    !nwamd_event_enqueued(NWAM_EVENT_TYPE_NCU_CHECK,
	    NWAM_OBJECT_TYPE_NCP, NULL)) {
		nwamd_create_ncu_check_event(NEXT_FEW_SECONDS);
	}
	free(name);
	nwamd_object_release(object);
}

void
nwamd_ncu_handle_fini_event(nwamd_event_t event)
{
	nwamd_object_t object;
	nwamd_event_t state_event;

	nlog(LOG_DEBUG, "nwamd_ncu_handle_fini_event(%s)",
	    event->event_object);

	/*
	 * Simulate a state event so that the state machine can correctly
	 * disable the NCU.  Then free up allocated objects.
	 */
	state_event = nwamd_event_init_object_state(NWAM_OBJECT_TYPE_NCU,
	    event->event_object, NWAM_STATE_ONLINE_TO_OFFLINE,
	    NWAM_AUX_STATE_UNINITIALIZED);
	if (state_event == NULL) {
		nwamd_event_do_not_send(event);
		return;
	}
	nwamd_ncu_handle_state_event(state_event);
	nwamd_event_fini(state_event);

	if ((object = nwamd_object_find(NWAM_OBJECT_TYPE_NCU,
	    event->event_object)) == NULL) {
		nlog(LOG_INFO, "nwamd_ncu_handle_fini_event: "
		    "ncu %s not found", event->event_object);
		nwamd_event_do_not_send(event);
		return;
	}
	nwamd_object_release_and_destroy(object);
}

void
nwamd_ncu_handle_action_event(nwamd_event_t event)
{
	nwamd_object_t object;

	(void) pthread_mutex_lock(&active_ncp_mutex);
	if (strcmp(event->event_msg->nwe_data.nwe_object_action.nwe_parent,
	    active_ncp) != 0) {
		nlog(LOG_DEBUG, "nwamd_ncu_handle_action_event: action for "
		    "inactive NCP %s, nothing to do",
		    event->event_msg->nwe_data.nwe_object_action.nwe_parent);
		(void) pthread_mutex_unlock(&active_ncp_mutex);
		return;
	}
	(void) pthread_mutex_unlock(&active_ncp_mutex);

	switch (event->event_msg->nwe_data.nwe_object_action.nwe_action) {
	case NWAM_ACTION_ENABLE:
		object = nwamd_object_find(NWAM_OBJECT_TYPE_NCU,
		    event->event_object);
		if (object == NULL) {
			nlog(LOG_ERR, "nwamd_ncu_handle_action_event: "
			    "could not find ncu %s", event->event_object);
			nwamd_event_do_not_send(event);
			return;
		}
		if (object->nwamd_object_state == NWAM_STATE_ONLINE) {
			nlog(LOG_DEBUG, "nwamd_ncu_handle_action_event: "
			    "ncu %s already online, nothing to do",
			    event->event_object);
			nwamd_object_release(object);
			return;
		}
		nwamd_object_release(object);

		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
		    event->event_object, NWAM_STATE_OFFLINE_TO_ONLINE,
		    NWAM_AUX_STATE_INITIALIZED);
		break;
	case NWAM_ACTION_DISABLE:
		object = nwamd_object_find(NWAM_OBJECT_TYPE_NCU,
		    event->event_object);
		if (object == NULL) {
			nlog(LOG_ERR, "nwamd_ncu_handle_action_event: "
			    "could not find ncu %s", event->event_object);
			nwamd_event_do_not_send(event);
			return;
		}
		if (object->nwamd_object_state == NWAM_STATE_DISABLED) {
			nlog(LOG_DEBUG, "nwamd_ncu_handle_action_event: "
			    "ncu %s already disabled, nothing to do",
			    event->event_object);
			nwamd_object_release(object);
			return;
		}
		nwamd_object_release(object);

		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
		    event->event_object, NWAM_STATE_ONLINE_TO_OFFLINE,
		    NWAM_AUX_STATE_MANUAL_DISABLE);
		break;
	case NWAM_ACTION_ADD:
	case NWAM_ACTION_REFRESH:
		nwamd_ncu_handle_init_event(event);
		break;
	case NWAM_ACTION_DESTROY:
		nwamd_ncu_handle_fini_event(event);
		break;
	default:
		nlog(LOG_INFO, "nwam_ncu_handle_action_event: "
		    "unexpected action");
		nwamd_event_do_not_send(event);
		break;
	}
}

void
nwamd_ncu_handle_state_event(nwamd_event_t event)
{
	nwamd_object_t object;
	nwam_state_t old_state, new_state;
	nwam_aux_state_t new_aux_state;
	nwamd_ncu_t *ncu;
	boolean_t is_link, enabled, prioritized = B_FALSE;
	char linkname[NWAM_MAX_NAME_LEN];
	nwam_event_t m = event->event_msg;

	if ((object = nwamd_object_find(NWAM_OBJECT_TYPE_NCU,
	    event->event_object)) == NULL) {
		nlog(LOG_INFO, "nwamd_ncu_handle_state_event %lld: "
		    "state event for nonexistent NCU %s", event->event_id,
		    event->event_object);
		nwamd_event_do_not_send(event);
		return;
	}
	ncu = object->nwamd_object_data;
	old_state = object->nwamd_object_state;
	new_state = event->event_msg->nwe_data.nwe_object_state.nwe_state;
	new_aux_state =
	    event->event_msg->nwe_data.nwe_object_state.nwe_aux_state;

	/*
	 * For NCU state changes, we need to supply the parent NCP name also,
	 * regardless of whether the event is handled or not.  It is best to
	 * fill this in here as we have the object lock - when we create
	 * object state events we sometimes do not have the object lock, but
	 * at this point in consuming the events (and prior to the associated
	 * event message being sent out) we do.
	 */
	(void) strlcpy(m->nwe_data.nwe_object_state.nwe_parent, ncu->ncu_parent,
	    sizeof (m->nwe_data.nwe_object_state.nwe_parent));

	/*
	 * If we receive a state change event moving this NCU to
	 * DHCP_TIMED_OUT or UP state but this NCU is already ONLINE, then
	 * ignore this state change event.
	 */
	if ((new_aux_state == NWAM_AUX_STATE_IF_DHCP_TIMED_OUT ||
	    new_aux_state == NWAM_AUX_STATE_UP) &&
	    object->nwamd_object_state == NWAM_STATE_ONLINE) {
		nlog(LOG_INFO, "nwamd_ncu_handle_state_event: "
		    "NCU %s already online, not going to '%s' state",
		    object->nwamd_object_name,
		    nwam_aux_state_to_string(new_aux_state));
		nwamd_event_do_not_send(event);
		nwamd_object_release(object);
		return;
	}

	if (new_state == object->nwamd_object_state &&
	    new_aux_state == object->nwamd_object_aux_state) {
		nlog(LOG_DEBUG, "nwamd_ncu_handle_state_event: "
		    "NCU %s already in state (%s, %s)",
		    object->nwamd_object_name, nwam_state_to_string(new_state),
		    nwam_aux_state_to_string(new_aux_state));
		nwamd_object_release(object);
		return;
	}

	if (old_state == NWAM_STATE_MAINTENANCE &&
	    (new_state == NWAM_STATE_ONLINE ||
	    (new_state == NWAM_STATE_OFFLINE_TO_ONLINE &&
	    new_aux_state != NWAM_AUX_STATE_INITIALIZED))) {
		nlog(LOG_DEBUG, "nwamd_ncu_handle_state_event: "
		    "NCU %s cannot transition from state %s to state (%s, %s)",
		    object->nwamd_object_name, nwam_state_to_string(old_state),
		    nwam_state_to_string(new_state),
		    nwam_aux_state_to_string(new_aux_state));
		nwamd_event_do_not_send(event);
		nwamd_object_release(object);
		return;
	}

	object->nwamd_object_state = new_state;
	object->nwamd_object_aux_state = new_aux_state;

	nlog(LOG_DEBUG, "nwamd_ncu_handle_state_event: changing state for NCU "
	    "%s to (%s, %s)", object->nwamd_object_name,
	    nwam_state_to_string(object->nwamd_object_state),
	    nwam_aux_state_to_string(object->nwamd_object_aux_state));

	is_link = (ncu->ncu_type == NWAM_NCU_TYPE_LINK);
	if (is_link)
		(void) strlcpy(linkname, ncu->ncu_name, sizeof (linkname));
	prioritized = (ncu->ncu_type == NWAM_NCU_TYPE_LINK &&
	    ncu->ncu_link.nwamd_link_activation_mode ==
	    NWAM_ACTIVATION_MODE_PRIORITIZED);
	enabled = ncu->ncu_enabled;

	nwamd_object_release(object);

	/*
	 * State machine for NCUs
	 */
	switch (new_state) {
	case NWAM_STATE_OFFLINE_TO_ONLINE:
		if (enabled) {
			nwamd_ncu_state_machine(event->event_object);
		} else {
			nlog(LOG_DEBUG, "nwamd_ncu_handle_state_event: "
			    "cannot move disabled NCU %s online",
			    event->event_object);
			nwamd_event_do_not_send(event);
		}
		break;

	case NWAM_STATE_ONLINE_TO_OFFLINE:
		nwamd_ncu_state_machine(event->event_object);
		break;

	case NWAM_STATE_ONLINE:
		/*
		 * We usually don't need to do anything when we're in the
		 * ONLINE state.  However, for  WiFi we can be in INIT or
		 * SCAN aux states while being ONLINE.
		 */
		nwamd_ncu_state_machine(event->event_object);
		break;

	case NWAM_STATE_OFFLINE:
		/* Reassess priority group now member is offline */
		if (prioritized) {
			nwamd_create_ncu_check_event(0);
		}
		break;

	case NWAM_STATE_DISABLED:
	case NWAM_STATE_UNINITIALIZED:
	case NWAM_STATE_MAINTENANCE:
	case NWAM_STATE_DEGRADED:
	default:
		/* do nothing */
		break;
	}

	if (is_link) {
		if ((new_state == NWAM_STATE_ONLINE_TO_OFFLINE &&
		    new_aux_state != NWAM_AUX_STATE_UNINITIALIZED &&
		    new_aux_state != NWAM_AUX_STATE_NOT_FOUND) ||
		    new_state == NWAM_STATE_DISABLED) {
			/*
			 * Going offline, propogate down event to IP NCU.  Do
			 * not propogate event if new aux state is uninitialized
			 * or not found as these auxiliary states signify
			 * that an NCP switch/device removal is in progress.
			 */
			nwamd_propogate_link_up_down_to_ip(linkname, B_FALSE);
		}
		if (new_state == NWAM_STATE_ONLINE) {
			/* gone online, propogate up event to IP NCU */
			nwamd_propogate_link_up_down_to_ip(linkname, B_TRUE);
		}
	} else {
		/* If IP NCU is online, reasses priority group */
		if (new_state == NWAM_STATE_ONLINE)
			nwamd_create_ncu_check_event(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>.
 */

#ifndef _NCU_H
#define	_NCU_H

#include <dhcpagent_ipc.h>
#include <dhcpagent_util.h>
#include <libdladm.h>
#include <libdlpi.h>
#include <libdlwlan.h>
#include <libinetutil.h>
#include <libipadm.h>
#include <libnwam.h>
#include <libnwam_priv.h>
#include <libuutil.h>
#include <pthread.h>
#include <sys/mac.h>

#include "events.h"

extern pthread_mutex_t active_ncp_mutex;
extern pthread_mutex_t active_loc_mutex;
extern char active_loc[];
extern uint64_t wireless_scan_interval;
extern dladm_wlan_strength_t wireless_scan_level;
extern boolean_t wireless_autoconf;
extern boolean_t wireless_strict_bssid;

/*
 * NCPs are collections of NCUs.  At the moment there is one NCP in the system
 * and its expected there will never be many.  There is a lock on the NCP which
 * must be obtained to add or remove anything from the NCP.
 *
 * NCUs are also kept in a uu list for easy walking.  Each NCU has a lock which
 * is used to protect manipulation of its contents.  One of its members is a
 * reference count which is initialized to 1 when its placed on the NCP.  As
 * references are passed around that should be manipulated as necessary
 * (helper functions YYY provided).  It is removed from the NCP by
 * ncu_destroy() but the memory containing it is not returned to the free pool
 * until the reference count falls to 0.
 *
 * As we add
 * more complex system objects their relationship becomes more complex.  That
 * is represented by the links within the NCUs.  Reference counts should be
 * used to maintain the consistency of these links.  Care should be used when
 * walking more complex structures that might contain cycles.
 */

/* Stores details of last/current WiFi scans */
typedef struct nwamd_wifi_scan {
	char nwamd_wifi_scan_link[NWAM_MAX_NAME_LEN];
	nwam_wlan_t nwamd_wifi_scan_last[NWAMD_MAX_NUM_WLANS];
	uint_t nwamd_wifi_scan_last_num;
	nwam_wlan_t nwamd_wifi_scan_curr[NWAMD_MAX_NUM_WLANS];
	uint_t nwamd_wifi_scan_curr_num;
	boolean_t nwamd_wifi_scan_changed;
	uint32_t nwamd_wifi_scan_last_time;
} nwamd_wifi_scan_t;

typedef struct nwamd_link {
	pthread_mutex_t nwamd_link_wifi_mutex;
	pthread_t nwamd_link_wifi_scan_thread;
	pthread_t nwamd_link_wifi_monitor_thread;
	char nwamd_link_wifi_essid[DLADM_STRSIZE];
	char nwamd_link_wifi_bssid[DLADM_STRSIZE];
	char nwamd_link_wifi_keyname[DLADM_STRSIZE];
	char nwamd_link_wifi_signal_strength[DLADM_STRSIZE];
	boolean_t nwamd_link_wifi_add_to_known_wlans;
	boolean_t nwamd_link_wifi_connected;
	uint32_t nwamd_link_wifi_security_mode;
	dladm_wlan_key_t *nwamd_link_wifi_key;
	nwamd_wifi_scan_t nwamd_link_wifi_scan;
	uint64_t nwamd_link_wifi_priority;
	boolean_t nwamd_link_wifi_autoconf;
	uint32_t nwamd_link_id;
	uint32_t nwamd_link_media;
	uint64_t nwamd_link_flags;
	dlpi_handle_t nwamd_link_dhp;
	pthread_t nwamd_link_dlpi_thread;
	uint64_t nwamd_link_activation_mode;
	uint64_t nwamd_link_priority_mode;
	uint64_t nwamd_link_priority_group;
	char *nwamd_link_mac_addr;
	size_t nwamd_link_mac_addr_len;
	uint64_t nwamd_link_mtu;
	char **nwamd_link_autopush;
	uint_t nwamd_link_num_autopush;
} nwamd_link_t;

struct nwamd_if_address {
	sa_family_t family;
	ipadm_addr_type_t ipaddr_atype;
	ipadm_addrobj_t ipaddr;
	boolean_t configured;
	struct sockaddr_storage conf_addr;	/* address configured for */
	struct sockaddr_storage conf_stateless_addr; /* this nwamd_if_address */
	struct nwamd_if_address *next;
};

typedef struct nwamd_if {
	boolean_t nwamd_if_dhcp_requested;
	boolean_t nwamd_if_dhcp_configured;
	boolean_t nwamd_if_stateful_requested;
	boolean_t nwamd_if_stateful_configured;
	boolean_t nwamd_if_stateless_requested;
	boolean_t nwamd_if_stateless_configured;
	struct nwamd_if_address *nwamd_if_list;
	struct sockaddr_in nwamd_if_ipv4_default_route;
	boolean_t nwamd_if_ipv4_default_route_set;
	struct sockaddr_in6 nwamd_if_ipv6_default_route;
	boolean_t nwamd_if_ipv6_default_route_set;
	boolean_t nwamd_if_ipv4;
	boolean_t nwamd_if_ipv6;
} nwamd_if_t;

typedef struct nwamd_ncu {
	nwam_ncu_type_t ncu_type;
	char *ncu_name;
	char ncu_parent[NWAM_MAX_NAME_LEN];
	boolean_t ncu_enabled; /* whether NCU has been enabled or not */
	union {
		nwamd_link_t u_link;
		nwamd_if_t u_if;
	} ncu_node;
} nwamd_ncu_t;

#define	ncu_link	ncu_node.u_link
#define	ncu_if		ncu_node.u_if

#define	LOOPBACK_IF				"lo0"

struct nwamd_dhcp_thread_arg {
	char *name;
	dhcp_ipc_type_t type;
	ipadm_addrobj_t ipaddr;
	volatile uint32_t *guard;
};

#define	WIRELESS_SCAN_INTERVAL_DEFAULT		120
#define	WIRELESS_SCAN_INTERVAL_MIN		30
#define	WIRELESS_SCAN_REQUESTED_INTERVAL_MIN	10
#define	WIRELESS_MONITOR_SIGNAL_INTERVAL	10
#define	WIRELESS_RETRY_INTERVAL			30
#define	WIRELESS_SCAN_LEVEL_DEFAULT		DLADM_WLAN_STRENGTH_WEAK
#define	NWAMD_DHCP_RETRIES			5
#define	NWAMD_DHCP_RETRY_WAIT_TIME		10
#define	NWAMD_READONLY_RETRY_INTERVAL		5

/*
 * This dladm and ipadm handles are opened before interfaces are initialized
 * and closed only when nwamd shuts down.
 */
extern dladm_handle_t dld_handle;
extern ipadm_handle_t ipadm_handle;

extern nwamd_object_t nwamd_ncu_object_find(nwam_ncu_type_t, const char *);
extern void nwamd_log_ncus(void);
extern void nwamd_ncu_free(nwamd_ncu_t *);

/* WLAN functions */
extern void nwamd_set_selected_connected(nwamd_ncu_t *, boolean_t, boolean_t);
extern nwam_error_t nwamd_wlan_select(const char *, const char *, const char *,
    uint32_t, boolean_t);
extern nwam_error_t nwamd_wlan_set_key(const char *, const char *, const char *,
    uint32_t, uint_t, char *);
extern nwam_error_t nwamd_wlan_scan(const char *);
extern void nwamd_wlan_connect(const char *);
extern boolean_t nwamd_wlan_connected(nwamd_object_t);
extern void nwamd_wlan_monitor_signal(const char *);
extern void nwamd_ncu_create_periodic_scan_event(nwamd_object_t);
extern dladm_wlan_key_t *nwamd_wlan_get_key_named(const char *, uint32_t);
extern void nwamd_set_key_name(const char *, const char *, char *, size_t);

/* Link functions */
extern link_state_t nwamd_get_link_state(const char *);
extern const char *nwamd_sockaddr_to_str(const struct sockaddr *, char *,
    size_t);
extern void nwamd_propogate_link_up_down_to_ip(const char *, boolean_t);
extern void nwamd_set_unset_link_properties(nwamd_ncu_t *, boolean_t);
/* DLPI event hooking */
extern void nwamd_dlpi_add_link(nwamd_object_t);
extern void nwamd_dlpi_delete_link(nwamd_object_t);

/* IP functions */
extern boolean_t nwamd_static_addresses_configured(nwamd_ncu_t *, sa_family_t);
extern void nwamd_plumb_interface(nwamd_ncu_t *, sa_family_t);
extern void nwamd_unplumb_interface(nwamd_ncu_t *, sa_family_t);
extern boolean_t nwamd_dhcp_managing(int, nwamd_ncu_t *);
extern void nwamd_configure_interface_addresses(nwamd_ncu_t *);
extern char *nwamd_get_dhcpinfo_data(const char *, char *);
extern void nwamd_dhcp_release(const char *);
extern void nwamd_add_default_routes(nwamd_ncu_t *);
extern void nwamd_add_route(struct sockaddr *, struct sockaddr *,
    struct sockaddr *, const char *);

/* NCU value set/get functions */
extern nwam_error_t nwamd_set_ncu_uint(nwam_ncu_handle_t, uint64_t *, uint_t,
    const char *);
extern nwam_error_t nwamd_set_ncu_string(nwam_ncu_handle_t, char **, uint_t,
    const char *);
extern nwam_error_t nwamd_get_ncu_uint(nwam_ncu_handle_t, nwam_value_t *,
    uint64_t **, uint_t *, const char *);
extern nwam_error_t nwamd_get_ncu_string(nwam_ncu_handle_t, nwam_value_t *,
    char ***, uint_t *, const char *);
extern nwam_error_t nwamd_get_ncu_boolean(nwam_ncu_handle_t, nwam_value_t *,
    boolean_t **, uint_t *, const char *);

extern void nwamd_walk_physical_configuration(void);

#endif /* _NCU_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.
 */

#include <arpa/inet.h>
#include <assert.h>
#include <dhcpagent_ipc.h>
#include <dhcp_inittab.h>
#include <dhcp_symbol.h>
#include <dhcpagent_util.h>
#include <errno.h>
#include <execinfo.h>
#include <libnwam.h>
#include <stdlib.h>
#include <strings.h>
#include <ucontext.h>
#include <unistd.h>
#include <libscf.h>

#include "conditions.h"
#include "events.h"
#include "ncp.h"
#include "ncu.h"
#include "objects.h"
#include "util.h"

/*
 * ncu_ip.c - contains routines that are IP interface-specific for NCUs.
 */

#define	STATELESS_RUNNING	(IFF_RUNNING | IFF_UP | IFF_ADDRCONF)
#define	DHCP_RUNNING		(IFF_RUNNING | IFF_UP | IFF_DHCPRUNNING)

static void nwamd_dhcp(const char *, ipadm_addrobj_t, dhcp_ipc_type_t);
static void nwamd_down_interface(const char *, ipadm_addr_type_t, const char *);
static boolean_t stateless_running(const nwamd_ncu_t *);

/*
 * Given a sockaddr representation of an IPv4 or IPv6 address returns the
 * string representation. Note that 'sockaddr' should point at the correct
 * sockaddr structure for the address family (sockaddr_in for AF_INET or
 * sockaddr_in6 for AF_INET6) or alternatively at a sockaddr_storage
 * structure.
 */
static const char *
nwamd_sockaddr2str(const struct sockaddr *addr, char *str, size_t len)
{
	struct sockaddr_in *sin;
	struct sockaddr_in6 *sin6;
	const char *straddr;

	if (addr == NULL)
		return (NULL);

	if (addr->sa_family == AF_INET) {
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		sin = (struct sockaddr_in *)addr;
		straddr = inet_ntop(AF_INET, (void *)&sin->sin_addr, str, len);
	} else if (addr->sa_family == AF_INET6) {
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		sin6 = (struct sockaddr_in6 *)addr;
		straddr = inet_ntop(AF_INET6, (void *)&sin6->sin6_addr, str,
		    len);
	} else {
		errno = EINVAL;
		return (NULL);
	}
	return (straddr != NULL ? str : NULL);
}

void
nwamd_propogate_link_up_down_to_ip(const char *linkname, boolean_t up)
{
	nwamd_object_t ip_ncu = nwamd_ncu_object_find(NWAM_NCU_TYPE_INTERFACE,
	    linkname);
	nwamd_ncu_t *ncu;

	if (ip_ncu == NULL) {
		nlog(LOG_DEBUG, "nwamd_propogate_link_up_down_to_ip: no IP NCU "
		    "for link %s, cannot propogate %s event", linkname,
		    up ? "up" : "down");
		return;
	}
	ncu = ip_ncu->nwamd_object_data;

	if (ncu->ncu_enabled) {
		if (ip_ncu->nwamd_object_aux_state ==
		    NWAM_AUX_STATE_UNINITIALIZED) {
			nlog(LOG_DEBUG,
			    "nwamd_propogate_link_up_down_to_ip: will not "
			    "propogate link %s event as IP NCU %s is being "
			    "removed", up ? "up" : "down", linkname);
		} else {
			nlog(LOG_DEBUG,
			    "nwamd_propogate_link_up_down_to_ip: propogating "
			    "link %s event to interface %s",
			    up ? "up" : "down", linkname);
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    ip_ncu->nwamd_object_name,
			    up ?
			    NWAM_STATE_OFFLINE_TO_ONLINE :
			    NWAM_STATE_ONLINE_TO_OFFLINE,
			    up ? NWAM_AUX_STATE_INITIALIZED :
			    NWAM_AUX_STATE_CONDITIONS_NOT_MET);
		}
	} else {
		nlog(LOG_DEBUG,
		    "nwamd_propogate_link_up_down_to_ip: not propogating "
		    "link %s event to interface %s, IP NCU is disabled",
		    up ? "up" : "down", linkname);
	}
	nwamd_object_release(ip_ncu);
}

/*
 * Returns the value associated with the given symbol for the given
 * interface.  The interface may be NULL, in which case the primary
 * interface is used.
 * This function substitutes the need to call dhcpinfo(1), thus it is
 * very similar to the implementation of dhcpinfo(1).
 * When multiple values need to be returned (e.g., nameservers), they
 * are separated by a space ' '.
 */
char *
nwamd_get_dhcpinfo_data(const char *sym_name, char *ifname)
{
	dhcp_symbol_t *entry;
	dhcp_optnum_t optnum;
	dhcp_ipc_request_t *request = NULL;
	dhcp_ipc_reply_t *reply;
	DHCP_OPT *opt;
	size_t opt_len;
	char *value; /* return value */
	int err;
	char errmsg[LINE_MAX];

	/* if interface is not given, change it to empty string */
	if (ifname == NULL)
		ifname = "";

	/* find code and category in dhcp_inittab(5) */
	entry = inittab_getbyname(ITAB_CAT_SITE | ITAB_CAT_STANDARD |
	    ITAB_CAT_VENDOR | ITAB_CAT_FIELD, ITAB_CONS_INFO, sym_name);

	if (entry == NULL) {
		(void) snprintf(errmsg, LINE_MAX, "unknown identifier: %s",
		    sym_name);
		goto fail;
	}

	/* allocate request */
	optnum.code = entry->ds_code;
	optnum.category = entry->ds_category;
	optnum.size = entry->ds_max * inittab_type_to_size(entry);
	request = dhcp_ipc_alloc_request(DHCP_GET_TAG, ifname, &optnum,
	    sizeof (dhcp_optnum_t), DHCP_TYPE_OPTNUM);
	if (request == NULL) {
		(void) snprintf(errmsg, LINE_MAX, "failed dhcp alloc request");
		goto fail;
	}

	/* make the request */
	err = dhcp_ipc_make_request(request, &reply, DHCP_IPC_WAIT_DEFAULT);
	if (err != 0 || reply->return_code != 0) {
		(void) snprintf(errmsg, LINE_MAX, "%s",
		    dhcp_ipc_strerror(err == 0 ? reply->return_code : err));
	}

	/* get data from the reply */
	opt = dhcp_ipc_get_data(reply, &opt_len, NULL);
	if (opt_len == 0) {
		(void) snprintf(errmsg, LINE_MAX, "invalid data");
		goto fail;
	}

	/* check protocol error */
	if (opt_len < 2 || (opt_len -2 != opt->len)) {
		(void) snprintf(errmsg, LINE_MAX, "data length mismatch");
		goto fail;
	}
	opt_len -= 2;

	/* decode the data into ascii */
	value = inittab_decode(entry, opt->value, opt_len, B_TRUE);
	if (value == NULL) {
		(void) snprintf(errmsg, LINE_MAX, "cannot decode reply");
		goto fail;
	}

	free(request);
	free(reply);
	return (value);

fail:
	nlog(LOG_DEBUG, "get_dhcpinfo_data() failed: %s", errmsg);
	free(request);
	free(reply);
	return (NULL);
}

void
nwamd_add_default_routes(nwamd_ncu_t *ncu)
{
	nwamd_if_t *nif = &ncu->ncu_if;
	char str[INET6_ADDRSTRLEN];

	if (nif->nwamd_if_ipv4 && nif->nwamd_if_ipv4_default_route_set) {
		struct sockaddr_in v4dest, v4mask;

		v4dest.sin_addr.s_addr = htonl(INADDR_ANY);
		v4dest.sin_family = AF_INET;

		v4mask.sin_addr.s_addr = 0;
		v4mask.sin_family = AF_INET;

		nlog(LOG_DEBUG, "nwamd_add_default_routes: adding default "
		    "route %s", nwamd_sockaddr2str((struct sockaddr *)
		    &nif->nwamd_if_ipv4_default_route, str,
		    sizeof (str)));
		nwamd_add_route((struct sockaddr *)&v4dest,
		    (struct sockaddr *)&v4mask,
		    (struct sockaddr *)&nif->nwamd_if_ipv4_default_route,
		    ncu->ncu_name);
	}

	if (nif->nwamd_if_ipv6 && nif->nwamd_if_ipv6_default_route_set) {
		struct sockaddr_in6 v6dest, v6mask;

		(void) bzero(&v6dest, sizeof (struct sockaddr_in6));
		v6dest.sin6_family = AF_INET6;

		(void) bzero(&v6mask, sizeof (struct sockaddr_in6));
		v6mask.sin6_family = AF_INET6;

		nlog(LOG_DEBUG, "nwamd_add_default_routes: adding default "
		    "route %s", nwamd_sockaddr2str((struct sockaddr *)
		    &nif->nwamd_if_ipv6_default_route, str,
		    sizeof (str)));
		nwamd_add_route((struct sockaddr *)&v6dest,
		    (struct sockaddr *)&v6mask,
		    (struct sockaddr *)&nif->nwamd_if_ipv6_default_route,
		    ncu->ncu_name);
	}
}

/*
 * Returns the nwamd_if_address structure for the given static address,
 * NULL if not found.
 */
static struct nwamd_if_address *
find_static_address(const struct sockaddr_storage *addr, const nwamd_ncu_t *ncu)
{
	struct nwamd_if_address *nifap, *nifa = ncu->ncu_if.nwamd_if_list;
	struct sockaddr_storage saddr;
	char str[INET6_ADDRSTRLEN];

	nlog(LOG_DEBUG, "find_static_address: %s",
	    nwamd_sockaddr2str((struct sockaddr *)addr, str, sizeof (str)));
	for (nifap = nifa; nifap != NULL; nifap = nifap->next) {
		if (nifap->ipaddr_atype != IPADM_ADDR_STATIC ||
		    ipadm_get_addr(nifap->ipaddr, &saddr) != IPADM_SUCCESS)
			continue;

		if (sockaddrcmp(addr, &saddr))
			return (nifap);
	}
	return (NULL);
}

/*
 * Returns the nwamd_if_address structure representing the non-static address
 * in the NCU.  For IPv6, both stateless and stateful (DHCPv6) share the same
 * nwamd_if_address.  Will only return the nwamd_if_address if the relevant
 * address is configured (v4 DHCP, v6 either stateless or stateless) for the
 * NCU.  Returns NULL if the structure is not found.
 */
static struct nwamd_if_address *
find_nonstatic_address(const nwamd_ncu_t *ncu, sa_family_t family)
{
	struct nwamd_if_address *nifap, *nifa = ncu->ncu_if.nwamd_if_list;
	const nwamd_if_t *u_if = &ncu->ncu_if;

	nlog(LOG_DEBUG, "find_nonstatic_address for %s %s",
	    (family == AF_INET ? "IPv4" : "IPv6"),  ncu->ncu_name);
	for (nifap = nifa; nifap != NULL; nifap = nifap->next) {
		if (nifap->ipaddr_atype == IPADM_ADDR_STATIC)
			continue;

		if (family == AF_INET) {
			if (nifap->ipaddr_atype == IPADM_ADDR_DHCP &&
			    u_if->nwamd_if_dhcp_requested)
				return (nifap);
		} else if (family == AF_INET6) {
			if (nifap->ipaddr_atype == IPADM_ADDR_IPV6_ADDRCONF &&
			    (u_if->nwamd_if_stateful_requested ||
			    u_if->nwamd_if_stateless_requested))
				return (nifap);
		}
	}
	return (NULL);
}

/*
 * Returns the nwamd_if_address structure that configured the given address,
 * NULL if not found.
 */
static struct nwamd_if_address *
find_configured_address(const struct sockaddr_storage *addr,
    const nwamd_ncu_t *ncu)
{
	struct nwamd_if_address *nifap, *nifa = ncu->ncu_if.nwamd_if_list;
	char str[INET6_ADDRSTRLEN];

	nlog(LOG_DEBUG, "find_configured_address: %s",
	    nwamd_sockaddr2str((struct sockaddr *)addr, str, sizeof (str)));
	for (nifap = nifa; nifap != NULL; nifap = nifap->next) {
		if (sockaddrcmp(addr, &nifap->conf_addr) ||
		    sockaddrcmp(addr, &nifap->conf_stateless_addr))
			return (nifap);
	}
	return (NULL);
}

/*
 * Are one or more static addresses configured?
 */
boolean_t
nwamd_static_addresses_configured(nwamd_ncu_t *ncu, sa_family_t family)
{
	struct nwamd_if_address *n;

	for (n = ncu->ncu_if.nwamd_if_list; n != NULL; n = n->next) {
		if (n->ipaddr_atype != IPADM_ADDR_STATIC)
			continue;
		if ((family == AF_UNSPEC || family == n->family) &&
		    n->configured)
			return (B_TRUE);
	}
	nlog(LOG_DEBUG, "no static addresses configured for %s", ncu->ncu_name);
	return (B_FALSE);
}

/*
 * Is DHCP probably managing an address on this index.  We decide that it is
 * probably managing an address if there is an interface with IFF_DHCP set
 * that isn't in our set of static addresses.  Note that IFF_DHCP gets set
 * on static addresses when we do a dhcp inform and if that list has changed
 * recently then the result of this function could be erronous.
 */
boolean_t
nwamd_dhcp_managing(int protocol, nwamd_ncu_t *ncu)
{
	struct sockaddr_storage addr;
	uint64_t flags;
	boolean_t rv = B_FALSE;
	ipadm_addr_info_t *addrinfo, *a;
	ipadm_status_t ipstatus;

	if ((ipstatus = ipadm_addr_info(ipadm_handle, ncu->ncu_name, &addrinfo,
	    0, 0)) != IPADM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_dhcp_managing: "
		    "ipadm_addr_info failed for %s: %s",
		    ncu->ncu_name, ipadm_status2str(ipstatus));
		return (B_FALSE);
	}

	for (a = addrinfo; a != NULL; a = IA_NEXT(a)) {
		/*
		 * WARNING: This memcpy() assumes knowledge of the
		 * implementation of getifaddrs() and that it always
		 * uses sockaddr_storage as the backing store for
		 * address information, thus making it possible to
		 * copy the entire structure rather than do it on
		 * the size of the sockaddr according to family.
		 * This assumption is made elsewhere in this file.
		 */
		(void) memcpy(&addr, a->ia_ifa.ifa_addr, sizeof (addr));

		/* is this address an expected static one? */
		if (find_static_address(&addr, ncu) != NULL)
			continue;

		/*
		 * For IPv4, DHCPRUNNING flag is set when dhcpagent is in
		 * the process of getting an address, but doesn't have one
		 * yet (interface has 0.0.0.0).  For IPv6, DHCPRUNNING flag
		 * is set on the link-local address if trying to get a
		 * stateful address.  In both cases, consider the interface
		 * as not being managed by DHCP and skip checking of flags.
		 */
		if ((protocol == AF_INET &&
		    ((struct sockaddr_in *)&addr)->sin_addr.s_addr ==
		    INADDR_ANY) ||
		    (protocol == AF_INET6 &&
		    IN6_IS_ADDR_LINKLOCAL(
		    &((struct sockaddr_in6 *)&addr)->sin6_addr))) {
			continue;
		}

		flags = a->ia_ifa.ifa_flags;
		if (flags & IFF_DHCPRUNNING) {
			/*
			 * If we get here we have an address that has the
			 * DHCP flag set and isn't an expected static address.
			 */
			rv = B_TRUE;
			break;
		}
	}

	ipadm_free_addr_info(addrinfo);
	return (rv);
}

/*
 * Return B_TRUE if IPv4 is requested in the given NCU.
 */
static boolean_t
nwamd_v4_requested(nwamd_ncu_t *ncu)
{
	boolean_t anyv4_requested;
	nwamd_if_t *u_if;

	anyv4_requested = B_FALSE;
	u_if = &ncu->ncu_if;
	if (u_if->nwamd_if_dhcp_requested) {
		anyv4_requested = B_TRUE;
	} else {
		struct nwamd_if_address *n;

		for (n = u_if->nwamd_if_list; n != NULL; n = n->next) {
			if (n->family == AF_INET &&
			    n->ipaddr_atype == IPADM_ADDR_STATIC)
				break;
		}
		if (n != NULL)
			anyv4_requested = B_TRUE;
	}

	return (anyv4_requested);
}

/*
 * Returns B_TRUE if IPv6 is requested in the given NCU.
 */
static boolean_t
nwamd_v6_requested(nwamd_ncu_t *ncu)
{
	boolean_t anyv6_requested;
	nwamd_if_t *u_if;

	anyv6_requested = B_FALSE;
	u_if = &ncu->ncu_if;
	if (u_if->nwamd_if_stateful_requested ||
	    u_if->nwamd_if_stateless_requested) {
		anyv6_requested = B_TRUE;
	} else {
		struct nwamd_if_address *n;

		for (n = u_if->nwamd_if_list; n != NULL; n = n->next) {
			if (n->family == AF_INET6 &&
			    n->ipaddr_atype == IPADM_ADDR_STATIC)
				break;
		}
		if (n != NULL)
			anyv6_requested = B_TRUE;
	}

	return (anyv6_requested);
}

/*
 * Bring up the ncu if we have the right combination of requested configuration
 * and actual configuration and up is true, or bring down the ncu if no
 * addresses are configured, and up is false.
 */
static void
interface_ncu_up_down(nwamd_ncu_t *ncu, boolean_t up)
{
	boolean_t ncu_online;
	char *name;

	assert(ncu->ncu_type == NWAM_NCU_TYPE_INTERFACE);

	/*
	 * If V4 with or without V6 is configured then one of its interfaces
	 * needs to be up for the ncu to come online.  If only V6 is requested
	 * then one of its interfaces needs to be up for the ncu to come online.
	 */
	ncu_online = B_FALSE;
	if (nwamd_v4_requested(ncu)) {
		if (nwamd_dhcp_managing(AF_INET, ncu) ||
		    nwamd_static_addresses_configured(ncu, AF_INET))
			ncu_online = B_TRUE;
	} else if (nwamd_v6_requested(ncu)) {
		if ((nwamd_dhcp_managing(AF_INET6, ncu) ||
		    stateless_running(ncu) ||
		    nwamd_static_addresses_configured(ncu, AF_INET6)))
			ncu_online = B_TRUE;
	}

	if (nwam_ncu_name_to_typed_name(ncu->ncu_name, ncu->ncu_type, &name) !=
	    NWAM_SUCCESS) {
		nlog(LOG_DEBUG, "interface_ncu_up_down: "
		    "nwam_ncu_name_to_typed_name failed");
		return;
	}
	if (ncu_online && up) {
		nlog(LOG_DEBUG, "interface_ncu_up_down: "
		    "bringing %s up", name);
		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU, name,
		    NWAM_STATE_OFFLINE_TO_ONLINE, NWAM_AUX_STATE_UP);
	} else if (!ncu_online && !up) {
		nlog(LOG_DEBUG, "interface_ncu_up_down: "
		    "bringing %s down", name);
		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU, name,
		    NWAM_STATE_ONLINE_TO_OFFLINE,
		    NWAM_AUX_STATE_DOWN);
	}

	free(name);
}

static void
interface_ncu_up(nwamd_ncu_t *ncu)
{
	interface_ncu_up_down(ncu, B_TRUE);
}

static void
interface_ncu_down(nwamd_ncu_t *ncu)
{
	interface_ncu_up_down(ncu, B_FALSE);
}

static boolean_t
stateless_running(const nwamd_ncu_t *ncu)
{
	ipadm_addr_info_t *ainfo, *ainfop;
	ipadm_status_t ipstatus;
	boolean_t rv = B_FALSE;
	uint64_t flags;

	if ((ipstatus = ipadm_addr_info(ipadm_handle, ncu->ncu_name, &ainfo,
	    0, 0)) != IPADM_SUCCESS) {
		nlog(LOG_ERR, "stateless_running: "
		    "ipadm_addr_info failed for %s: %s",
		    ncu->ncu_name, ipadm_status2str(ipstatus));
		return (B_FALSE);
	}

	for (ainfop = ainfo; ainfop != NULL; ainfop = IA_NEXT(ainfop)) {
		if (ainfop->ia_ifa.ifa_addr->sa_family != AF_INET6)
			continue;
		flags = ainfop->ia_ifa.ifa_flags;
		if (flags & STATELESS_RUNNING) {
			rv = B_TRUE;
			break;
		}
	}
	ipadm_free_addr_info(ainfo);
	return (rv);
}

/*
 * Returns the addrinfo associated with the given address.  There is always
 * only one addrinfo for each address.
 */
static boolean_t
addrinfo_for_addr(const struct sockaddr_storage *caddr, const char *ifname,
    ipadm_addr_info_t **ainfo)
{
	ipadm_addr_info_t *addrinfo, *ainfop, *last = NULL;
	ipadm_status_t ipstatus;

	ipstatus = ipadm_addr_info(ipadm_handle, ifname, &addrinfo, 0, 0);
	if (ipstatus != IPADM_SUCCESS) {
		nlog(LOG_INFO, "addrinfo_for_addr: "
		    "ipadm_addr_info failed for %s: %s",
		    ifname, ipadm_status2str(ipstatus));
		return (B_FALSE);
	}

	*ainfo = NULL;
	for (ainfop = addrinfo; ainfop != NULL; ainfop = IA_NEXT(ainfop)) {
		struct sockaddr_storage addr;

		(void) memcpy(&addr, ainfop->ia_ifa.ifa_addr, sizeof (addr));
		/*
		 * If addresses match, rearrange pointers so that addrinfo
		 * does not contain a, and return a.
		 */
		if (sockaddrcmp(&addr, caddr)) {
			if (last != NULL)
				last->ia_ifa.ifa_next = ainfop->ia_ifa.ifa_next;
			else
				addrinfo = IA_NEXT(ainfop);

			ainfop->ia_ifa.ifa_next = NULL;
			*ainfo = ainfop;
			break;
		}
		last = ainfop;
	}
	ipadm_free_addr_info(addrinfo);
	return (*ainfo == NULL ? B_FALSE : B_TRUE);
}

/*
 * Returns B_TRUE if the addrinfo associated with the given ipaddr using its
 * aobjname is found.  An addrinfo list is created and returned in ainfo.
 * Stateless and stateful IPv6 addrinfo have the same aobjname, thus the need
 * to create a list of addrinfo.
 */
static boolean_t
addrinfo_for_ipaddr(ipadm_addrobj_t ipaddr, const char *ifname,
    ipadm_addr_info_t **ainfo)
{
	char aobjname[IPADM_AOBJSIZ];
	ipadm_addr_info_t *addrinfo, *ainfop;
	ipadm_addr_info_t *last = NULL;
	ipadm_status_t ipstatus;

	ipstatus = ipadm_get_aobjname(ipaddr, aobjname, sizeof (aobjname));
	if (ipstatus != IPADM_SUCCESS)
		return (B_FALSE);

	ipstatus = ipadm_addr_info(ipadm_handle, ifname, &addrinfo, 0, 0);
	if (ipstatus != IPADM_SUCCESS) {
		nlog(LOG_INFO, "addrinfo_for_ipaddr: "
		    "ipadm_addr_info failed for %s: %s",
		    ifname, ipadm_status2str(ipstatus));
		return (B_FALSE);
	}

	*ainfo = NULL;
	ainfop = addrinfo;
	while (ainfop != NULL) {
		/* If aobjnames match, rearrange pointers to create new list */
		if (strcmp(ainfop->ia_aobjname, aobjname) == 0) {
			ipadm_addr_info_t *match = ainfop;

			ainfop = IA_NEXT(ainfop); /* move iterator */
			if (last != NULL)
				last->ia_ifa.ifa_next = match->ia_ifa.ifa_next;
			else
				addrinfo = ainfop;
			if (*ainfo == NULL)
				match->ia_ifa.ifa_next = NULL;
			else
				match->ia_ifa.ifa_next = &(*ainfo)->ia_ifa;
			*ainfo = match;
		} else {
			last = ainfop;
			ainfop = IA_NEXT(ainfop);
		}
	}
	ipadm_free_addr_info(addrinfo);
	return (*ainfo == NULL ? B_FALSE : B_TRUE);
}

/*
 * Add the address provided in the nwamd_if_address.  If DHCP is required,
 * start DHCP.  If a static address is configured, create the address; then do
 * a DHCP_INFORM (in a separate thread) to get other networking configuration
 * parameters.  RTM_NEWADDRs - translated into IF_STATE events - will then
 * finish the job of bringing the NCU online.
 */
static boolean_t
add_ip_address(const char *ifname, const struct nwamd_if_address *nifa,
    boolean_t *do_inform)
{
	ipadm_status_t ipstatus;
	ipadm_addr_info_t *addrinfo = NULL;
	uint64_t flags;

	if (nifa->ipaddr_atype == IPADM_ADDR_DHCP) {
		/*
		 * To make getting a DHCP address asynchronous, call
		 * ipadm_create_addr() in a new thread.
		 */
		nlog(LOG_DEBUG, "add_ip_address: "
		    "adding IPv4 DHCP address on %s", ifname);
		nwamd_dhcp(ifname, nifa->ipaddr, DHCP_START);
	} else {
		nlog(LOG_DEBUG, "add_ip_address: adding %s address on %s",
		    (nifa->ipaddr_atype == IPADM_ADDR_STATIC ?
		    "STATIC" : "IPv6 ADDRCONF"), ifname);
		if ((ipstatus = ipadm_create_addr(ipadm_handle, nifa->ipaddr,
		    IPADM_OPT_ACTIVE | IPADM_OPT_UP)) != IPADM_SUCCESS) {
			nlog(LOG_ERR, "add_ip_address: "
			    "ipadm_create_addr failed on %s: %s",
			    ifname, ipadm_status2str(ipstatus));
			return (B_FALSE);
		}
		/*
		 * When creating a static address, ipadm_create_addr() returns
		 * SUCCESS even if duplicate address is detected.  Retrieve
		 * the addrinfo to get the flags.
		 */
		if (nifa->ipaddr_atype == IPADM_ADDR_STATIC) {
			/*
			 * Since we are configuring a static address, there
			 * will be just *ONE* addrinfo with the aobjname in
			 * nifa->ipaddr.
			 */
			if (!addrinfo_for_ipaddr(nifa->ipaddr, ifname,
			    &addrinfo)) {
				nlog(LOG_ERR, "add_ip_address: "
				    "could not find addrinfo on %s", ifname);
				return (B_FALSE);
			}

			flags = addrinfo->ia_ifa.ifa_flags;
			ipadm_free_addr_info(addrinfo);
			if (flags & IFF_DUPLICATE) {
				char *object_name;
				nwam_error_t err;

				nlog(LOG_INFO, "add_ip_address: "
				    "duplicate address detected on %s", ifname);
				if ((err = nwam_ncu_name_to_typed_name(ifname,
				    NWAM_NCU_TYPE_INTERFACE, &object_name))
				    == NWAM_SUCCESS) {
					nwamd_object_set_state(
					    NWAM_OBJECT_TYPE_NCU,
					    object_name, NWAM_STATE_MAINTENANCE,
					    NWAM_AUX_STATE_IF_DUPLICATE_ADDR);
					free(object_name);
				} else {
					nlog(LOG_ERR, "add_ip_address: "
					    "could not create state event "
					    "for %s: %s",
					    ifname, nwam_strerror(err));
				}
				return (B_FALSE);
			}
			/*
			 * Do DHCP_INFORM using async ipadm_refresh_addr().
			 * Only need to do this once per interface, and we
			 * do *not* need to do it if we are also getting a
			 * dhcp lease; so we only send the INFORM if the
			 * passed-in flag says to, and we clear the flag
			 * once we've initiated the INFORM transaction.
			 */
			if (*do_inform) {
				nwamd_dhcp(ifname, nifa->ipaddr, DHCP_INFORM);
				*do_inform = B_FALSE;
			}
		}
	}

	return (B_TRUE);
}

/*
 * Adds addresses for the given NCU.
 */
void
nwamd_configure_interface_addresses(nwamd_ncu_t *ncu)
{
	struct nwamd_if_address *nifap, *nifa = ncu->ncu_if.nwamd_if_list;
	boolean_t do_inform;

	/* only need an inform if we're not also getting a dhcp lease */
	do_inform = !ncu->ncu_if.nwamd_if_dhcp_requested;

	nlog(LOG_DEBUG, "nwamd_configure_interface_addresses(%s)",
	    ncu->ncu_name);

	for (nifap = nifa; nifap != NULL; nifap = nifap->next) {
		if (nifap->configured)
			continue;

		nifap->configured = add_ip_address(ncu->ncu_name, nifap,
		    &do_inform);
	}
}

/*
 * This event tells us that an interface address has appeared or disappeared,
 * or that the interface flags on an interface have changed.
 */
void
nwamd_ncu_handle_if_state_event(nwamd_event_t event)
{
	nwam_event_t evm;
	nwamd_object_t ncu_obj;
	nwamd_ncu_t *ncu;
	nwam_state_t state;
	nwam_aux_state_t aux_state;

	ncu_obj = nwamd_object_find(NWAM_OBJECT_TYPE_NCU,
	    event->event_object);
	if (ncu_obj == NULL) {
		nlog(LOG_INFO, "nwamd_ncu_handle_if_state_event: no object %s",
		    event->event_object);
		nwamd_event_do_not_send(event);
		return;
	}
	ncu = ncu_obj->nwamd_object_data;
	evm = event->event_msg;
	state = ncu_obj->nwamd_object_state;
	aux_state = ncu_obj->nwamd_object_aux_state;

	nlog(LOG_DEBUG, "nwamd_ncu_handle_if_state_event: "
	    "if %s, state (%s, %s)", event->event_object,
	    nwam_state_to_string(state), nwam_aux_state_to_string(aux_state));

	/* Ensure object is in correct state to handle IF state events */
	switch (state) {
	case NWAM_STATE_OFFLINE_TO_ONLINE:
		if (aux_state != NWAM_AUX_STATE_IF_WAITING_FOR_ADDR &&
		    aux_state != NWAM_AUX_STATE_IF_DHCP_TIMED_OUT) {
			nlog(LOG_DEBUG, "nwamd_ncu_handle_if_state_event: "
			    "if %s is in invalid aux state %s for IF_STATE "
			    "events", event->event_object,
			    nwam_aux_state_to_string(aux_state));
			nwamd_event_do_not_send(event);
			nwamd_object_release(ncu_obj);
			return;
		}
		break;
	case NWAM_STATE_ONLINE:
	/*
	 * We can get addresses from DHCP after we've taken the interface down.
	 * We deal with those below.
	 */
	case NWAM_STATE_ONLINE_TO_OFFLINE:
	case NWAM_STATE_OFFLINE:
		break;
	default:
		nlog(LOG_DEBUG, "nwamd_ncu_handle_if_state_event: "
		    "if %s is in invalid state %s for IF_STATE events",
		    event->event_object, nwam_state_to_string(state));
		nwamd_event_do_not_send(event);
		nwamd_object_release(ncu_obj);
		return;
	}

	if (evm->nwe_data.nwe_if_state.nwe_addr_valid) {
		struct nwam_event_if_state *if_state;
		char addrstr[INET6_ADDRSTRLEN];
		boolean_t static_addr = B_FALSE, addr_added;
		boolean_t v4dhcp_running, v6dhcp_running, stateless_running;
		ipadm_addr_info_t *ai = NULL, *addrinfo = NULL;
		boolean_t stateless_ai_found = B_FALSE;
		boolean_t stateful_ai_found = B_FALSE;
		struct nwamd_if_address *nifa = NULL;
		nwamd_if_t *u_if;
		struct sockaddr_storage *addr, ai_addr, *aip = NULL;
		ushort_t family;
		uint64_t flags = 0;

		if_state = &evm->nwe_data.nwe_if_state;
		u_if = &ncu->ncu_if;
		family = if_state->nwe_addr.ss_family;
		addr = &if_state->nwe_addr;
		addr_added = if_state->nwe_addr_added;

		v4dhcp_running = B_FALSE;
		v6dhcp_running = B_FALSE;
		stateless_running = B_FALSE;

		nlog(LOG_DEBUG,
		    "nwamd_ncu_handle_if_state_event: addr %s %s",
		    nwamd_sockaddr2str((struct sockaddr *)addr, addrstr,
		    sizeof (addrstr)), addr_added ? "added" : "removed");

		/*
		 * Need to get flags for this interface.  Get the addrinfo for
		 * the address that generated this IF_STATE event.
		 */
		if (addr_added) {
			/*
			 * Address was added.  Find the addrinfo for this
			 * address and the nwamd_if_address corresponding to
			 * this address.
			 */
			if (!addrinfo_for_addr(addr, ncu->ncu_name, &ai)) {
				nlog(LOG_ERR,
				    "nwamd_ncu_handle_if_state_event: "
				    "addrinfo doesn't exist for %s", addrstr);
				nwamd_event_do_not_send(event);
				goto valid_done;
			}
			addrinfo = ai;
			flags = addrinfo->ia_ifa.ifa_flags;
			(void) memcpy(&ai_addr, addrinfo->ia_ifa.ifa_addr,
			    sizeof (ai_addr));
			aip = &ai_addr;

			if (addrinfo->ia_atype == IPADM_ADDR_IPV6_ADDRCONF ||
			    addrinfo->ia_atype == IPADM_ADDR_DHCP)
				nifa = find_nonstatic_address(ncu, family);
			else if (addrinfo->ia_atype == IPADM_ADDR_STATIC)
				nifa = find_static_address(addr, ncu);

			/*
			 * If nwamd_if_address is not found, then this address
			 * isn't one that nwamd created.  Remove it.
			 */
			if (nifa == NULL) {
				nlog(LOG_ERR,
				    "nwamd_ncu_handle_if_state_event: "
				    "address %s not managed by nwam added, "
				    "removing it", addrstr);
				nwamd_down_interface(addrinfo->ia_aobjname,
				    addrinfo->ia_atype, ncu->ncu_name);
				nwamd_event_do_not_send(event);
				goto valid_done;
			}

			/* check flags to determine how intf is configured */
			stateless_running = (family == AF_INET6) &&
			    ((flags & STATELESS_RUNNING) == STATELESS_RUNNING);
			v4dhcp_running = (family == AF_INET) &&
			    ((flags & DHCP_RUNNING) == DHCP_RUNNING);
			v6dhcp_running = (family == AF_INET6) &&
			    ((flags & DHCP_RUNNING) == DHCP_RUNNING);
			static_addr = (addrinfo->ia_atype == IPADM_ADDR_STATIC);

			/* copy the configured address into nwamd_if_address */
			if (stateless_running) {
				(void) memcpy(&nifa->conf_stateless_addr,
				    addrinfo->ia_ifa.ifa_addr,
				    sizeof (struct sockaddr_storage));
			} else {
				(void) memcpy(&nifa->conf_addr,
				    addrinfo->ia_ifa.ifa_addr,
				    sizeof (struct sockaddr_storage));
			}

		} else {
			/*
			 * Address was removed.  Find the nwamd_if_address
			 * that configured this address.
			 */
			nifa = find_configured_address(addr, ncu);
			if (nifa == NULL) {
				nlog(LOG_ERR,
				    "nwamd_ncu_handle_if_state_event: "
				    "address %s not managed by nwam removed, "
				    "nothing to do", addrstr);
				nwamd_event_do_not_send(event);
				goto valid_done;
			}

			if (addrinfo_for_ipaddr(nifa->ipaddr, ncu->ncu_name,
			    &ai)) {
				ipadm_addr_info_t *a;
				for (a = ai; a != NULL; a = IA_NEXT(a)) {
					struct sockaddr_storage stor;

					(void) memcpy(&stor, a->ia_ifa.ifa_addr,
					    sizeof (stor));
					/*
					 * Since multiple addrinfo can have
					 * the same ipaddr, find the one for
					 * the address that generated this
					 * state event.
					 */
					if (sockaddrcmp(addr, &stor)) {
						flags = a->ia_ifa.ifa_flags;
						(void) memcpy(&ai_addr,
						    a->ia_ifa.ifa_addr,
						    sizeof (ai_addr));
						aip = &ai_addr;
						addrinfo = a;
					}
					/*
					 * Stateful and stateless IPv6
					 * addrinfo have the same aobjname.
					 * Use the flags to determine which
					 * address is present in the system.
					 */
					if (family == AF_INET6) {
						stateless_ai_found =
						    (a->ia_ifa.ifa_flags &
						    STATELESS_RUNNING);
						stateful_ai_found =
						    (a->ia_ifa.ifa_flags &
						    DHCP_RUNNING);
					}
				}
			}
		}

		/* Set the flags in the event for listeners */
		evm->nwe_data.nwe_if_state.nwe_flags = flags;

		if (family == AF_INET && !addr_added) {
			/*
			 * Check for failure due to CR 6745448: if we get a
			 * report that an address has been deleted, then check
			 * for interface up, datalink down, and actual address
			 * non-zero.  If that combination is seen, then this is
			 * a DHCP cached lease, and we need to remove it from
			 * the system, or it'll louse up the kernel routes
			 * (which aren't smart enough to avoid dead
			 * interfaces).
			 */
			if (((struct sockaddr_in *)addr)->sin_addr.s_addr
			    == INADDR_ANY && aip != 0) {
				struct sockaddr_in *a;
				char astr[INET6_ADDRSTRLEN];
				a = (struct sockaddr_in *)aip;

				if ((flags & IFF_UP) &&
				    !(flags & IFF_RUNNING) &&
				    a->sin_addr.s_addr != INADDR_ANY) {
					nlog(LOG_DEBUG,
					    "nwamd_ncu_handle_if_state_event: "
					    "bug workaround: clear out addr "
					    "%s on %s", nwamd_sockaddr2str
					    ((struct sockaddr *)a, astr,
					    sizeof (astr)),
					    ncu->ncu_name);
					nwamd_down_interface(
					    addrinfo->ia_aobjname,
					    IPADM_ADDR_DHCP, ncu->ncu_name);
				}
				goto valid_done;
			}
		}

		/*
		 * If we received an RTM_NEWADDR and the IFF_UP flags has not
		 * been set, ignore this IF_STATE event.  Once the IFF_UP flag
		 * is set, we'll get another RTM_NEWADDR message.
		 */
		if (addr_added & !(flags & IFF_UP)) {
			nlog(LOG_INFO, "nwamd_ncu_handle_if_state_event: "
			    "address %s added on %s without IFF_UP flag (%x), "
			    "ignoring IF_STATE event",
			    addrstr, ncu->ncu_name, flags);
			nwamd_event_do_not_send(event);
			goto valid_done;
		}

		/*
		 * Has the address really been removed?  Sometimes spurious
		 * RTM_DELADDRs are generated, so we need to ensure that
		 * the address is really gone.  If IFF_DUPLICATE is set,
		 * we're getting the RTM_DELADDR due to DAD, so don't test
		 * in that case.
		 */
		if (!addr_added && !(flags & IFF_DUPLICATE)) {
			if (aip != 0 && sockaddrcmp(addr, aip)) {
				nlog(LOG_INFO,
				    "nwamd_ncu_handle_if_state_event: "
				    "address %s is not really gone from %s, "
				    "ignoring IF_STATE event",
				    addrstr, ncu->ncu_name);
				nwamd_event_do_not_send(event);
				goto valid_done;
			}
		}

		if (addr_added) {
			/*
			 * Address has been added.
			 *
			 * We need to make sure that we really want to keep
			 * this address.  There is a race where we requested an
			 * address but by the time we got here we don't really
			 * want it and need to remove it.
			 *
			 * Once we decide we want the address adjust the ncu
			 * state accordingly.  For example if this address is
			 * enough move online.
			 */
			if (u_if->nwamd_if_dhcp_requested && v4dhcp_running) {
				u_if->nwamd_if_dhcp_configured = B_TRUE;
			} else if (u_if->nwamd_if_stateful_requested &&
			    v6dhcp_running) {
				u_if->nwamd_if_stateful_configured = B_TRUE;
			} else if (u_if->nwamd_if_stateless_requested &&
			    stateless_running) {
				u_if->nwamd_if_stateless_configured = B_TRUE;
			} else if (!static_addr) {
				/*
				 * This is something we didn't expect.  Remove
				 * the address.
				 */
				nwamd_down_interface(addrinfo->ia_aobjname,
				    addrinfo->ia_atype, ncu->ncu_name);
				nifa->configured = B_FALSE;
				goto valid_done;
			}

			/*
			 * The address looks valid so mark configured and
			 * move online if we either have a v4 address if
			 * v4 is configured or a v6 address if only v6 is
			 * configured.
			 */
			nifa->configured = B_TRUE;
			if (state != NWAM_STATE_ONLINE)
				interface_ncu_up(ncu);

			/*
			 * Refresh network/location since we may also have other
			 * DHCP information.  We might have to restore it first
			 * in case it is in maintenance.
			 */
			nlog(LOG_DEBUG, "nwamd_handle_if_state_event: "
			    "refreshing %s as we may have other "
			    "DHCP information", NET_LOC_FMRI);
			(void) smf_restore_instance(NET_LOC_FMRI);
			if (smf_refresh_instance(NET_LOC_FMRI) != 0) {
				nlog(LOG_ERR,
				    "nwamd_ncu_handle_if_state_"
				    "event: refresh of %s "
				    "failed", NET_LOC_FMRI);
			}

		} else if (state == NWAM_STATE_ONLINE ||
		    state == NWAM_STATE_OFFLINE_TO_ONLINE) {
			/*
			 * Address has been removed.  Only pay attention to
			 * disappearing addresses if we are online or coming
			 * online.
			 *
			 * Undo whatever configuration is necessary.  Note
			 * that this may or may not cause the NCU to go down.
			 * We can get RTM_DELADDRs for duplicate addresses
			 * so deal with this seperately.
			 */
			nifa->configured = B_FALSE;

			if (!static_addr && family == AF_INET) {
				u_if->nwamd_if_dhcp_configured = B_FALSE;
			} else if (!static_addr && family == AF_INET6) {
				/*
				 * The address is already gone.  When looking
				 * for the addrinfo (using aobjname in
				 * ipaddr), we found addrinfo for either one
				 * or both stateless and stateful.  Using the
				 * flags we determined whether each was
				 * configured or not.  Update the flags here
				 * accordingly.
				 */
				u_if->nwamd_if_stateful_configured =
				    stateless_ai_found;
				u_if->nwamd_if_stateless_configured =
				    stateful_ai_found;
			}

			if (flags & IFF_DUPLICATE) {
				nlog(LOG_INFO,
				    "nwamd_ncu_handle_if_state_event: "
				    "duplicate address detected on %s",
				    ncu->ncu_name);
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    event->event_object,
				    NWAM_STATE_MAINTENANCE,
				    NWAM_AUX_STATE_IF_DUPLICATE_ADDR);
			} else {
				interface_ncu_down(ncu);
			}
		}
valid_done:
		ipadm_free_addr_info(ai);
	}
	nwamd_object_release(ncu_obj);
}

void
nwamd_ncu_handle_if_action_event(nwamd_event_t event)
{
	nwamd_object_t ncu_obj;

	nlog(LOG_DEBUG, "if action event %s",
	    event->event_object[0] == '\0' ? "n/a" : event->event_object);

	ncu_obj = nwamd_object_find(NWAM_OBJECT_TYPE_NCU, event->event_object);
	if (ncu_obj == NULL) {
		nlog(LOG_ERR, "nwamd_ncu_handle_if_action_event: no object");
		nwamd_event_do_not_send(event);
		return;
	}
	nwamd_object_release(ncu_obj);
}

/*
 * Remove the address in the given aobjname.  IPADM_OPT_RELEASE is specified
 * for a DHCP address and specifies that the DHCP lease should also be released.
 * ifname is only used for nlog().
 */
static void
nwamd_down_interface(const char *aobjname, ipadm_addr_type_t atype,
    const char *ifname)
{
	ipadm_status_t ipstatus;
	uint32_t rflags = (atype == IPADM_ADDR_DHCP ? IPADM_OPT_RELEASE : 0);

	nlog(LOG_DEBUG, "nwamd_down_interface: %s [aobjname = %s]",
	    ifname, aobjname);
	if ((ipstatus = ipadm_delete_addr(ipadm_handle, aobjname,
	    IPADM_OPT_ACTIVE | rflags)) != IPADM_SUCCESS) {
		nlog(LOG_ERR, "nwamd_down_interface: "
		    "ipadm_delete_addr failed on %s: %s",
		    ifname, ipadm_status2str(ipstatus));
	}
}

static void
unconfigure_addresses(nwamd_ncu_t *ncu, sa_family_t af)
{
	struct nwamd_if_address *nifap, *nifa = ncu->ncu_if.nwamd_if_list;

	for (nifap = nifa; nifap != NULL; nifap = nifap->next)
		if (af == AF_UNSPEC || nifap->family == af)
			nifap->configured = B_FALSE;
}

static void
dhcp_release(const char *ifname)
{
	ipadm_addr_info_t *ainfo, *ainfop;

	if (ipadm_addr_info(ipadm_handle, ifname, &ainfo, 0, 0)
	    != IPADM_SUCCESS)
		return;

	for (ainfop = ainfo; ainfop != NULL; ainfop = IA_NEXT(ainfop)) {
		if (ainfop->ia_atype == IPADM_ADDR_DHCP)
			nwamd_down_interface(ainfop->ia_aobjname,
			    ainfop->ia_atype, ifname);
	}
	ipadm_free_addr_info(ainfo);
}

static void
nwamd_plumb_unplumb_interface(nwamd_ncu_t *ncu, sa_family_t af, boolean_t plumb)
{
	char *ifname = ncu->ncu_name;
	nwamd_if_t *u_if = &ncu->ncu_if;
	ipadm_status_t ipstatus;

	nlog(LOG_DEBUG, "nwamd_plumb_unplumb_interface: %s %s %s",
	    (plumb ? "plumb" : "unplumb"), (af == AF_INET ? "IPv4" : "IPv6"),
	    ifname);

	if (plumb) {
		ipstatus = ipadm_create_if(ipadm_handle, ifname, af,
		    IPADM_OPT_ACTIVE);
	} else {
		/* release DHCP address, if any */
		if (af == AF_INET)
			dhcp_release(ifname);
		ipstatus = ipadm_delete_if(ipadm_handle, ifname, af,
		    IPADM_OPT_ACTIVE);
	}

	if (ipstatus != IPADM_SUCCESS) {
		if ((plumb && ipstatus != IPADM_IF_EXISTS) ||
		    (!plumb && ipstatus != IPADM_ENXIO)) {
			nlog(LOG_ERR, "nwamd_plumb_unplumb_interface: "
			    "%s %s failed for %s: %s",
			    (plumb ? "plumb" : "unplumb"),
			    (af == AF_INET ? "IPv4" : "IPv6"),
			    ifname, ipadm_status2str(ipstatus));
		}
	}

	/* Unset flags */
	if (!plumb) {
		unconfigure_addresses(ncu, af);
		switch (af) {
		case AF_INET:
			u_if->nwamd_if_dhcp_configured = B_FALSE;
			break;
		case AF_INET6:
			u_if->nwamd_if_stateful_configured = B_FALSE;
			u_if->nwamd_if_stateless_configured = B_FALSE;
			break;
		}
	}
}

void
nwamd_plumb_interface(nwamd_ncu_t *ncu, sa_family_t af)
{
	/*
	 * We get all posssible privs by calling nwamd_deescalate().  During
	 * startup opening /dev/dld (data link management) needs all privs
	 * because we don't have access to /etc/security/device_policy yet.
	 */
	nwamd_escalate();
	nwamd_plumb_unplumb_interface(ncu, af, B_TRUE);
	nwamd_deescalate();
}

void
nwamd_unplumb_interface(nwamd_ncu_t *ncu, sa_family_t af)
{
	nwamd_plumb_unplumb_interface(ncu, af, B_FALSE);
}

static void *
start_dhcp_thread(void *arg)
{
	struct nwamd_dhcp_thread_arg *thread_arg = arg;
	nwamd_object_t ncu_obj;
	dhcp_ipc_type_t type;
	char *name;
	ipadm_addrobj_t ipaddr;
	ipadm_status_t ipstatus;
	int retries = 0;

	name = thread_arg->name;
	type = thread_arg->type;
	ipaddr = thread_arg->ipaddr;

retry:
	/* Make sure the NCU is in appropriate state for DHCP command */
	ncu_obj = nwamd_ncu_object_find(NWAM_NCU_TYPE_INTERFACE, name);
	if (ncu_obj == NULL) {
		nlog(LOG_ERR, "start_dhcp: no IP object %s", name);
		return (NULL);
	}

	if (ncu_obj->nwamd_object_state != NWAM_STATE_OFFLINE_TO_ONLINE &&
	    ncu_obj->nwamd_object_state != NWAM_STATE_ONLINE) {
		nlog(LOG_INFO, "start_dhcp: IP NCU %s is in invalid state "
		    "for DHCP command", ncu_obj->nwamd_object_name);
		nwamd_object_release(ncu_obj);
		return (NULL);
	}
	nwamd_object_release(ncu_obj);

	switch (type) {
	case DHCP_INFORM:
	{
		char aobjname[IPADM_AOBJSIZ];

		if ((ipstatus = ipadm_get_aobjname(ipaddr, aobjname,
		    sizeof (aobjname))) != IPADM_SUCCESS) {
			nlog(LOG_ERR, "start_dhcp: "
			    "ipadm_get_aobjname failed for %s: %s",
			    name, ipadm_status2str(ipstatus));
			goto done;
		}
		ipstatus = ipadm_refresh_addr(ipadm_handle, aobjname,
		    IPADM_OPT_ACTIVE | IPADM_OPT_INFORM);
		break;
	}
	case DHCP_START:
		ipstatus = ipadm_create_addr(ipadm_handle, ipaddr,
		    IPADM_OPT_ACTIVE);
		break;
	default:
		nlog(LOG_ERR, "start_dhcp: invalid dhcp_ipc_type_t: %d", type);
		goto done;
	}

	if (ipstatus == IPADM_DHCP_IPC_TIMEOUT) {
		/*
		 * DHCP timed out: for DHCP_START requests, change state for
		 * this NCU and euqueue event to check NCU priority-groups;
		 * for DHCP_INFORM requests, nothing to do.
		 */
		if (type == DHCP_START) {
			char *object_name;

			nlog(LOG_INFO,
			    "start_dhcp: DHCP_START timed out for %s", name);

			if (nwam_ncu_name_to_typed_name(name,
			    NWAM_NCU_TYPE_INTERFACE, &object_name)
			    != NWAM_SUCCESS) {
				nlog(LOG_ERR, "start_dhcp: "
				    "nwam_ncu_name_to_typed_name failed for %s",
				    name);
				goto done;
			}
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    object_name, NWAM_STATE_OFFLINE_TO_ONLINE,
			    NWAM_AUX_STATE_IF_DHCP_TIMED_OUT);
			nwamd_create_ncu_check_event(0);
			free(object_name);
		} else {
			nlog(LOG_INFO,
			    "start_dhcp: DHCP_INFORM timed out for %s", name);
		}

	} else if ((ipstatus == IPADM_DHCP_IPC_ERROR ||
	    ipstatus == IPADM_IPC_ERROR) && retries++ < NWAMD_DHCP_RETRIES) {
		/*
		 * Retry DHCP request as we may have been unplumbing as part
		 * of the configuration phase.
		 */
		nlog(LOG_ERR, "start_dhcp: ipadm_%s_addr on %s returned: %s, "
		    "retrying in %d sec",
		    (type == DHCP_START ? "create" : "refresh"), name,
		    ipadm_status2str(ipstatus), NWAMD_DHCP_RETRY_WAIT_TIME);
		(void) sleep(NWAMD_DHCP_RETRY_WAIT_TIME);
		goto retry;

	} else if (ipstatus != IPADM_SUCCESS) {
		nlog(LOG_ERR, "start_dhcp: ipadm_%s_addr failed for %s: %s",
		    (type == DHCP_START ? "create" : "refresh"), name,
		    ipadm_status2str(ipstatus));
	}

done:
	free(name);
	free(arg);
	return (NULL);
}

static void
nwamd_dhcp(const char *ifname, ipadm_addrobj_t ipaddr, dhcp_ipc_type_t cmd)
{
	struct nwamd_dhcp_thread_arg *arg;
	pthread_attr_t attr;

	nlog(LOG_DEBUG, "nwamd_dhcp: starting DHCP %s thread for %s",
	    dhcp_ipc_type_to_string(cmd), ifname);

	arg = malloc(sizeof (*arg));
	if (arg == NULL) {
		nlog(LOG_ERR, "nwamd_dhcp: error allocating memory for "
		    "dhcp request");
		return;
	}

	arg->name = strdup(ifname);
	arg->type = cmd;
	arg->ipaddr = ipaddr;

	(void) pthread_attr_init(&attr);
	(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	if (pthread_create(NULL, &attr, start_dhcp_thread, arg) == -1) {
		nlog(LOG_ERR, "nwamd_dhcp: cannot start dhcp thread");
		free(arg->name);
		free(arg);
		(void) pthread_attr_destroy(&attr);
		return;
	}
	(void) pthread_attr_destroy(&attr);
}
/*
 * 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.
 */

#include <assert.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <execinfo.h>
#include <kstat.h>
#include <libdladm.h>
#include <libdllink.h>
#include <libdlstat.h>
#include <libdlwlan.h>
#include <libnwam.h>
#include <limits.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <libdlpi.h>
#include <ucontext.h>

#include "events.h"
#include "llp.h"
#include "objects.h"
#include "ncp.h"
#include "ncu.h"
#include "known_wlans.h"
#include "util.h"

/*
 * ncu_phys.c - contains routines that are physical-link specific.
 * Mostly WiFi code.
 */

/*
 * Get link state from kstats. Used to determine initial link state for
 * cases where drivers do not support DL_NOTE_LINK_UP/DOWN.  If link
 * state is LINK_STATE_UNKNOWN, we assume the link is up and the IP NCU
 * timeout will cause us to move on to other links.
 */
link_state_t
nwamd_get_link_state(const char *name)
{
	kstat_ctl_t *kcp;
	kstat_t *ksp;
	char module[DLPI_LINKNAME_MAX];
	uint_t instance;
	link_state_t link_state = LINK_STATE_UNKNOWN;

	if ((kcp = kstat_open()) == NULL)
		return (link_state);

	if (dlpi_parselink(name, module, &instance) != DLPI_SUCCESS)
		goto out;

	if ((ksp = kstat_lookup(kcp, module, instance, "mac")) == NULL) {
		/*
		 * The kstat query could fail if the underlying MAC
		 * driver was already detached.
		 */
		goto out;
	}

	if (kstat_read(kcp, ksp, NULL) == -1)
		goto out;

	(void) dladm_kstat_value(ksp, "link_state", KSTAT_DATA_UINT32,
	    &link_state);

out:
	(void) kstat_close(kcp);

	return (link_state);
}

/*
 * Set/unset link propeties.  At present, these are MAC address, link MTU and
 * autopush modules.  We set MAC address last as setting it may cause a chip
 * reset which can prevent other device property setting succeeding.
 */
void
nwamd_set_unset_link_properties(nwamd_ncu_t *ncu, boolean_t set)
{
	dlpi_handle_t dh = ncu->ncu_link.nwamd_link_dhp;
	char *addr = set ? ncu->ncu_link.nwamd_link_mac_addr : NULL;
	uint64_t mtu = set ? ncu->ncu_link.nwamd_link_mtu : 0;
	char **autopush = set ? ncu->ncu_link.nwamd_link_autopush : NULL;
	uint_t num_autopush = set ? ncu->ncu_link.nwamd_link_num_autopush : 0;
	uchar_t *hwaddr = NULL, curraddr[DLPI_PHYSADDR_MAX];
	size_t hwaddrlen = DLPI_PHYSADDR_MAX;
	int retval;
	dladm_status_t status;
	char mtustr[DLADM_PROP_VAL_MAX];
	char *cp;
	char errmsg[DLADM_STRSIZE];
	uint_t cnt = 1;

	/*
	 * Set MTU here - either default value (if mtu == 0 indicating it has
	 * not been set) or specified value.
	 */
	if (mtu == 0) {
		cp = mtustr;
		status = dladm_get_linkprop(dld_handle,
		    ncu->ncu_link.nwamd_link_id, DLADM_PROP_VAL_DEFAULT, "mtu",
		    &cp, &cnt);
		if (status != DLADM_STATUS_OK) {
			nlog(LOG_ERR, "nwamd_set_unset_link_properties: "
			    "dladm_get_linkprop failed: %s",
			    dladm_status2str(status, errmsg));
			return;
		}
	} else {
		(void) snprintf(mtustr, DLADM_PROP_VAL_MAX, "%lld", mtu);
	}

	cp = mtustr;

	nlog(LOG_DEBUG, "nwamd_set_unset_link_properties: setting MTU of %s "
	    "for link %s", mtustr, ncu->ncu_name);
	status = dladm_set_linkprop(dld_handle, ncu->ncu_link.nwamd_link_id,
	    "mtu", &cp, 1, DLADM_OPT_ACTIVE);
	if (status != DLADM_STATUS_OK) {
		nlog(LOG_ERR, "nwamd_set_unset_link_properties: "
		    "dladm_set_linkprop failed: %s",
		    dladm_status2str(status, errmsg));
	}

	nlog(LOG_DEBUG, "nwamd_set_unset_link_properties: setting %d "
	    "autopush module for link %s", num_autopush, ncu->ncu_name);
	status = dladm_set_linkprop(dld_handle, ncu->ncu_link.nwamd_link_id,
	    "autopush", autopush, num_autopush, DLADM_OPT_ACTIVE);
	if (status != DLADM_STATUS_OK) {
		nlog(LOG_ERR, "nwamd_set_unset_link_properties: "
		    "dladm_set_linkprop failed for autopush property: %s",
		    dladm_status2str(status, errmsg));
	}

	/*
	 * Set physical address - either factory (if link_mac_addr is NULL
	 * or we are unsetting properties) or specified MAC address string.
	 */
	if (addr == NULL) {
		if ((hwaddr = calloc(1, DLPI_PHYSADDR_MAX)) == NULL) {
			nlog(LOG_ERR,
			    "nwamd_set_unset_link_properties: malloc() failed");
			return;
		}
		if ((retval = dlpi_get_physaddr(dh, DL_FACT_PHYS_ADDR,
		    hwaddr, &hwaddrlen)) != DLPI_SUCCESS) {
			nlog(LOG_ERR, "nwamd_set_unset_link_properties: "
			    "could not get physical address for %s: %s",
			    ncu->ncu_name, dlpi_strerror(retval));
			free(hwaddr);
			return;
		}
	} else {
		int addrlen = hwaddrlen;
		if ((hwaddr = _link_aton(addr, &addrlen)) == NULL) {
			if (addrlen == -1) {
				nlog(LOG_ERR,
				    "nwamd_set_unset_link_properties: "
				    "%s: bad address for %s",
				    addr, ncu->ncu_name);
				return;
			} else {
				nlog(LOG_ERR, "nwamd_set_unset_link_properties:"
				    " malloc() failed");
				return;
			}
		}
		hwaddrlen = addrlen;
	}

	/*
	 * Only set physical address if desired address differs from current -
	 * this avoids unnecessary chip resets for some drivers.
	 */
	retval = dlpi_get_physaddr(dh, DL_CURR_PHYS_ADDR, curraddr,
	    &hwaddrlen);
	if (retval != DLPI_SUCCESS || bcmp(curraddr, hwaddr, hwaddrlen) != 0) {
		retval = dlpi_set_physaddr(dh, DL_CURR_PHYS_ADDR, hwaddr,
		    hwaddrlen);
		if (retval != DLPI_SUCCESS) {
			nlog(LOG_ERR, "nwamd_set_unset_link_properties:"
			    "failed setting mac address on %s: %s",
			    ncu->ncu_name, dlpi_strerror(retval));
		}
	}
	free(hwaddr);
}

#define	WLAN_ENC(sec)						\
	((sec == DLADM_WLAN_SECMODE_WPA ? "WPA" : 		\
	(sec == DLADM_WLAN_SECMODE_WEP ? "WEP" : "none")))

#define	NEED_ENC(sec)						\
	(sec == DLADM_WLAN_SECMODE_WPA || sec == DLADM_WLAN_SECMODE_WEP)

#define	WIRELESS_LAN_INIT_COUNT	8

/*
 * The variable wireless_scan_level specifies the signal level
 * that we will initiate connections to previously-visited APs
 * at when we are in the connected state.
 */
dladm_wlan_strength_t wireless_scan_level = DLADM_WLAN_STRENGTH_WEAK;

/*
 * The variable wireless_scan_interval specifies how often the periodic
 * scan occurs.
 */
uint64_t wireless_scan_interval = WIRELESS_SCAN_INTERVAL_DEFAULT;

/*
 * The variable wireless_autoconf specifies if we use dladm_wlan_autoconf()
 * to connect.
 */
boolean_t wireless_autoconf = B_FALSE;

/*
 * The variable wireless_strict_bssid specifies if we only connect
 * to WLANs with BSSIDs that we previously connected to.
 */
boolean_t wireless_strict_bssid = B_FALSE;

/*
 * We need to ensure scan or connect threads do not run concurrently
 * on any links - otherwise we get radio interference.  Acquire this
 * lock on entering scan/connect threads to prevent this.
 */
pthread_mutex_t wireless_mutex = PTHREAD_MUTEX_INITIALIZER;

static void
scanconnect_entry(void)
{
	(void) pthread_mutex_lock(&wireless_mutex);
}

static void
scanconnect_exit(void)
{
	(void) pthread_mutex_unlock(&wireless_mutex);
}

/*
 * Below are functions used to handle storage/retrieval of keys
 * for a given WLAN. The keys are stored/retrieved using dladm_set_secobj()
 * and dladm_get_secobj().
 */

/*
 * Convert key hexascii string to raw secobj value. This
 * code is very similar to convert_secobj() in dladm.c, it would
 * be good to have a libdladm function to convert values.
 */
static int
key_string_to_secobj_value(char *buf, uint8_t *obj_val, uint_t *obj_lenp,
    dladm_secobj_class_t class)
{
	size_t buf_len = strlen(buf);

	nlog(LOG_DEBUG, "before: key_string_to_secobj_value: buf_len = %d",
	    buf_len);
	if (buf_len == 0) {
		/* length zero means "delete" */
		return (0);
	}

	if (buf[buf_len - 1] == '\n')
		buf[--buf_len] = '\0';

	nlog(LOG_DEBUG, "after: key_string_to_secobj_value: buf_len = %d",
	    buf_len);

	if (class == DLADM_SECOBJ_CLASS_WPA) {
		/*
		 * Per IEEE802.11i spec, the Pre-shared key (PSK) length should
		 * be between 8 and 63.
		 */
		if (buf_len < 8 || buf_len > 63) {
			nlog(LOG_ERR,
			    "key_string_to_secobj_value:"
			    " invalid WPA key length: buf_len = %d", buf_len);
			return (-1);
		}
		(void) memcpy(obj_val, buf, (uint_t)buf_len);
		*obj_lenp = buf_len;
		return (0);
	}

	switch (buf_len) {
	case 5:		/* ASCII key sizes */
	case 13:
		(void) memcpy(obj_val, buf, (uint_t)buf_len);
		*obj_lenp = (uint_t)buf_len;
		break;
	case 10:
	case 26:	/* Hex key sizes, not preceded by 0x */
		if (hexascii_to_octet(buf, (uint_t)buf_len, obj_val, obj_lenp)
		    != 0) {
			nlog(LOG_ERR,
			    "key_string_to_secobj_value: invalid WEP key");
			return (-1);
		}
		break;
	case 12:
	case 28:	/* Hex key sizes, preceded by 0x */
		if (strncmp(buf, "0x", 2) != 0 ||
		    hexascii_to_octet(buf + 2, (uint_t)buf_len - 2, obj_val,
		    obj_lenp) != 0) {
			nlog(LOG_ERR,
			    "key_string_to_secobj_value: invalid WEP key");
			return (-1);
		}
		break;
	default:
		syslog(LOG_ERR,
		    "key_string_to_secobj_value: invalid WEP key length");
		return (-1);
	}
	return (0);
}

/*
 * Callback used on each known WLAN:
 * return 1 if a secobj, linked with an existing kwown wlan, has the same name
 * of the secobj that is being created.
 */

static int
find_keyname_cb(nwam_known_wlan_handle_t kwh, void *new_keyname)
{
	nwam_error_t err;
	nwam_value_t old_key;

	char **old_keyname;
	uint_t num_old_keyname, i;

	if ((err = nwam_known_wlan_get_prop_value(kwh,
	    NWAM_KNOWN_WLAN_PROP_KEYNAME, &old_key)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "find_keyname_cb: nwam_known_wlan_get_prop: %s",
		    nwam_strerror(err));
		return (0);
	}
	if ((err = nwam_value_get_string_array(old_key, &old_keyname,
	    &num_old_keyname))
	    != NWAM_SUCCESS) {
		nlog(LOG_ERR, "find_keyname_cb: nwam_value_get_string: %s",
		    nwam_strerror(err));
		nwam_value_free(old_key);
		return (0);
	}
	nwam_value_free(old_key);
	for (i = 0; i < num_old_keyname; i++) {
		if (strcmp(old_keyname[i], (const char *)new_keyname) == 0)
			/* Found matching keyname so terminate walk */
			return (1);
	}
	return (0);
}

/*
 * Print the key name format into the appropriate field, then convert any ":"
 * characters to ".", as ":[1-4]" is the slot indicator, which otherwise
 * would trip us up.  Invalid characters for secobj names are ignored.
 * The fourth parameter is expected to be of size DLADM_SECOBJ_NAME_MAX.
 *
 * (Note that much of the system uses DLADM_WLAN_MAX_KEYNAME_LEN, which is 64
 * rather than 32, but that dladm_get_secobj will fail if a length greater than
 * DLD_SECOBJ_NAME_MAX is seen, and that's 32.  This is all horribly broken.)
 */
void
nwamd_set_key_name(const char *essid, const char *bssid, char *name, size_t nsz)
{
	int i, j;
	char secobj_name[DLADM_WLAN_MAX_KEYNAME_LEN];

	/* create a concatenated string with essid and bssid */
	if (bssid == NULL || bssid[0] == '\0') {
		(void) snprintf(secobj_name, sizeof (secobj_name), "nwam-%s",
		    essid);
	} else {
		(void) snprintf(secobj_name, sizeof (secobj_name), "nwam-%s-%s",
		    essid, bssid);
	}

	/* copy only valid chars to the return string, terminating with \0 */
	i = 0; /* index into secobj_name */
	j = 0; /* index into name */
	while (secobj_name[i] != '\0') {
		if (j == nsz - 1)
			break;

		if (secobj_name[i] == ':') {
			name[j] = '.';
			j++;
		} else if (isalnum(secobj_name[i]) ||
		    secobj_name[i] == '.' || secobj_name[i] == '-' ||
		    secobj_name[i] == '_') {
			name[j] = secobj_name[i];
			j++;
		}
		i++;
	}
	name[j] = '\0';
}

nwam_error_t
nwamd_wlan_set_key(const char *linkname, const char *essid, const char *bssid,
    uint32_t security_mode, uint_t keyslot, char *raw_key)
{
	nwamd_object_t ncu_obj;
	nwamd_ncu_t *ncu;
	nwamd_link_t *link;
	int ret = 0;
	uint8_t obj_val[DLADM_SECOBJ_VAL_MAX];
	uint_t obj_len = sizeof (obj_val);
	char obj_name[DLADM_SECOBJ_NAME_MAX];
	char obj_tempname[DLADM_SECOBJ_NAME_MAX];
	dladm_status_t status;
	char errmsg[DLADM_STRSIZE];
	dladm_secobj_class_t class;

	if ((ncu_obj = nwamd_ncu_object_find(NWAM_NCU_TYPE_LINK, linkname))
	    == NULL) {
		nlog(LOG_ERR, "nwamd_wlan_set_key: could not find object  "
		    "for link %s", linkname);
		return (NWAM_ENTITY_NOT_FOUND);
	}
	ncu = ncu_obj->nwamd_object_data;
	link = &ncu->ncu_link;

	class = (security_mode == DLADM_WLAN_SECMODE_WEP ?
	    DLADM_SECOBJ_CLASS_WEP : DLADM_SECOBJ_CLASS_WPA);
	if (key_string_to_secobj_value(raw_key, obj_val, &obj_len,
	    class) != 0) {
		/* above function logs internally on failure */
		nwamd_object_release(ncu_obj);
		return (NWAM_ERROR_INTERNAL);
	}

	nlog(LOG_DEBUG, "nwamd_wlan_set_key: running for link %s", linkname);
	/*
	 * Name key object for this WLAN so it can be later retrieved.
	 * (bssid is appended if an object, with the same keyname,
	 * already exists and is associated to a known wlan)
	 */
	nwamd_set_key_name(essid, NULL, obj_tempname, sizeof (obj_tempname));
	(void) nwam_walk_known_wlans(find_keyname_cb, obj_tempname, 0, &ret);
	/*
	 * We also check if the keyval is the same. The user might want
	 * to use the same key for more APs with the same ESSID.
	 * This can result in a known wlan with multiple BSSIDs
	 */
	if (ret == 1) {
		dladm_wlan_key_t *old_secobj = nwamd_wlan_get_key_named(
		    obj_tempname, security_mode);
		nlog(LOG_DEBUG, "found existing obj_name %s", obj_tempname);
		ret = memcmp((*old_secobj).wk_val, obj_val, obj_len);
		nwamd_set_key_name(essid, ret ? bssid : NULL, obj_name,
		    sizeof (obj_name));
		free(old_secobj);
	} else {
		nwamd_set_key_name(essid, NULL, obj_name,
		    sizeof (obj_name));
	}
	nlog(LOG_DEBUG, "store_key: obj_name is %s", obj_name);

	/*
	 * We have validated the new key, so remove the old one.
	 * This will actually delete the keyobj only if the user had set
	 * a wrong key and is replacing it with a new one for the same AP.
	 */
	status = dladm_unset_secobj(dld_handle, obj_name,
	    DLADM_OPT_ACTIVE | DLADM_OPT_PERSIST);
	if (status != DLADM_STATUS_OK && status != DLADM_STATUS_NOTFOUND) {
		nlog(LOG_ERR, "store_key: could not remove old secure object "
		    "'%s' for key: %s", obj_name,
		    dladm_status2str(status, errmsg));
		nwamd_object_release(ncu_obj);
		return (NWAM_ERROR_INTERNAL);
	}

	/* if we're just deleting the key, then we're done */
	if (raw_key[0] == '\0') {
		nwamd_object_release(ncu_obj);
		return (NWAM_SUCCESS);
	}

	status = dladm_set_secobj(dld_handle, obj_name, class,
	    obj_val, obj_len,
	    DLADM_OPT_CREATE | DLADM_OPT_PERSIST | DLADM_OPT_ACTIVE);
	if (status != DLADM_STATUS_OK) {
		nlog(LOG_ERR, "store_key: could not create secure object "
		    "'%s' for key: %s", obj_name,
		    dladm_status2str(status, errmsg));
		nwamd_object_release(ncu_obj);
		return (NWAM_ERROR_INTERNAL);
	}
	link->nwamd_link_wifi_key = nwamd_wlan_get_key_named(obj_name,
	    security_mode);
	(void) strlcpy(link->nwamd_link_wifi_keyname, obj_name,
	    sizeof (link->nwamd_link_wifi_keyname));
	link->nwamd_link_wifi_security_mode = security_mode;
	if (security_mode == DLADM_WLAN_SECMODE_WEP) {
		link->nwamd_link_wifi_key->wk_idx =
		    (keyslot >= 1 && keyslot <= 4) ? keyslot : 1;
	}

	/* If link NCU is offline* or online, (re)connect. */
	switch (ncu_obj->nwamd_object_state) {
	case NWAM_STATE_ONLINE:
		/* if changing the key of the connected WLAN, reconnect */
		if (strcmp(essid, link->nwamd_link_wifi_essid) == 0)
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    ncu_obj->nwamd_object_name, NWAM_STATE_ONLINE,
			    NWAM_AUX_STATE_LINK_WIFI_CONNECTING);
		break;
	case NWAM_STATE_OFFLINE_TO_ONLINE:
		/* if we are waiting for the key, connect */
		if (ncu_obj->nwamd_object_aux_state ==
		    NWAM_AUX_STATE_LINK_WIFI_NEED_KEY)
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    ncu_obj->nwamd_object_name,
			    NWAM_STATE_OFFLINE_TO_ONLINE,
			    NWAM_AUX_STATE_LINK_WIFI_CONNECTING);
		break;
	default:
		break;
	}
	nwamd_object_release(ncu_obj);

	return (NWAM_SUCCESS);
}

/*
 * returns NULL if no key was recovered from libdladm.  Passing in
 * security mode of 0 means we don't care what key type it is.
 */
dladm_wlan_key_t *
nwamd_wlan_get_key_named(const char *name, uint32_t security_mode)
{
	dladm_status_t status;
	char errmsg[DLADM_STRSIZE];
	dladm_wlan_key_t *cooked_key;
	dladm_secobj_class_t class;

	if (security_mode == DLADM_WLAN_SECMODE_NONE)
		return (NULL);

	/*
	 * Newly-allocated key must be freed by caller, or by
	 * subsequent call to nwamd_wlan_get_key_named().
	 */
	if ((cooked_key = malloc(sizeof (dladm_wlan_key_t))) == NULL) {
		nlog(LOG_ERR, "nwamd_wlan_get_key_named: malloc failed");
		return (NULL);
	}

	/*
	 * Set name appropriately to retrieve key for this WLAN.  Note that we
	 * cannot use the actual wk_name buffer size, as it's two times too
	 * large for dladm_get_secobj.
	 */
	(void) strlcpy(cooked_key->wk_name, name, DLADM_SECOBJ_NAME_MAX);
	nlog(LOG_DEBUG, "nwamd_wlan_get_key_named: len = %d, object = %s\n",
	    strlen(cooked_key->wk_name), cooked_key->wk_name);
	cooked_key->wk_len = sizeof (cooked_key->wk_val);
	cooked_key->wk_idx = 1;

	/* Try the kernel first, then fall back to persistent storage. */
	status = dladm_get_secobj(dld_handle, cooked_key->wk_name, &class,
	    cooked_key->wk_val, &cooked_key->wk_len,
	    DLADM_OPT_ACTIVE);
	if (status != DLADM_STATUS_OK) {
		nlog(LOG_DEBUG, "nwamd_wlan_get_key_named: "
		    "dladm_get_secobj(TEMP) failed: %s",
		    dladm_status2str(status, errmsg));
		status = dladm_get_secobj(dld_handle, cooked_key->wk_name,
		    &class, cooked_key->wk_val, &cooked_key->wk_len,
		    DLADM_OPT_PERSIST);
	}

	switch (status) {
	case DLADM_STATUS_OK:
		nlog(LOG_DEBUG, "nwamd_wlan_get_key_named: "
		    "dladm_get_secobj succeeded: len %d", cooked_key->wk_len);
		break;
	case DLADM_STATUS_NOTFOUND:
		/*
		 * We do not want an error in the case that the secobj
		 * is not found, since we then prompt for it.
		 */
		free(cooked_key);
		return (NULL);
	default:
		nlog(LOG_ERR, "nwamd_wlan_get_key_named: could not get key "
		    "from secure object '%s': %s", cooked_key->wk_name,
		    dladm_status2str(status, errmsg));
		free(cooked_key);
		return (NULL);
	}

	if (security_mode != 0) {
		switch (class) {
		case DLADM_SECOBJ_CLASS_WEP:
			if (security_mode == DLADM_WLAN_SECMODE_WEP)
				return (cooked_key);
			break;
		case DLADM_SECOBJ_CLASS_WPA:
			if (security_mode == DLADM_WLAN_SECMODE_WPA)
				return (cooked_key);
			break;
		default:
			/* shouldn't happen */
			nlog(LOG_ERR, "nwamd_wlan_get_key: invalid class %d",
			    class);
			break;
		}
		/* key type mismatch */
		nlog(LOG_ERR, "nwamd_wlan_get_key: key type mismatch"
		    " from secure object '%s'", cooked_key->wk_name);
		free(cooked_key);
		return (NULL);
	}

	return (cooked_key);
}

static dladm_wlan_key_t *
nwamd_wlan_get_key(const char *essid, const char *bssid, uint32_t security_mode)
{
	char keyname[DLADM_SECOBJ_NAME_MAX];

	nwamd_set_key_name(essid, bssid, keyname, DLADM_SECOBJ_NAME_MAX);

	return (nwamd_wlan_get_key_named(keyname, security_mode));
}

/*
 * Checks if a wireless network can be selected or not.  A wireless network
 * CANNOT be selected if the NCU is DISABLED, or the NCU is OFFLINE or
 * ONLINE* and has lower priority than the currently active priority-group.
 * Called with object lock held.
 */
static boolean_t
wireless_selection_possible(nwamd_object_t object)
{
	nwamd_ncu_t *ncu = object->nwamd_object_data;

	if (ncu->ncu_link.nwamd_link_media != DL_WIFI)
		return (B_FALSE);

	(void) pthread_mutex_lock(&active_ncp_mutex);
	if (object->nwamd_object_state == NWAM_STATE_DISABLED ||
	    ((object->nwamd_object_state == NWAM_STATE_OFFLINE ||
	    object->nwamd_object_state == NWAM_STATE_ONLINE_TO_OFFLINE) &&
	    ncu->ncu_link.nwamd_link_activation_mode ==
	    NWAM_ACTIVATION_MODE_PRIORITIZED &&
	    (current_ncu_priority_group == INVALID_PRIORITY_GROUP ||
	    ncu->ncu_link.nwamd_link_priority_group >
	    current_ncu_priority_group))) {
		(void) pthread_mutex_unlock(&active_ncp_mutex);
		return (B_FALSE);
	}
	(void) pthread_mutex_unlock(&active_ncp_mutex);

	return (B_TRUE);
}

/*
 * Update the selected and/or connected values for the
 * scan data.  If these change, we need to trigger a scan
 * event since the updated values need to be communicated
 * to the GUI.
 */
void
nwamd_set_selected_connected(nwamd_ncu_t *ncu, boolean_t selected,
    boolean_t connected)
{
	nwamd_link_t *link = &ncu->ncu_link;
	nwamd_wifi_scan_t *s = &link->nwamd_link_wifi_scan;
	int i;
	boolean_t trigger_scan_event = B_FALSE;

	for (i = 0; i < s->nwamd_wifi_scan_curr_num; i++) {
		if (strcmp(s->nwamd_wifi_scan_curr[i].nww_essid,
		    link->nwamd_link_wifi_essid) != 0 ||
		    (link->nwamd_link_wifi_bssid[0] != '\0' &&
		    strcmp(s->nwamd_wifi_scan_curr[i].nww_bssid,
		    link->nwamd_link_wifi_bssid) != 0))
			continue;
		if (selected) {
			if (!s->nwamd_wifi_scan_curr[i].nww_selected)
				trigger_scan_event = B_TRUE;
			s->nwamd_wifi_scan_curr[i].nww_selected = B_TRUE;
		} else {
			if (s->nwamd_wifi_scan_curr[i].nww_selected)
				trigger_scan_event = B_TRUE;
			s->nwamd_wifi_scan_curr[i].nww_selected = B_FALSE;
		}
		if (connected) {
			if (!s->nwamd_wifi_scan_curr[i].nww_connected)
				trigger_scan_event = B_TRUE;
			s->nwamd_wifi_scan_curr[i].nww_connected = B_TRUE;
		} else {
			if (s->nwamd_wifi_scan_curr[i].nww_connected)
				trigger_scan_event = B_TRUE;
			s->nwamd_wifi_scan_curr[i].nww_connected = B_FALSE;
		}
	}

	if (trigger_scan_event || s->nwamd_wifi_scan_changed) {
		nwamd_event_t scan_event = nwamd_event_init_wlan
		    (ncu->ncu_name, NWAM_EVENT_TYPE_WLAN_SCAN_REPORT, connected,
		    s->nwamd_wifi_scan_curr, s->nwamd_wifi_scan_curr_num);
		if (scan_event != NULL) {
			/* Avoid sending same scan data multiple times */
			s->nwamd_wifi_scan_changed = B_FALSE;
			nwamd_event_enqueue(scan_event);
		}
	}
}

/*
 * Callback used on each known WLAN - if the BSSID is matched, set
 * the ESSID of the hidden WLAN to the known WLAN name.
 */
static int
find_bssid_cb(nwam_known_wlan_handle_t kwh, void *data)
{
	nwamd_link_t *link = data;
	nwam_error_t err;
	nwam_value_t bssidval;
	char **bssids, *name;
	uint_t num_bssids, i;

	if ((err = nwam_known_wlan_get_prop_value(kwh,
	    NWAM_KNOWN_WLAN_PROP_BSSIDS, &bssidval)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "find_bssid_cb: nwam_known_wlan_get_prop: %s",
		    nwam_strerror(err));
		return (0);
	}
	if ((err = nwam_value_get_string_array(bssidval, &bssids, &num_bssids))
	    != NWAM_SUCCESS) {
		nlog(LOG_ERR, "find_bssid_cb: nwam_value_get_string_array: %s",
		    nwam_strerror(err));
		nwam_value_free(bssidval);
		return (0);
	}
	for (i = 0; i < num_bssids; i++) {
		if (strcmp(bssids[i], link->nwamd_link_wifi_bssid) == 0) {
			if ((err = nwam_known_wlan_get_name(kwh, &name))
			    != NWAM_SUCCESS) {
				nlog(LOG_ERR, "find_bssid_cb: "
				    "nwam_known_wlan_get_name: %s",
				    nwam_strerror(err));
				continue;
			}
			(void) strlcpy(link->nwamd_link_wifi_essid, name,
			    sizeof (link->nwamd_link_wifi_essid));
			free(name);
			nwam_value_free(bssidval);
			/* Found ESSID for BSSID so terminate walk */
			return (1);
		}
	}
	nwam_value_free(bssidval);

	return (0);
}

/*
 * We may have encountered a BSSID for a hidden WLAN before and as a result
 * may have a known WLAN entry with this BSSID.  Walk known WLANs, searching
 * for a BSSID match.  Called with object lock held.
 */
static void
check_if_hidden_wlan_was_visited(nwamd_link_t *link)
{
	(void) nwam_walk_known_wlans(find_bssid_cb, link,
	    NWAM_FLAG_KNOWN_WLAN_WALK_PRIORITY_ORDER, NULL);
}

nwam_error_t
nwamd_wlan_select(const char *linkname, const char *essid, const char *bssid,
    uint32_t security_mode, boolean_t add_to_known_wlans)
{
	nwamd_object_t ncu_obj;
	nwamd_ncu_t *ncu;
	nwamd_link_t *link;
	boolean_t found_key = B_FALSE;

	if ((ncu_obj = nwamd_ncu_object_find(NWAM_NCU_TYPE_LINK, linkname))
	    == NULL) {
		nlog(LOG_ERR, "nwamd_wlan_select: could not find object  "
		    "for link %s", linkname);
		return (NWAM_ENTITY_NOT_FOUND);
	}
	ncu = ncu_obj->nwamd_object_data;
	link = &ncu->ncu_link;

	/*
	 * If wireless selection is not possible because of the current
	 * state or priority-group, then stop.
	 */
	if (!wireless_selection_possible(ncu_obj)) {
		nwamd_object_release(ncu_obj);
		return (NWAM_ENTITY_INVALID_STATE);
	}

	/* unset selected, connected flag for previously connected wlan */
	nwamd_set_selected_connected(ncu, B_FALSE, B_FALSE);

	/* Disconnect to allow new selection to go ahead */
	(void) dladm_wlan_disconnect(dld_handle, link->nwamd_link_id);

	(void) strlcpy(link->nwamd_link_wifi_essid, essid,
	    sizeof (link->nwamd_link_wifi_essid));
	(void) strlcpy(link->nwamd_link_wifi_bssid, bssid,
	    sizeof (link->nwamd_link_wifi_bssid));
	link->nwamd_link_wifi_security_mode = security_mode;
	link->nwamd_link_wifi_add_to_known_wlans = add_to_known_wlans;

	/* If this is a hidden wlan, then essid is empty */
	if (link->nwamd_link_wifi_essid[0] == '\0')
		check_if_hidden_wlan_was_visited(link);

	/* set selected flag for newly-selected WLAN */
	nwamd_set_selected_connected(ncu, B_TRUE, B_FALSE);

	/* does this WLAN require a key? If so go to NEED_KEY */
	if (NEED_ENC(link->nwamd_link_wifi_security_mode)) {
		/*
		 * nwam secobjs can have two formats: nwam-ESSID-BSSID and
		 * nwam-ESSID. There is no reason for searching through known
		 * wlan keynames since this is only the selection process.
		 */
		if ((link->nwamd_link_wifi_key = nwamd_wlan_get_key
		    (link->nwamd_link_wifi_essid, link->nwamd_link_wifi_bssid,
		    link->nwamd_link_wifi_security_mode)) != NULL) {
			/*
			 * Found old key format,
			 * known wlans with similar names might exist
			 */
			nwamd_set_key_name(link->nwamd_link_wifi_essid,
			    link->nwamd_link_wifi_bssid,
			    link->nwamd_link_wifi_keyname,
			    DLADM_SECOBJ_NAME_MAX);
			nlog(LOG_DEBUG, "nwamd_wlan_select: got old format "
			    "WLAN key %s",
			    link->nwamd_link_wifi_keyname);
			found_key = B_TRUE;
		} else if ((link->nwamd_link_wifi_key = nwamd_wlan_get_key
		    (link->nwamd_link_wifi_essid, NULL,
		    link->nwamd_link_wifi_security_mode)) != NULL) {
			nwamd_set_key_name(link->nwamd_link_wifi_essid, NULL,
			    link->nwamd_link_wifi_keyname,
			    DLADM_SECOBJ_NAME_MAX);
			nlog(LOG_DEBUG, "nwamd_wlan_select: got WLAN key %s",
			    link->nwamd_link_wifi_keyname);
			found_key = B_TRUE;
		} else {
			nlog(LOG_ERR, "nwamd_wlan_select: could not "
			    "find key for WLAN '%s'",
			    link->nwamd_link_wifi_essid);
		}
	} else {
		free(link->nwamd_link_wifi_key);
		link->nwamd_link_wifi_key = NULL;
		link->nwamd_link_wifi_keyname[0] = '\0';
	}

	if (NEED_ENC(link->nwamd_link_wifi_security_mode) && !found_key) {
		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
		    ncu_obj->nwamd_object_name,
		    NWAM_STATE_OFFLINE_TO_ONLINE,
		    NWAM_AUX_STATE_LINK_WIFI_NEED_KEY);
	} else {
		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
		    ncu_obj->nwamd_object_name, NWAM_STATE_OFFLINE_TO_ONLINE,
		    NWAM_AUX_STATE_LINK_WIFI_CONNECTING);
	}
	nwamd_object_release(ncu_obj);

	return (NWAM_SUCCESS);
}

/*
 * See if BSSID is in visited list of BSSIDs for known WLAN. Used for
 * strict BSSID matching (depends on wireless_strict_bssid property value).
 */
static int
bssid_match(nwam_known_wlan_handle_t kwh, void *bssid)
{
	nwam_value_t bssidsval;
	nwam_error_t err;
	char **bssids;
	uint_t nelem, i;
	int found = 0;

	if ((err = nwam_known_wlan_get_prop_value(kwh,
	    NWAM_KNOWN_WLAN_PROP_BSSIDS, &bssidsval)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "bssid_match: %s", nwam_strerror(err));
		return (0);
	}
	if ((err = nwam_value_get_string_array(bssidsval, &bssids, &nelem))
	    != NWAM_SUCCESS) {
		nwam_value_free(bssidsval);
		return (0);
	}
	for (i = 0; i < nelem; i++) {
		if (strcmp((const char *)bssid, bssids[i]) == 0) {
			found = 1;
			break;
		}
	}
	nwam_value_free(bssidsval);

	return (found);
}

/* Find most prioritized AP with strongest signal in scan data. */
static int
find_best_wlan_cb(nwam_known_wlan_handle_t kwh, void *data)
{
	nwamd_ncu_t *ncu = data;
	nwamd_link_t *link = &ncu->ncu_link;
	nwamd_wifi_scan_t *s = &link->nwamd_link_wifi_scan;
	nwam_error_t err;
	char *name = NULL;
	int i;
	dladm_wlan_strength_t curr_strength = 0;
	dladm_wlan_strength_t max_strength = 0;
	boolean_t found = B_FALSE;

	if ((err = nwam_known_wlan_get_name(kwh, &name)) != NWAM_SUCCESS) {
		nlog(LOG_ERR, "find_best_wlan_cb: could not look up name: %s",
		    nwam_strerror(err));
		return (0);
	}

	if (link->nwamd_link_wifi_connected) {
		(void) dladm_wlan_str2strength
		    (link->nwamd_link_wifi_signal_strength, &curr_strength);
	}

	/*
	 * If we're >= scan level, don't pick another Known WLAN if still
	 * connected (even if a Known WLAN with higher priority is available).
	 * If the user wants to connect to a different Known WLAN, it can be
	 * done from the GUI or select-wifi subcommand of nwamadm(8).
	 */
	if (curr_strength >= wireless_scan_level &&
	    link->nwamd_link_wifi_connected) {
		free(name);
		return (1);
	}

	for (i = 0; i < s->nwamd_wifi_scan_curr_num; i++) {
		nwam_wlan_t *cur_wlan = &(s->nwamd_wifi_scan_curr[i]);
		int b_match = bssid_match(kwh, cur_wlan->nww_bssid);

		/*
		 * We need to either match the scanned essid, or in the case
		 * where the essid was not broadcast, match the scanned bssid.
		 */
		if (strcmp(cur_wlan->nww_essid, name) != 0 &&
		    !(cur_wlan->nww_essid[0] == '\0' && b_match))
			continue;
		/*
		 * If wireless_strict_bssid is specified, need to match
		 * BSSID too.
		 */
		if (wireless_strict_bssid && !b_match)
			continue;
		/*
		 * Found a match. Since we walk known WLANs in
		 * priority order, it's guaranteed to be the
		 * most prioritized. It may not be the strongest though -
		 * we continue the walk and record the strength along
		 * with the ESSID and BSSID, so that if we encounter
		 * another AP with the same ESSID but a higher signal strength,
		 * we will choose it - but only if the currently-connected
		 * WLAN is at or below wireless_scan_level.
		 */
		(void) dladm_wlan_str2strength
		    (cur_wlan->nww_signal_strength, &curr_strength);

		if (curr_strength > max_strength) {
			(void) strlcpy(link->nwamd_link_wifi_essid,
			    cur_wlan->nww_essid,
			    sizeof (link->nwamd_link_wifi_essid));
			/*
			 * Set BSSID if wireless_strict_bssid is specified or
			 * if this is a hidden WLAN.  Store the BSSID here and
			 * then later determine the hidden WLAN's name in the
			 * connect thread.
			 */
			if (wireless_strict_bssid ||
			    cur_wlan->nww_essid[0] == '\0') {
				(void) strlcpy(link->nwamd_link_wifi_bssid,
				    cur_wlan->nww_bssid,
				    sizeof (link->nwamd_link_wifi_bssid));
			}
			(void) strlcpy(link->nwamd_link_wifi_signal_strength,
			    cur_wlan->nww_signal_strength,
			    sizeof (link->nwamd_link_wifi_signal_strength));
			link->nwamd_link_wifi_security_mode =
			    cur_wlan->nww_security_mode;
			found = B_TRUE;
		}
		(void) dladm_wlan_str2strength
		    (link->nwamd_link_wifi_signal_strength, &max_strength);
	}
	free(name);
	return (found ? 1 : 0);
}

static boolean_t
nwamd_find_known_wlan(nwamd_object_t ncu_obj)
{
	nwamd_ncu_t *ncu = ncu_obj->nwamd_object_data;
	int ret;

	/*
	 * Walk known WLANs, finding lowest priority (preferred) WLAN
	 * in our scan results.
	 */
	(void) nwam_walk_known_wlans(find_best_wlan_cb, ncu,
	    NWAM_FLAG_KNOWN_WLAN_WALK_PRIORITY_ORDER, &ret);

	return (ret == 1);
}

/*
 * WLAN scan code for WIFI link NCUs.
 */

/* Create periodic scan event for object.  Called with object lock held. */
void
nwamd_ncu_create_periodic_scan_event(nwamd_object_t ncu_obj)
{
	nwamd_event_t scan_event;

	if (wireless_scan_interval == 0) {
		nlog(LOG_DEBUG, "nwamd_ncu_create_periodic_scan_event: "
		    "wireless_scan_interval set to 0 so no periodic scanning");
		return;
	}
	scan_event = nwamd_event_init(NWAM_EVENT_TYPE_PERIODIC_SCAN,
	    NWAM_OBJECT_TYPE_NCU, 0, ncu_obj->nwamd_object_name);
	if (scan_event != NULL) {
		nwamd_event_enqueue_timed(scan_event,
		    wireless_scan_interval > WIRELESS_SCAN_INTERVAL_MIN ?
		    wireless_scan_interval : WIRELESS_SCAN_INTERVAL_MIN);
	}
}

/* Handle periodic scan event (which puts link into WIFI_INIT state */
void
nwamd_ncu_handle_periodic_scan_event(nwamd_event_t event)
{
	nwamd_object_t ncu_obj;
	nwamd_ncu_t *ncu;

	ncu_obj = nwamd_object_find(NWAM_OBJECT_TYPE_NCU,
	    event->event_object);
	if (ncu_obj == NULL) {
		nlog(LOG_ERR, "nwamd_ncu_handle_periodic_scan_event: "
		    "no object %s", event->event_object);
		return;
	}
	ncu = ncu_obj->nwamd_object_data;

	/* Only rescan if state is offline* or online */
	nlog(LOG_DEBUG, "nwamd_ncu_handle_periodic_scan_event: doing rescan..");

	if (ncu_obj->nwamd_object_state == NWAM_STATE_OFFLINE_TO_ONLINE ||
	    ncu_obj->nwamd_object_state == NWAM_STATE_ONLINE) {
		/* rescan, then create periodic scan event */
		(void) nwamd_wlan_scan(ncu->ncu_name);
		nwamd_ncu_create_periodic_scan_event(ncu_obj);
	}
	nwamd_object_release(ncu_obj);
}

static boolean_t
get_scan_results(void *arg, dladm_wlan_attr_t *attrp)
{
	nwamd_wifi_scan_t *s = arg;
	const char *linkname = s->nwamd_wifi_scan_link;
	char essid_name[DLADM_STRSIZE];
	char bssid_name[DLADM_STRSIZE];
	char strength[DLADM_STRSIZE];
	uint_t i, index = 0;
	boolean_t found = B_FALSE;

	(void) dladm_wlan_essid2str(&attrp->wa_essid, essid_name);
	(void) dladm_wlan_bssid2str(&attrp->wa_bssid, bssid_name);
	(void) dladm_wlan_strength2str(&attrp->wa_strength, strength);

	index = s->nwamd_wifi_scan_curr_num;
	if (index == NWAMD_MAX_NUM_WLANS) {
		nlog(LOG_ERR, "get_scan_results: truncating WLAN scan results "
		    "for link %s: ommiting (%s, %s)", linkname, essid_name,
		    bssid_name);
		return (B_TRUE);
	}

	(void) strlcpy(s->nwamd_wifi_scan_curr[index].nww_essid, essid_name,
	    sizeof (s->nwamd_wifi_scan_curr[index].nww_essid));
	(void) strlcpy(s->nwamd_wifi_scan_curr[index].nww_bssid, bssid_name,
	    sizeof (s->nwamd_wifi_scan_curr[index].nww_bssid));
	(void) strlcpy(s->nwamd_wifi_scan_curr[index].nww_signal_strength,
	    strength,
	    sizeof (s->nwamd_wifi_scan_curr[index].nww_signal_strength));
	s->nwamd_wifi_scan_curr[index].nww_security_mode = attrp->wa_secmode;
	s->nwamd_wifi_scan_curr[index].nww_speed = attrp->wa_speed;
	s->nwamd_wifi_scan_curr[index].nww_channel = attrp->wa_channel;
	s->nwamd_wifi_scan_curr[index].nww_bsstype = attrp->wa_bsstype;

	/*
	 * We fill in actual values for selected/connected/key later when we
	 * reacquire the object lock.
	 */
	s->nwamd_wifi_scan_curr[index].nww_selected = B_FALSE;
	s->nwamd_wifi_scan_curr[index].nww_connected = B_FALSE;
	s->nwamd_wifi_scan_curr[index].nww_have_key = B_FALSE;
	s->nwamd_wifi_scan_curr[index].nww_keyindex = 1;
	s->nwamd_wifi_scan_curr_num++;

	/* Check if this AP was in previous scan results */
	for (i = 0; i < s->nwamd_wifi_scan_last_num; i++) {
		found = (strcmp(s->nwamd_wifi_scan_last[i].nww_essid,
		    essid_name) == 0 &&
		    strcmp(s->nwamd_wifi_scan_last[i].nww_bssid,
		    bssid_name) == 0);
		if (found)
			break;
	}
	if (!found)
		s->nwamd_wifi_scan_changed = B_TRUE;

	nlog(LOG_DEBUG, "get_scan_results(%s, %d): ESSID %s, BSSID %s",
	    linkname, index, essid_name, bssid_name);

	return (B_TRUE);
}

/*
 * Check if we're connected to the expected WLAN, or in the case of autoconf
 * record the WLAN we're connected to.
 */
boolean_t
nwamd_wlan_connected(nwamd_object_t ncu_obj)
{
	nwamd_ncu_t *ncu = ncu_obj->nwamd_object_data;
	nwamd_link_t *link = &ncu->ncu_link;
	dladm_wlan_linkattr_t attr;
	char essid[DLADM_STRSIZE];
	char bssid[DLADM_STRSIZE];
	boolean_t connected = B_FALSE;
	int retries = 0;

	/*
	 * This is awful, but some wireless drivers
	 * (particularly 'ath') will erroneously report
	 * "disconnected" if queried right after a scan.  If we
	 * see 'down' reported here, we retry a few times to
	 * make sure it's really down.
	 */
	while (retries++ < 4) {
		if (dladm_wlan_get_linkattr(dld_handle, link->nwamd_link_id,
		    &attr) != DLADM_STATUS_OK) {
			attr.la_status = DLADM_WLAN_LINK_DISCONNECTED;
		} else if (attr.la_status == DLADM_WLAN_LINK_CONNECTED) {
			break;
		}
	}

	if (attr.la_status == DLADM_WLAN_LINK_CONNECTED) {
		(void) dladm_wlan_essid2str(&attr.la_wlan_attr.wa_essid, essid);
		(void) dladm_wlan_bssid2str(&attr.la_wlan_attr.wa_bssid, bssid);
		connected = B_TRUE;
		nlog(LOG_DEBUG, "nwamd_wlan_connected: %s connected to %s %s",
		    ncu->ncu_name, essid, bssid);
	} else {
		return (B_FALSE);
	}
	/*
	 * If we're using autoconf,  we have no control over what we connect to,
	 * so rather than verifying ESSSID, simply record ESSID/BSSID.
	 */
	if (link->nwamd_link_wifi_autoconf) {
		(void) strlcpy(link->nwamd_link_wifi_essid, essid,
		    sizeof (link->nwamd_link_wifi_essid));
		(void) strlcpy(link->nwamd_link_wifi_bssid, bssid,
		    sizeof (link->nwamd_link_wifi_bssid));
	}
	/*
	 * Are we connected to expected WLAN? Note:
	 * we'd like to verify BSSID, but we cannot due to CR 6772510.
	 */
	if (strcmp(essid, link->nwamd_link_wifi_essid) == 0) {
		/* Update connected signal strength */
		(void) dladm_wlan_strength2str(&attr.la_wlan_attr.wa_strength,
		    link->nwamd_link_wifi_signal_strength);

		/* Store current BSSID */
		(void) strlcpy(link->nwamd_link_wifi_bssid, bssid,
		    sizeof (link->nwamd_link_wifi_bssid));

		if (attr.la_wlan_attr.wa_strength < wireless_scan_level) {
			/*
			 * We're connected, but we've dropped below
			 * scan threshold.  Initiate a scan.
			 */
			nlog(LOG_DEBUG, "nwamd_wlan_connected: "
			    "connected but signal under threshold...");
			(void) nwamd_wlan_scan(ncu->ncu_name);
		}
		return (connected);
	} else if (strlen(essid) == 0) {
		/*
		 * For hidden WLANs, no ESSID is specified, so we cannot verify
		 * WLAN name.
		 */
		nlog(LOG_DEBUG,
		    "nwamd_wlan_connected: connected to hidden WLAN, cannot "
		    "verify connection details");
		return (connected);
	} else {
		(void) nlog(LOG_ERR,
		    "nwamd_wlan_connected: wrong AP on %s; expected %s %s",
		    ncu->ncu_name, link->nwamd_link_wifi_essid,
		    link->nwamd_link_wifi_bssid);
		(void) dladm_wlan_disconnect(dld_handle, link->nwamd_link_id);
		link->nwamd_link_wifi_connected = B_FALSE;
		return (B_FALSE);
	}
}

/*
 * WLAN scan thread. Called with the per-link WiFi mutex held.
 */
static void *
wlan_scan_thread(void *arg)
{
	char *linkname = arg;
	nwamd_object_t ncu_obj;
	nwamd_ncu_t *ncu;
	nwamd_link_t *link;
	dladm_status_t status;
	char essid[DLADM_STRSIZE];
	char bssid[DLADM_STRSIZE];
	uint32_t now, link_id;
	nwamd_wifi_scan_t s;
	int i;

	if ((ncu_obj = nwamd_ncu_object_find(NWAM_NCU_TYPE_LINK, linkname))
	    == NULL) {
		nlog(LOG_ERR, "wlan_scan_thread: could not find object  "
		    "for link %s", linkname);
		free(linkname);
		return (NULL);
	}

	ncu = ncu_obj->nwamd_object_data;
	link = &ncu->ncu_link;

	/*
	 * It is possible multiple scan threads have queued up waiting for the
	 * object lock.  We try to prevent excessive scanning by limiting the
	 * interval between scans to WIRELESS_SCAN_REQUESTED_INTERVAL_MIN sec.
	 */
	now = NSEC_TO_SEC(gethrtime());
	if ((now - link->nwamd_link_wifi_scan.nwamd_wifi_scan_last_time) <
	    WIRELESS_SCAN_REQUESTED_INTERVAL_MIN) {
		nlog(LOG_DEBUG, "wlan_scan_thread: last scan for %s "
		    "was < %d sec ago, ignoring scan request",
		    linkname, WIRELESS_SCAN_REQUESTED_INTERVAL_MIN);
		nwamd_object_release(ncu_obj);
		free(linkname);
		return (NULL);
	}

	/*
	 * Prepare scan data - copy link name and copy previous "current"
	 * scan results from the nwamd_link_t to the last scan results for
	 * the next scan so that we can compare results to find if things
	 * have changed since last time.
	 */
	(void) bzero(&s, sizeof (nwamd_wifi_scan_t));
	(void) strlcpy(s.nwamd_wifi_scan_link, ncu->ncu_name,
	    sizeof (s.nwamd_wifi_scan_link));
	s.nwamd_wifi_scan_last_num =
	    link->nwamd_link_wifi_scan.nwamd_wifi_scan_curr_num;
	if (s.nwamd_wifi_scan_last_num > 0) {
		(void) memcpy(s.nwamd_wifi_scan_last,
		    link->nwamd_link_wifi_scan.nwamd_wifi_scan_curr,
		    s.nwamd_wifi_scan_last_num * sizeof (nwam_wlan_t));
	}
	link_id = link->nwamd_link_id;
	nwamd_object_release(ncu_obj);

	nlog(LOG_DEBUG, "wlan_scan_thread: initiating scan on %s",
	    s.nwamd_wifi_scan_link);

	scanconnect_entry();
	status = dladm_wlan_scan(dld_handle, link_id, &s, get_scan_results);
	s.nwamd_wifi_scan_last_time = NSEC_TO_SEC(gethrtime());
	if (!s.nwamd_wifi_scan_changed) {
		/* Scan may have lost WLANs, if so this qualifies as change */
		s.nwamd_wifi_scan_changed = (s.nwamd_wifi_scan_curr_num !=
		    s.nwamd_wifi_scan_last_num);
	}
	scanconnect_exit();

	if (status != DLADM_STATUS_OK) {
		nlog(LOG_ERR, "wlan_scan_thread: cannot scan link %s",
		    s.nwamd_wifi_scan_link);
		free(linkname);
		return (NULL);
	}

	if ((ncu_obj = nwamd_ncu_object_find(NWAM_NCU_TYPE_LINK, linkname))
	    == NULL) {
		nlog(LOG_ERR, "wlan_scan_thread: could not find object  "
		    "for link %s after doing scan", linkname);
		free(linkname);
		return (NULL);
	}
	ncu = ncu_obj->nwamd_object_data;
	link = &ncu->ncu_link;

	/* For new scan data, add key info from known WLANs */
	for (i = 0; i < s.nwamd_wifi_scan_curr_num; i++) {
		if (NEED_ENC(s.nwamd_wifi_scan_curr[i].nww_security_mode)) {
			char keyname[NWAM_MAX_VALUE_LEN];
			dladm_wlan_key_t *key = NULL;

			/*
			 * If strict_bssid is true, we start checking for
			 * known wlans with the same BSSID.
			 * This would prevent the selection of secobjs
			 * that actually are referenced by different kwl
			 * with the same ESSID.
			 */
			if (wireless_strict_bssid) {
				int b_match = 0;
				(void) nwam_walk_known_wlans(bssid_match,
				    s.nwamd_wifi_scan_curr[i].nww_bssid, 0,
				    &b_match);
				if (b_match == 0)
					continue;
			}

			if (known_wlan_get_keyname
			    (s.nwamd_wifi_scan_curr[i].nww_essid, keyname)
			    == NWAM_SUCCESS &&
			    (key = nwamd_wlan_get_key_named(keyname,
			    s.nwamd_wifi_scan_curr[i].nww_security_mode))
			    != NULL) {
				s.nwamd_wifi_scan_curr[i].nww_have_key =
				    B_TRUE;
				s.nwamd_wifi_scan_curr[i].nww_keyindex =
				    s.nwamd_wifi_scan_curr[i].
				    nww_security_mode ==
				    DLADM_WLAN_SECMODE_WEP ?
				    key->wk_idx : 1;
				nlog(LOG_DEBUG, "found matching keyname for \
				    %s", s.nwamd_wifi_scan_curr[i].nww_bssid);
				free(key);
			}
		}
	}
	/* Copy scan data into nwamd_link_t */
	link->nwamd_link_wifi_scan = s;
	/* Set selected, connected and send scan event if we've got new data */
	nwamd_set_selected_connected(ncu,
	    link->nwamd_link_wifi_essid[0] != '\0',
	    link->nwamd_link_wifi_connected);

	/*
	 * If wireless selection is not possible because of the current
	 * state or priority-group, then this was just a scan request.
	 * Nothing else to do.
	 */
	if (!wireless_selection_possible(ncu_obj)) {
		nwamd_object_release(ncu_obj);
		free(linkname);
		return (NULL);
	}

	/*
	 * Check if WLAN is on our known WLAN list. If no
	 * previously-visited WLANs are found in scan data, set
	 * new state to NEED_SELECTION (provided we're not currently
	 * connected, as can be the case during a periodic scan or
	 * monitor-triggered scan where the signal strength recovers.
	 */
	if (!nwamd_find_known_wlan(ncu_obj)) {
		if (!nwamd_wlan_connected(ncu_obj)) {
			if (link->nwamd_link_wifi_connected) {
				nlog(LOG_DEBUG, "wlan_scan_thread: "
				    "unexpected disconnect after scan");
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    ncu_obj->nwamd_object_name,
				    NWAM_STATE_ONLINE_TO_OFFLINE,
				    NWAM_AUX_STATE_DOWN);
			} else {
				nlog(LOG_DEBUG, "wlan_scan_thread: "
				    "no known WLANs - ask user");
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    ncu_obj->nwamd_object_name,
				    NWAM_STATE_OFFLINE_TO_ONLINE,
				    NWAM_AUX_STATE_LINK_WIFI_NEED_SELECTION);
			}
		} else {
			/* still connected. if not online, change to online */
			nlog(LOG_DEBUG, "wlan_scan_thread: still connected to "
			    "%s %s", link->nwamd_link_wifi_essid,
			    link->nwamd_link_wifi_bssid);
			if (ncu_obj->nwamd_object_state != NWAM_STATE_ONLINE) {
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    ncu_obj->nwamd_object_name,
				    NWAM_STATE_OFFLINE_TO_ONLINE,
				    NWAM_AUX_STATE_UP);
			}
		}
		nwamd_object_release(ncu_obj);

	} else {
		nlog(LOG_DEBUG, "wlan_scan_thread: found known WLAN %s %s",
		    link->nwamd_link_wifi_essid, link->nwamd_link_wifi_bssid);

		if (!nwamd_wlan_connected(ncu_obj)) {
			/* Copy selected ESSID/BSSID, unlock, call select */
			(void) strlcpy(essid, link->nwamd_link_wifi_essid,
			    sizeof (essid));
			(void) strlcpy(bssid, link->nwamd_link_wifi_bssid,
			    sizeof (bssid));
			nwamd_object_release(ncu_obj);
			(void) nwamd_wlan_select(linkname, essid, bssid,
			    link->nwamd_link_wifi_security_mode, B_TRUE);
		} else {
			/* still connected.  if not online, change to online */
			nlog(LOG_DEBUG, "wlan_scan_thread: still connected to "
			    "known WLAN %s %s", link->nwamd_link_wifi_essid,
			    link->nwamd_link_wifi_bssid);
			if (ncu_obj->nwamd_object_state != NWAM_STATE_ONLINE) {
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    ncu_obj->nwamd_object_name,
				    NWAM_STATE_OFFLINE_TO_ONLINE,
				    NWAM_AUX_STATE_UP);
			}
			nwamd_object_release(ncu_obj);
		}
	}
	free(linkname);
	return (NULL);
}

nwam_error_t
nwamd_wlan_scan(const char *linkname)
{
	pthread_t wifi_thread;
	char *link = strdup(linkname);

	if (link == NULL) {
		nlog(LOG_ERR, "nwamd_wlan_scan: out of memory");
		return (NWAM_NO_MEMORY);
	}

	nlog(LOG_DEBUG, "nwamd_wlan_scan: WLAN scan for %s",
	    link);

	if (pthread_create(&wifi_thread, NULL, wlan_scan_thread,
	    link) != 0) {
		nlog(LOG_ERR, "nwamd_wlan_scan: could not start scan");
		free(link);
		return (NWAM_ERROR_INTERNAL);
	}
	/* detach thread so that it doesn't become a zombie */
	(void) pthread_detach(wifi_thread);
	return (NWAM_SUCCESS);
}

/*
 * WLAN connection code.
 */

static dladm_status_t
do_connect(uint32_t link_id, dladm_wlan_attr_t *attrp, dladm_wlan_key_t *key,
    uint_t keycount, uint_t flags)
{
	dladm_status_t status;
	char errmsg[DLADM_STRSIZE];

	scanconnect_entry();
	status = dladm_wlan_connect(dld_handle, link_id, attrp,
	    DLADM_WLAN_CONNECT_TIMEOUT_DEFAULT, key, keycount, flags);
	scanconnect_exit();

	nlog(LOG_DEBUG, "nwamd_do_connect: dladm_wlan_connect returned %s",
	    dladm_status2str(status, errmsg));

	return (status);
}

static void *
wlan_connect_thread(void *arg)
{
	char *linkname = arg;
	nwamd_object_t ncu_obj;
	nwamd_ncu_t *ncu;
	nwamd_link_t *link;
	nwam_error_t err;
	uint_t	keycount;
	uint32_t link_id;
	dladm_wlan_key_t *key = NULL;
	dladm_wlan_attr_t attr;
	dladm_status_t status;
	boolean_t autoconf = B_FALSE;

	if ((ncu_obj = nwamd_ncu_object_find(NWAM_NCU_TYPE_LINK, linkname))
	    == NULL) {
		nlog(LOG_ERR, "wlan_connect_thread: could not find object  "
		    "for link %s", linkname);
		free(linkname);
		return (NULL);
	}

	ncu = ncu_obj->nwamd_object_data;
	link = &ncu->ncu_link;

	if (!wireless_selection_possible(ncu_obj)) {
		nlog(LOG_DEBUG, "wlan_connect_thread: %s in invalid state or "
		    "has lower priority", ncu->ncu_name);
		goto done;
	}

	/* If it is already connected to the required AP, just return. */
	if (nwamd_wlan_connected(ncu_obj)) {
		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
		    ncu_obj->nwamd_object_name,
		    ncu_obj->nwamd_object_state, NWAM_AUX_STATE_UP);
		goto done;
	}

	(void) memset(&attr, 0, sizeof (attr));
	if (dladm_wlan_str2essid(link->nwamd_link_wifi_essid, &attr.wa_essid)
	    != DLADM_STATUS_OK) {
		nlog(LOG_ERR, "wlan_connect_thread: invalid ESSID '%s' "
		    "for '%s'", link->nwamd_link_wifi_essid, ncu->ncu_name);
		goto done;
	}
	attr.wa_valid = DLADM_WLAN_ATTR_ESSID;

	/* note: bssid logic here is non-functional */
	if (link->nwamd_link_wifi_bssid[0] != '\0') {
		if (dladm_wlan_str2bssid(link->nwamd_link_wifi_bssid,
		    &attr.wa_bssid) != DLADM_STATUS_OK) {
			nlog(LOG_ERR, "wlan_connect_thread: invalid BSSID '%s'",
			    "for '%s'", link->nwamd_link_wifi_bssid,
			    ncu->ncu_name);
		} else {
			attr.wa_valid |= DLADM_WLAN_ATTR_BSSID;
		}
	}

	/* First check for the key */
	if (NEED_ENC(link->nwamd_link_wifi_security_mode)) {
		if (link->nwamd_link_wifi_key == NULL) {
			nlog(LOG_ERR, "wlan_connect_thread: could not find "
			    "key for WLAN '%s'", link->nwamd_link_wifi_essid);
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    ncu_obj->nwamd_object_name,
			    NWAM_STATE_OFFLINE_TO_ONLINE,
			    NWAM_AUX_STATE_LINK_WIFI_NEED_KEY);
			goto done;
		}
		/* Make a copy of the key as we need to unlock the object */
		if ((key = calloc(1, sizeof (dladm_wlan_key_t))) == NULL) {
			nlog(LOG_ERR, "wlan_connect_thread: out of memory");
			goto done;
		}
		(void) memcpy(key, link->nwamd_link_wifi_key,
		    sizeof (dladm_wlan_key_t));

		attr.wa_valid |= DLADM_WLAN_ATTR_SECMODE;
		attr.wa_secmode = link->nwamd_link_wifi_security_mode;
		keycount = 1;
		nlog(LOG_DEBUG, "wlan_connect_thread: retrieved key");
	} else {
		key = NULL;
		keycount = 0;
	}

	/*
	 * Connect; only scan if a bssid was not specified.  If it times out,
	 * try a second time using autoconf.  Drop the object lock during the
	 * connect attempt since connecting may take some time, and access to
	 * the link object during that period would be impossible if we held the
	 * lock.
	 */

	link->nwamd_link_wifi_autoconf = B_FALSE;
	link_id = link->nwamd_link_id;

	nwamd_object_release(ncu_obj);

	status = do_connect(link_id, &attr, key, keycount,
	    DLADM_WLAN_CONNECT_NOSCAN);
	if (status != DLADM_STATUS_OK) {
		/* Connect failed, try autoconf */
		if (!wireless_autoconf || (status = do_connect(link_id, &attr,
		    NULL, 0, 0)) != DLADM_STATUS_OK) {
			nlog(LOG_ERR, "wlan_connect_thread: connect failed for "
			    "%s", linkname);
			goto done_unlocked;
		}
		if (status == DLADM_STATUS_OK)
			autoconf = B_TRUE;
	}

	/* Connect succeeded, reacquire object */
	if ((ncu_obj = nwamd_ncu_object_find(NWAM_NCU_TYPE_LINK, linkname))
	    == NULL) {
		nlog(LOG_ERR, "wlan_connect_thread: could not find object  "
		    "for link %s", linkname);
		goto done_unlocked;
	}

	ncu = ncu_obj->nwamd_object_data;
	link = &ncu->ncu_link;

	if (autoconf)
		link->nwamd_link_wifi_autoconf = B_TRUE;

	/*
	 * If WLAN is WEP/WPA, we would like to test the connection as the key
	 * may be wrong.  It is difficult to find a reliable test that works
	 * across APs however.  Do nothing for now.
	 */
	link->nwamd_link_wifi_connected = nwamd_wlan_connected(ncu_obj);

	if (link->nwamd_link_wifi_connected) {
		if (link->nwamd_link_wifi_add_to_known_wlans) {
			/* add to known WLANs */
			nlog(LOG_DEBUG, "wlan_connect_thread: "
			    "add '%s' to known WLANs",
			    link->nwamd_link_wifi_essid);
			if ((err = nwam_known_wlan_add_to_known_wlans
			    (link->nwamd_link_wifi_essid,
			    link->nwamd_link_wifi_bssid[0] != '\0' ?
			    link->nwamd_link_wifi_bssid : NULL,
			    link->nwamd_link_wifi_security_mode,
			    link->nwamd_link_wifi_security_mode ==
			    DLADM_WLAN_SECMODE_WEP ?
			    (uint_t)link->nwamd_link_wifi_key->wk_idx : 1,
			    NEED_ENC(link->nwamd_link_wifi_security_mode) ?
			    link->nwamd_link_wifi_keyname : NULL))
			    != NWAM_SUCCESS) {
				nlog(LOG_ERR, "wlan_connect_thread: "
				    "could not add to known WLANs: %s",
				    nwam_strerror(err));
			}
		}
		nwamd_set_selected_connected(ncu, B_TRUE, B_TRUE);
		nlog(LOG_DEBUG, "wlan_connect_thread: connect "
		    "succeeded, setting state online");
		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
		    ncu_obj->nwamd_object_name, NWAM_STATE_ONLINE,
		    NWAM_AUX_STATE_UP);
	}

done:
	nwamd_object_release(ncu_obj);
done_unlocked:
	free(linkname);
	free(key);

	return (NULL);
}

void
nwamd_wlan_connect(const char *linkname)
{
	pthread_t wifi_thread;
	char *link = strdup(linkname);

	if (link == NULL) {
		nlog(LOG_ERR, "nwamd_wlan_connect: out of memory");
		return;
	}

	nlog(LOG_DEBUG, "nwamd_wlan_connect: WLAN connect for %s",
	    link);

	if (pthread_create(&wifi_thread, NULL, wlan_connect_thread, link) != 0)
		nlog(LOG_ERR, "nwamd_wlan_connect: could not start connect");

	/* detach thread so that it doesn't become a zombie */
	(void) pthread_detach(wifi_thread);
}

/*
 * Launch signal strength-monitoring thread which periodically
 * checks connection and signal strength.  If we become disconnected
 * or signal drops below threshold specified by wireless_scan_level,
 * initiate a scan.  The scan initiation is taken care of by
 * the call to nwamd_wlan_connected().
 */
static void *
wlan_monitor_signal_thread(void *arg)
{
	char *linkname = arg;
	nwamd_object_t ncu_obj;
	nwamd_ncu_t *ncu;
	nwamd_link_t *link;
	boolean_t first_time = B_TRUE;

	for (;;) {
		if ((ncu_obj = nwamd_ncu_object_find(NWAM_NCU_TYPE_LINK,
		    linkname)) == NULL) {
			nlog(LOG_ERR, "wlan_monitor_signal_thread: could "
			    "not find object for link %s", linkname);
			break;
		}
		ncu = ncu_obj->nwamd_object_data;
		link = &ncu->ncu_link;

		/* If the NCU is DISABLED/OFFLINE, exit the monitoring thread */
		if (ncu_obj->nwamd_object_state == NWAM_STATE_OFFLINE ||
		    ncu_obj->nwamd_object_state == NWAM_STATE_DISABLED) {
			nlog(LOG_INFO, "wlan_monitor_signal_thread: "
			    "%s is %s, stopping thread", linkname,
			    nwam_state_to_string(ncu_obj->nwamd_object_state));
			link->nwamd_link_wifi_monitor_thread = 0;
			nwamd_object_release(ncu_obj);
			break;
		}

		/*
		 * First time thru loop, we check if there is another
		 * link monitoring thread in operation - if so exit this
		 * thread.
		 */
		if (first_time) {
			first_time = B_FALSE;

			if (link->nwamd_link_wifi_monitor_thread != 0) {
				/* Already have a monitor thread for link? */
				nwamd_object_release(ncu_obj);
				break;
			} else {
				link->nwamd_link_wifi_monitor_thread =
				    pthread_self();
			}
		}
		if (!nwamd_wlan_connected(ncu_obj)) {
			nlog(LOG_ERR, "wlan_monitor_signal_thread: "
			    "disconnect occured for WLAN on link %s", linkname);
			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    ncu_obj->nwamd_object_name,
			    NWAM_STATE_ONLINE_TO_OFFLINE,
			    NWAM_AUX_STATE_DOWN);
			link->nwamd_link_wifi_monitor_thread = 0;
			nwamd_object_release(ncu_obj);
			break;
		}
		nwamd_object_release(ncu_obj);
		(void) sleep(WIRELESS_MONITOR_SIGNAL_INTERVAL);
	}
	free(linkname);

	return (NULL);
}

void
nwamd_wlan_monitor_signal(const char *linkname)
{
	pthread_t wifi_thread;
	char *link = strdup(linkname);

	if (link == NULL) {
		nlog(LOG_ERR, "nwamd_wlan_monitor_signal: out of memory");
		return;
	}

	nlog(LOG_DEBUG, "nwamd_wlan_monitor_signal: WLAN monitor for %s",
	    link);

	if (pthread_create(&wifi_thread, NULL, wlan_monitor_signal_thread,
	    link) != 0) {
		nlog(LOG_ERR, "nwamd_wlan_monitor_signal: could not monitor "
		    "link %s", link);
		free(link);
		return;
	}

	/* detach thread so that it doesn't become a zombie */
	(void) pthread_detach(wifi_thread);
}

void
nwamd_ncu_handle_link_state_event(nwamd_event_t event)
{
	nwam_event_t evm;
	nwamd_object_t ncu_obj;
	nwamd_ncu_t *ncu;
	nwamd_link_t *link;

	ncu_obj = nwamd_object_find(NWAM_OBJECT_TYPE_NCU, event->event_object);
	if (ncu_obj == NULL) {
		nlog(LOG_INFO, "nwamd_ncu_handle_link_state_event: no object "
		    "%s", event->event_object);
		nwamd_event_do_not_send(event);
		return;
	}
	ncu = ncu_obj->nwamd_object_data;
	link = &ncu->ncu_link;
	evm = event->event_msg;

	/*
	 * We ignore link state events for WiFi because it is very flaky.
	 * Instead we use the monitor thread and drive WiFi state changes from
	 * there.
	 */
	if (link->nwamd_link_media == DL_WIFI) {
		nwamd_object_release(ncu_obj);
		return;
	}

	/*
	 * If it's a link up event and we're not disabled, go online.
	 */
	if (evm->nwe_data.nwe_link_state.nwe_link_up &&
	    ncu_obj->nwamd_object_state != NWAM_STATE_DISABLED) {

		if (link->nwamd_link_activation_mode ==
		    NWAM_ACTIVATION_MODE_PRIORITIZED) {
			int64_t priority_group;

			(void) pthread_mutex_lock(&active_ncp_mutex);
			priority_group = current_ncu_priority_group;
			(void) pthread_mutex_unlock(&active_ncp_mutex);

			/* compare priority groups */
			if (link->nwamd_link_priority_group > priority_group) {
				nlog(LOG_DEBUG,
				    "nwamd_ncu_handle_link_state_event: "
				    "got LINK UP event for priority group "
				    "%lld, less preferred than current %lld, "
				    "ignoring",
				    link->nwamd_link_priority_group,
				    priority_group);

			} else if (link->nwamd_link_priority_group ==
			    priority_group) {
				nlog(LOG_DEBUG,
				    "nwamd_ncu_handle_link_state_event: "
				    "got LINK UP event for priority group "
				    "%lld, same as current %lld",
				    link->nwamd_link_priority_group,
				    priority_group);
				/*
				 * Change link state to UP.  It will be
				 * propagated to IP state machine.  Only do
				 * the NCU check if and when the interface
				 * NCU is online.
				 */
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    event->event_object,
				    NWAM_STATE_OFFLINE_TO_ONLINE,
				    NWAM_AUX_STATE_UP);
			} else {
				nlog(LOG_DEBUG,
				    "nwamd_ncu_handle_link_state_event: "
				    "got LINK UP event for priority group "
				    "%lld, more preferred than current %lld",
				    link->nwamd_link_priority_group,
				    priority_group);

				/*
				 * We need to mark the link as up so that when
				 * it is activated we will bring the interface
				 * up.
				 */
				nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
				    event->event_object,
				    NWAM_STATE_OFFLINE_TO_ONLINE,
				    NWAM_AUX_STATE_UP);
				nwamd_object_release(ncu_obj);
				nwamd_ncp_deactivate_priority_group
				    (priority_group);
				nwamd_ncp_activate_priority_group
				    (link->nwamd_link_priority_group);
				return;
			}

		} else if (link->nwamd_link_activation_mode ==
		    NWAM_ACTIVATION_MODE_MANUAL) {
			nlog(LOG_DEBUG, "nwamd_ncu_handle_link_state_event: "
			    "got LINK UP event for manual NCU %s",
			    ncu_obj->nwamd_object_name);

			nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
			    event->event_object, NWAM_STATE_OFFLINE_TO_ONLINE,
			    NWAM_AUX_STATE_UP);
		}
	}

	/*
	 * If the link is down then start or continue transition down.
	 */
	if (!evm->nwe_data.nwe_link_state.nwe_link_up &&
	    (ncu_obj->nwamd_object_state == NWAM_STATE_ONLINE ||
	    ncu_obj->nwamd_object_state == NWAM_STATE_OFFLINE_TO_ONLINE)) {

		if (link->nwamd_link_activation_mode ==
		    NWAM_ACTIVATION_MODE_PRIORITIZED) {
			nlog(LOG_DEBUG,
			    "nwamd_ncu_handle_link_state_event: "
			    "got LINK DOWN for priority group %lld",
			    link->nwamd_link_priority_group);
			/* Moving to offline checks priority group */
		} else {
			nlog(LOG_DEBUG, "nwamd_ncu_handle_link_state_event: "
			    "got LINK DOWN event for manual NCU %s",
			    ncu_obj->nwamd_object_name);
		}
		nwamd_object_set_state(NWAM_OBJECT_TYPE_NCU,
		    event->event_object, NWAM_STATE_ONLINE_TO_OFFLINE,
		    NWAM_AUX_STATE_DOWN);
	}

	nwamd_object_release(ncu_obj);
}
/*
 * 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.
 */

#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <signal.h>
#include <errno.h>
#include <syslog.h>
#include <libuutil.h>
#include <errno.h>

#include "events.h"
#include "objects.h"
#include "util.h"

/*
 * objects.c - contains routines which manipulate object lists of NCUs,
 * locations, ENMs and known WLANs.
 */

typedef struct nwamd_object_list {
	nwam_object_type_t object_type;
	uu_list_t *object_list;
	nwamd_event_method_t *object_event_methods;
	pthread_rwlock_t object_list_lock;
} nwamd_object_list_t;

nwamd_event_method_t enm_event_methods[] =
{
	{ NWAM_EVENT_TYPE_OBJECT_INIT, nwamd_enm_handle_init_event },
	{ NWAM_EVENT_TYPE_OBJECT_FINI, nwamd_enm_handle_fini_event },
	{ NWAM_EVENT_TYPE_OBJECT_ACTION, nwamd_enm_handle_action_event },
	{ NWAM_EVENT_TYPE_OBJECT_STATE, nwamd_enm_handle_state_event },
	{ NWAM_EVENT_TYPE_NOOP, NULL }
};

nwamd_event_method_t loc_event_methods[] =
{
	{ NWAM_EVENT_TYPE_OBJECT_INIT, nwamd_loc_handle_init_event },
	{ NWAM_EVENT_TYPE_OBJECT_FINI, nwamd_loc_handle_fini_event },
	{ NWAM_EVENT_TYPE_OBJECT_ACTION, nwamd_loc_handle_action_event },
	{ NWAM_EVENT_TYPE_OBJECT_STATE, nwamd_loc_handle_state_event },
	{ NWAM_EVENT_TYPE_NOOP, NULL }
};

nwamd_event_method_t ncu_event_methods[] =
{
	{ NWAM_EVENT_TYPE_IF_STATE, nwamd_ncu_handle_if_state_event },
	{ NWAM_EVENT_TYPE_IF_ACTION, nwamd_ncu_handle_if_action_event },
	{ NWAM_EVENT_TYPE_LINK_STATE, nwamd_ncu_handle_link_state_event },
	{ NWAM_EVENT_TYPE_LINK_ACTION, nwamd_ncu_handle_link_action_event },
	{ NWAM_EVENT_TYPE_OBJECT_INIT, nwamd_ncu_handle_init_event },
	{ NWAM_EVENT_TYPE_OBJECT_FINI, nwamd_ncu_handle_fini_event },
	{ NWAM_EVENT_TYPE_OBJECT_ACTION, nwamd_ncu_handle_action_event },
	{ NWAM_EVENT_TYPE_OBJECT_STATE, nwamd_ncu_handle_state_event },
	{ NWAM_EVENT_TYPE_PERIODIC_SCAN, nwamd_ncu_handle_periodic_scan_event },
	{ NWAM_EVENT_TYPE_NOOP, NULL }
};

nwamd_event_method_t ncp_event_methods[] =
{
	{ NWAM_EVENT_TYPE_OBJECT_ACTION, nwamd_ncp_handle_action_event },
	{ NWAM_EVENT_TYPE_OBJECT_STATE, nwamd_ncp_handle_state_event },
	{ NWAM_EVENT_TYPE_UPGRADE, nwamd_handle_upgrade },
	{ NWAM_EVENT_TYPE_NOOP, NULL }
};

nwamd_event_method_t known_wlan_event_methods[] =
{
	{ NWAM_EVENT_TYPE_OBJECT_INIT, nwamd_known_wlan_handle_init_event },
	{ NWAM_EVENT_TYPE_OBJECT_FINI, NULL },
	{ NWAM_EVENT_TYPE_OBJECT_ACTION, nwamd_known_wlan_handle_action_event },
	{ NWAM_EVENT_TYPE_NOOP, NULL }
};

/* Should be kept in same order as object types */
nwamd_object_list_t object_lists[] = {
	{ NWAM_OBJECT_TYPE_NCP, NULL, ncp_event_methods,
	PTHREAD_RWLOCK_INITIALIZER },
	{ NWAM_OBJECT_TYPE_NCU, NULL, ncu_event_methods,
	PTHREAD_RWLOCK_INITIALIZER },
	{ NWAM_OBJECT_TYPE_LOC, NULL, loc_event_methods,
	PTHREAD_RWLOCK_INITIALIZER },
	{ NWAM_OBJECT_TYPE_ENM, NULL, enm_event_methods,
	PTHREAD_RWLOCK_INITIALIZER },
	{ NWAM_OBJECT_TYPE_KNOWN_WLAN, NULL, known_wlan_event_methods,
	PTHREAD_RWLOCK_INITIALIZER }
};

uu_list_pool_t *object_list_pool = NULL;

/*
 * Comparison function for objects, passed in as callback to
 * uu_list_pool_create().
 */
/* ARGSUSED */
static int
nwamd_object_compare(const void *l_arg, const void *r_arg, void *private)
{
	nwamd_object_t l = (nwamd_object_t)l_arg;
	nwamd_object_t r = (nwamd_object_t)r_arg;
	int rv;

	(void) pthread_mutex_lock(&l->nwamd_object_mutex);
	if (l != r)
		(void) pthread_mutex_lock(&r->nwamd_object_mutex);

	rv = strcmp(l->nwamd_object_name, r->nwamd_object_name);
	if (l != r)
		(void) pthread_mutex_unlock(&r->nwamd_object_mutex);
	(void) pthread_mutex_unlock(&l->nwamd_object_mutex);

	return (rv);
}

void
nwamd_object_lists_init(void)
{
	int i;

	object_list_pool = uu_list_pool_create("object_list_pool",
	    sizeof (struct nwamd_object),
	    offsetof(struct nwamd_object, nwamd_object_node),
	    nwamd_object_compare, UU_LIST_POOL_DEBUG);
	if (object_list_pool == NULL)
		pfail("uu_list_pool_create failed with error %d", uu_error());

	for (i = 0;
	    i < sizeof (object_lists) / sizeof (struct nwamd_object_list);
	    i++) {
		object_lists[i].object_list = uu_list_create(object_list_pool,
		    NULL, 0);
		if (object_lists[i].object_list == NULL)
			pfail("uu_list_create failed with error %d",
			    uu_error());
	}
}

void
nwamd_object_lists_fini(void)
{
	int i;
	nwamd_object_t object;
	void *cookie = NULL;

	for (i = 0;
	    i < sizeof (object_lists) / sizeof (struct nwamd_object_list);
	    i++) {
		while ((object = uu_list_teardown(object_lists[i].object_list,
		    &cookie)) != NULL) {
			free(object);
		}
		uu_list_destroy(object_lists[i].object_list);
	}
	if (object_list_pool != NULL)
		uu_list_pool_destroy(object_list_pool);
}

static nwamd_object_list_t *
nwamd_get_object_list(nwam_object_type_t type)
{
	assert(type < sizeof (object_lists) / sizeof (object_lists[0]));
	return (&object_lists[type]);
}

static int
nwamd_object_list_lock(nwam_object_type_t type)
{
	nwamd_object_list_t *object_list = nwamd_get_object_list(type);

	(void) pthread_rwlock_wrlock(&object_list->object_list_lock);
	return (0);
}

static int
nwamd_object_list_rlock(nwam_object_type_t type)
{
	nwamd_object_list_t *object_list = nwamd_get_object_list(type);

	if (pthread_rwlock_rdlock(&object_list->object_list_lock) == -1) {
		nlog(LOG_ERR, "cannot get lock for object list: %s",
		    strerror(errno));
		return (-1);
	}
	return (0);
}

static void
nwamd_object_list_unlock(nwam_object_type_t type)
{
	nwamd_object_list_t *object_list = nwamd_get_object_list(type);

	(void) pthread_rwlock_unlock(&object_list->object_list_lock);
}

/*
 * Initialize object and return it in locked state.
 */
nwamd_object_t
nwamd_object_init(nwam_object_type_t type, const char *name, void *handle,
    void *data)
{
	nwamd_object_t object;
	struct nwamd_object_list *object_list = nwamd_get_object_list(type);

	object = calloc(1, sizeof (struct nwamd_object));
	if (object == NULL)
		return (NULL);

	(void) strlcpy(object->nwamd_object_name, name, NWAM_MAX_NAME_LEN);

	/* 1 for the list and 1 for the returned object */
	object->nwamd_object_refcount = 2;
	object->nwamd_object_handle = handle;
	object->nwamd_object_data = data;
	object->nwamd_object_type = type;
	object->nwamd_object_state = NWAM_STATE_INITIALIZED;
	object->nwamd_object_aux_state = NWAM_AUX_STATE_INITIALIZED;

	/* Add object to appropriate object list */
	if (nwamd_object_list_lock(type) != 0) {
		nlog(LOG_ERR, "nwamd_object_init: could not lock list to init "
		    "object %s", name);
		free(object);
		return (NULL);
	}

	if (pthread_mutex_init(&object->nwamd_object_mutex, NULL) == -1) {
		nlog(LOG_ERR, "pthread_mutex_init failed: %s",
		    strerror(errno));
		free(object);
		nwamd_object_list_unlock(type);
		return (NULL);
	}
	(void) pthread_mutex_lock(&object->nwamd_object_mutex);

	uu_list_node_init(object, &object->nwamd_object_node, object_list_pool);
	(void) uu_list_insert_after(object_list->object_list,
	    uu_list_last(object_list->object_list), object);

	nwamd_object_list_unlock(type);

	return (object);
}

/*
 * Find object in object list, returning it holding a lock and with the
 * reference count incremented.  The opposite function to this is
 * nwamd_object_release().
 */
nwamd_object_t
nwamd_object_find(nwam_object_type_t type, const char *name)
{
	nwamd_object_t object;
	struct nwamd_object_list *object_list = nwamd_get_object_list(type);

	assert(name != NULL);

	if (nwamd_object_list_rlock(type) != 0)
		return (NULL);

	for (object = uu_list_first(object_list->object_list);
	    object != NULL;
	    object = uu_list_next(object_list->object_list, object)) {
		if (strcmp(object->nwamd_object_name, name) == 0)
			break;
	}
	if (object != NULL) {
		(void) pthread_mutex_lock(&object->nwamd_object_mutex);
		object->nwamd_object_refcount++;
	}
	nwamd_object_list_unlock(type);

	return (object);
}

/* Removes object from list, destroy mutex, and free storage. */
static void
nwamd_object_fini(nwamd_object_t object, nwam_object_type_t objtype)
{
	nwamd_object_t o;
	struct nwamd_object_list *object_list;

	assert(object != NULL);

	object_list = nwamd_get_object_list(objtype);

	for (o = uu_list_first(object_list->object_list);
	    o != NULL;
	    o = uu_list_next(object_list->object_list, o)) {
		if (o == object) {
			uu_list_remove(object_list->object_list, object);
			(void) pthread_mutex_unlock(
			    &object->nwamd_object_mutex);
			(void) pthread_mutex_destroy(
			    &object->nwamd_object_mutex);
			uu_list_node_fini(object, &object->nwamd_object_node,
			    object_list_pool);
			switch (objtype) {
			case NWAM_OBJECT_TYPE_NCU:
				nwamd_ncu_free(object->nwamd_object_data);
				nwam_ncu_free(object->nwamd_object_handle);
				break;
			case NWAM_OBJECT_TYPE_LOC:
				nwam_loc_free(object->nwamd_object_handle);
				break;
			case NWAM_OBJECT_TYPE_ENM:
				nwam_enm_free(object->nwamd_object_handle);
				break;
			default:
				nlog(LOG_ERR, "nwamd_object_fini: "
				    "got unexpected object type %d", objtype);
				break;
			}
			free(object);
			break;
		}
	}
}

static void
nwamd_object_decref(nwamd_object_t object, int num)
{
	nwam_object_type_t objtype;

	assert(object->nwamd_object_refcount >= num);
	object->nwamd_object_refcount -= num;
	if (object->nwamd_object_refcount == 0) {
		/*
		 * We need to maintain the locking hierarchy of owning the
		 * list lock before we get the object lock when we are
		 * destroying the object.  If we merely release and then
		 * reacquire in the right order we might not find the right
		 * object.  Instead we bump the ref count so that it can't
		 * be destroyed, we drop the object lock, we acquire the
		 * list lock, we acquire the object lock, decrement the ref
		 * count, check to make sure we are really destroying it and
		 * somebody else hasn't gotten it, and then, if its unref'd,
		 * destroying it.
		 */
		object->nwamd_object_refcount++;
		objtype = object->nwamd_object_type;
		(void) pthread_mutex_unlock(&object->nwamd_object_mutex);
		(void) nwamd_object_list_lock(objtype);
		(void) pthread_mutex_lock(&object->nwamd_object_mutex);
		if (--object->nwamd_object_refcount != 0)
			(void) pthread_mutex_unlock(
			    &object->nwamd_object_mutex);
		else
			nwamd_object_fini(object, objtype);
		nwamd_object_list_unlock(objtype);
	} else {
		(void) pthread_mutex_unlock(&object->nwamd_object_mutex);
	}
}

/*
 * Drop mutex without decreasing reference count.  Used where we wish to
 * let go of an object but ensure it will not go away.
 */
void
nwamd_object_release_and_preserve(nwamd_object_t object)
{
	(void) pthread_mutex_unlock(&object->nwamd_object_mutex);
}

void
nwamd_object_release(nwamd_object_t object)
{
	nwamd_object_decref(object, 1);
}

void
nwamd_object_release_and_destroy(nwamd_object_t object)
{
	nwamd_object_decref(object, 2);
}

void
nwamd_object_release_and_destroy_after_preserve(nwamd_object_t object)
{
	nwamd_object_decref(object, 3);
}

void
nwamd_object_release_after_preserve(nwamd_object_t object)
{
	nwamd_object_decref(object, 2);
}

void
nwamd_object_set_state_timed(nwam_object_type_t type, const char *name,
    nwam_state_t state, nwam_aux_state_t aux_state, uint32_t when)
{
	nwamd_event_t event = nwamd_event_init_object_state(type, name,
	    state, aux_state);

	nlog(LOG_INFO, "nwamd_object_set_state: state event (%s, %s) for %s",
	    nwam_state_to_string(state),
	    nwam_aux_state_to_string(aux_state), name);
	if (event != NULL)
		nwamd_event_enqueue_timed(event, when);
}

void
nwamd_object_set_state(nwam_object_type_t type, const char *name,
    nwam_state_t state, nwam_aux_state_t aux_state)
{
	nwamd_object_set_state_timed(type, name, state, aux_state, 0);
}

nwamd_event_method_t *
nwamd_object_event_methods(nwam_object_type_t type)
{
	struct nwamd_object_list *object_list = nwamd_get_object_list(type);

	return (object_list->object_event_methods);
}

/*
 * Walk all objects of specified type calling callback function cb.
 * Object is locked for duration of callback.
 */
int
nwamd_walk_objects(nwam_object_type_t type, int (*cb)(nwamd_object_t, void *),
    void *data)
{
	nwamd_object_t object;
	struct nwamd_object_list *object_list = nwamd_get_object_list(type);
	int ret = 0;

	if (nwamd_object_list_rlock(type) != 0)
		return (-1);

	for (object = uu_list_first(object_list->object_list);
	    object != NULL;
	    object = uu_list_next(object_list->object_list, object)) {
		(void) pthread_mutex_lock(&object->nwamd_object_mutex);
		ret = cb(object, data);
		(void) pthread_mutex_unlock(&object->nwamd_object_mutex);
		if (ret != 0) {
			nwamd_object_list_unlock(type);
			return (ret);
		}
	}
	nwamd_object_list_unlock(type);

	return (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 2010 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _OBJECTS_H
#define	_OBJECTS_H

#include <door.h>
#include <libsysevent.h>
#include <libuutil.h>
#include <pthread.h>

#include <libnwam.h>
#include "events.h"
#include "ncp.h"
#include "ncu.h"

/*
 * Wrapper structure for libnwam object,  containing name, type,
 * associated object handle and optional object data field, and uu_list_node.
 */
struct nwamd_object {
	char nwamd_object_name[NWAM_MAX_NAME_LEN];
	nwam_object_type_t nwamd_object_type;

	/*
	 * These two elements provide a reference count for the structure and
	 * a lock for the data including reference count.
	 */
	int nwamd_object_refcount;
	pthread_mutex_t nwamd_object_mutex;

	void *nwamd_object_handle; /* can point at ENMs, locations, etc. */
	nwamd_ncu_t *nwamd_object_data;
	struct timeval nwamd_script_time;
	nwam_state_t nwamd_object_state;
	nwam_aux_state_t nwamd_object_aux_state;
	uu_list_node_t nwamd_object_node;
};

/* Object init/enqueueing */
extern void nwamd_object_lists_init(void);
extern void nwamd_object_lists_fini(void);
extern nwamd_object_t nwamd_object_init(nwam_object_type_t, const char *,
    void *, void *);
extern nwamd_object_t nwamd_object_find(nwam_object_type_t, const char *);
extern void nwamd_object_release_and_preserve(nwamd_object_t);
extern void nwamd_object_release(nwamd_object_t);
extern void nwamd_object_release_and_destroy(nwamd_object_t);
extern void nwamd_object_release_after_preserve(nwamd_object_t);
extern void nwamd_object_release_and_destroy_after_preserve(nwamd_object_t);
extern void nwamd_object_set_state(nwam_object_type_t, const char *,
    nwam_state_t, nwam_aux_state_t);
extern void nwamd_object_set_state_timed(nwam_object_type_t, const char *,
    nwam_state_t, nwam_aux_state_t, uint32_t);
extern nwamd_event_method_t *nwamd_object_event_methods(nwam_object_type_t);
extern int nwamd_walk_objects(nwam_object_type_t,
    int (*)(nwamd_object_t, void *), void *);
extern int nwamd_object_update(const char *, nwam_object_type_t);

/* Known WLAN functions (no wlan objects, so no init/fini functions) */
/* event methods */
extern void nwamd_known_wlan_handle_init_event(nwamd_event_t);

/* refresh/destroy a known WLAN */
extern int nwamd_known_wlan_action(const char *, nwam_action_t);

/* ENM functions */
/* Init/fini functions for ENMs */
extern void nwamd_init_enms(void);
extern void nwamd_fini_enms(void);

/* ENM condition check function */
extern void nwamd_enm_check_conditions(void);

/* event methods */
extern void nwamd_enm_handle_init_event(nwamd_event_t);
extern void nwamd_enm_handle_fini_event(nwamd_event_t);

/* enable/disable an enm */
extern int nwamd_enm_action(const char *, nwam_action_t);

/* reread an enm from the repository */
extern int nwamd_enm_refresh(const char *);

/* loc functions */
/* Init/fini functions for locs */
extern void nwamd_init_locs(void);
extern void nwamd_fini_locs(void);

/* loc condition check function */
extern void nwamd_loc_check_conditions(void);

/* on shutdown, revert to legacy location */
extern void nwamd_loc_revert_to_legacy(void);

/* event methods */
extern void nwamd_loc_handle_init_event(nwamd_event_t);
extern void nwamd_loc_handle_fini_event(nwamd_event_t);

/* enable/disable a loc */
extern int nwamd_loc_action(const char *, nwam_action_t);

/* reread a loc from the repository */
extern int nwamd_loc_refresh(const char *);

/* NCU functions */
extern void nwamd_init_ncus(void);
extern void nwamd_fini_ncus(void);

/* enable an ncp/ncu */
extern int nwamd_ncp_action(const char *, nwam_action_t);
extern int nwamd_ncu_action(const char *, const char *, nwam_action_t);

/*
 * Event callbacks.
 */
extern void nwamd_ncu_handle_init_event(nwamd_event_t);
extern void nwamd_ncu_handle_fini_event(nwamd_event_t);
extern void nwamd_ncu_handle_if_state_event(nwamd_event_t);
extern void nwamd_ncu_handle_if_action_event(nwamd_event_t);
extern void nwamd_ncu_handle_link_state_event(nwamd_event_t);
extern void nwamd_ncu_handle_link_action_event(nwamd_event_t);
extern void nwamd_ncu_handle_init_event(nwamd_event_t);
extern void nwamd_ncu_handle_fini_event(nwamd_event_t);
extern void nwamd_ncu_handle_action_event(nwamd_event_t);
extern void nwamd_ncu_handle_state_event(nwamd_event_t);

extern void nwamd_ncp_handle_action_event(nwamd_event_t);
extern void nwamd_ncp_handle_state_event(nwamd_event_t);
extern void nwamd_ncu_handle_periodic_scan_event(nwamd_event_t);
extern void nwamd_ncp_handle_enable_event(nwamd_event_t);
extern void nwamd_handle_upgrade(nwamd_event_t);

extern void nwamd_enm_handle_action_event(nwamd_event_t);
extern void nwamd_enm_handle_state_event(nwamd_event_t);

extern void nwamd_loc_handle_action_event(nwamd_event_t);
extern void nwamd_loc_handle_state_event(nwamd_event_t);

extern void nwamd_known_wlan_handle_action_event(nwamd_event_t);

extern void nwamd_add_phys_ncu_auto(nwam_ncp_handle_t, const char *);
extern void nwamd_rem_phys_ncu_auto(nwam_ncp_handle_t, const char *);
extern void add_auto_link(nwam_ncp_handle_t, const char *);
extern void add_auto_ip(nwam_ncp_handle_t, const char *);
extern void rem_auto_link(nwam_ncp_handle_t, const char *);
extern void rem_auto_ip(nwam_ncp_handle_t, const char *);

#endif /* _OBJECTS_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.
 */

#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <net/route.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/fcntl.h>
#include <unistd.h>

#include <libnwam.h>
#include "events.h"
#include "ncp.h"
#include "ncu.h"
#include "util.h"

/*
 * routing_events.c - this file contains routines to retrieve routing socket
 * events and package them for high level processing.
 */

#define	RTMBUFSZ	sizeof (struct rt_msghdr) + \
			(RTAX_MAX * sizeof (struct sockaddr_storage))

static void printaddrs(int, void *);
static char *printaddr(void **);
static void *getaddr(int, int, void *);
static void setaddr(int, int *, void *, struct sockaddr *);

union rtm_buf
{
	/* Routing information. */
	struct
	{
		struct rt_msghdr rtm;
		struct sockaddr_storage addr[RTAX_MAX];
	} r;

	/* Interface information. */
	struct
	{
		struct if_msghdr ifm;
		struct sockaddr_storage addr[RTAX_MAX];
	} im;

	/* Interface address information. */
	struct
	{
		struct ifa_msghdr ifa;
		struct sockaddr_storage addr[RTAX_MAX];
	} ia;
};

static int v4_sock = -1;
static int v6_sock = -1;
static pthread_t v4_routing, v6_routing;
static int seq = 0;

static const char *
rtmtype_str(int type)
{
	static char typestr[12]; /* strlen("type ") + enough for an int */

	switch (type) {
	case RTM_NEWADDR:
		return ("NEWADDR");
	case RTM_DELADDR:
		return ("DELADDR");
	case RTM_CHGADDR:
		return ("CHGADDR");
	case RTM_FREEADDR:
		return ("FREEADDR");
	default:
		(void) snprintf(typestr, sizeof (typestr), "type %d", type);
		return (typestr);
	}
}

/* ARGSUSED0 */
static void *
routing_events_v4(void *arg)
{
	int n;
	union rtm_buf buffer;
	struct rt_msghdr *rtm;
	struct ifa_msghdr *ifa;
	char *addrs, *if_name;
	struct sockaddr_dl *addr_dl;
	struct sockaddr *addr, *netmask;
	nwamd_event_t ip_event;

	nlog(LOG_DEBUG, "v4 routing socket %d", v4_sock);

	for (;;) {
		rtm = &buffer.r.rtm;
		n = read(v4_sock, &buffer, sizeof (buffer));
		if (n == -1 && errno == EAGAIN) {
			continue;
		} else if (n == -1) {
			nlog(LOG_ERR, "error reading routing socket "
			    "%d: %m", v4_sock);
			/* Low likelihood.  What's recovery path?  */
			continue;
		}

		if (rtm->rtm_msglen < n) {
			nlog(LOG_ERR, "only read %d bytes from "
			    "routing socket but message claims to be "
			    "of length %d", rtm->rtm_msglen);
			continue;
		}

		if (rtm->rtm_version != RTM_VERSION) {
			nlog(LOG_ERR, "tossing routing message of "
			    "version %d type %d", rtm->rtm_version,
			    rtm->rtm_type);
			continue;
		}

		if (rtm->rtm_msglen != n) {
			nlog(LOG_DEBUG, "routing message of %d size came from "
			    "read of %d on socket %d", rtm->rtm_msglen,
			    n, v4_sock);
		}

		switch (rtm->rtm_type) {
		case RTM_NEWADDR:
		case RTM_DELADDR:
		case RTM_CHGADDR:
		case RTM_FREEADDR:

			ifa = (void *)rtm;
			addrs = (char *)ifa + sizeof (*ifa);

			nlog(LOG_DEBUG, "v4 routing message %s: "
			    "index %d flags %x", rtmtype_str(rtm->rtm_type),
			    ifa->ifam_index, ifa->ifam_flags);

			if ((addr = (struct sockaddr *)getaddr(RTA_IFA,
			    ifa->ifam_addrs, addrs)) == NULL)
				break;

			/* Ignore routing socket messages for 0.0.0.0 */
			/*LINTED*/
			if (((struct sockaddr_in *)addr)->sin_addr.s_addr
			    == INADDR_ANY) {
				nlog(LOG_DEBUG, "routing_events_v4: "
				    "tossing message for 0.0.0.0");
				break;
			}

			if ((netmask = (struct sockaddr *)getaddr(RTA_NETMASK,
			    ifa->ifam_addrs, addrs)) == NULL)
				break;

			if ((addr_dl = (struct sockaddr_dl *)getaddr
			    (RTA_IFP, ifa->ifam_addrs, addrs)) == NULL)
				break;
			/*
			 * We don't use the lladdr in this structure so we can
			 * run over it.
			 */
			addr_dl->sdl_data[addr_dl->sdl_nlen] = 0;
			if_name = addr_dl->sdl_data; /* no lifnum */

			if (ifa->ifam_index == 0) {
				nlog(LOG_DEBUG, "tossing index 0 message");
				break;
			}
			if (ifa->ifam_type != rtm->rtm_type) {
				nlog(LOG_INFO,
				    "routing_events_v4: unhandled type %d",
				    ifa->ifam_type);
				break;
			}

			printaddrs(ifa->ifam_addrs, addrs);

			/* Create and enqueue IF_STATE event */
			ip_event = nwamd_event_init_if_state(if_name,
			    ifa->ifam_flags,
			    (rtm->rtm_type == RTM_NEWADDR ||
			    rtm->rtm_type == RTM_CHGADDR ? B_TRUE : B_FALSE),
			    addr, netmask);
			if (ip_event != NULL)
				nwamd_event_enqueue(ip_event);
			break;
		}
	}
	/* NOTREACHED */
	return (NULL);
}

/* ARGSUSED0 */
static void *
routing_events_v6(void *arg)
{
	int n;
	union rtm_buf buffer;
	struct rt_msghdr *rtm;
	struct ifa_msghdr *ifa;
	char *addrs, *if_name;
	struct sockaddr_dl *addr_dl;
	struct sockaddr *addr, *netmask;
	nwamd_event_t ip_event;

	nlog(LOG_DEBUG, "v6 routing socket %d", v6_sock);

	for (;;) {

		rtm = &buffer.r.rtm;
		n = read(v6_sock, &buffer, sizeof (buffer));
		if (n == -1 && errno == EAGAIN) {
			continue;
		} else if (n == -1) {
			nlog(LOG_ERR, "error reading routing socket "
			    "%d: %m", v6_sock);
			/* Low likelihood.  What's recovery path?  */
			continue;
		}

		if (rtm->rtm_msglen < n) {
			nlog(LOG_ERR, "only read %d bytes from "
			    "routing socket but message claims to be "
			    "of length %d", rtm->rtm_msglen);
			continue;
		}

		if (rtm->rtm_version != RTM_VERSION) {
			nlog(LOG_ERR, "tossing routing message of "
			    "version %d type %d", rtm->rtm_version,
			    rtm->rtm_type);
			continue;
		}

		if (rtm->rtm_msglen != n) {
			nlog(LOG_DEBUG, "routing message of %d size came from "
			    "read of %d on socket %d", rtm->rtm_msglen,
			    n, v6_sock);
		}

		switch (rtm->rtm_type) {
		case RTM_NEWADDR:
		case RTM_DELADDR:
		case RTM_CHGADDR:
		case RTM_FREEADDR:

			ifa = (void *)rtm;
			addrs = (char *)ifa + sizeof (*ifa);

			nlog(LOG_DEBUG, "v6 routing message %s: "
			    "index %d flags %x", rtmtype_str(rtm->rtm_type),
			    ifa->ifam_index, ifa->ifam_flags);

			if ((addr = (struct sockaddr *)getaddr(RTA_IFA,
			    ifa->ifam_addrs, addrs)) == NULL)
				break;

			/* Ignore routing socket messages for :: & linklocal */
			/*LINTED*/
			if (IN6_IS_ADDR_UNSPECIFIED(
			    &((struct sockaddr_in6 *)addr)->sin6_addr)) {
				nlog(LOG_INFO, "routing_events_v6: "
				    "tossing message for ::");
				break;
			}
			/*LINTED*/
			if (IN6_IS_ADDR_LINKLOCAL(
			    &((struct sockaddr_in6 *)addr)->sin6_addr)) {
				nlog(LOG_INFO, "routing_events_v6: "
				    "tossing message for link local address");
				break;
			}

			if ((netmask =
			    (struct sockaddr *)getaddr(RTA_NETMASK,
			    ifa->ifam_addrs, addrs)) == NULL)
				break;

			if ((addr_dl = (struct sockaddr_dl *)getaddr
			    (RTA_IFP, ifa->ifam_addrs, addrs)) == NULL)
				break;
			/*
			 * We don't use the lladdr in this structure so we can
			 * run over it.
			 */
			addr_dl->sdl_data[addr_dl->sdl_nlen] = 0;
			if_name = addr_dl->sdl_data; /* no lifnum */

			if (ifa->ifam_index == 0) {
				nlog(LOG_DEBUG, "tossing index 0 message");
				break;
			}
			if (ifa->ifam_type != rtm->rtm_type) {
				nlog(LOG_DEBUG,
				    "routing_events_v6: unhandled type %d",
				    ifa->ifam_type);
				break;
			}

			printaddrs(ifa->ifam_addrs, addrs);

			/* Create and enqueue IF_STATE event */
			ip_event = nwamd_event_init_if_state(if_name,
			    ifa->ifam_flags,
			    (rtm->rtm_type == RTM_NEWADDR ||
			    rtm->rtm_type == RTM_CHGADDR ? B_TRUE : B_FALSE),
			    addr, netmask);
			if (ip_event != NULL)
				nwamd_event_enqueue(ip_event);
			break;

		}
	}
	/* NOTREACHED */
	return (NULL);
}

void
nwamd_routing_events_init(void)
{
	pthread_attr_t attr;

	/*
	 * Initialize routing sockets here so that we know the routing threads
	 * (and any requests to add a route) will be working with a valid socket
	 * by the time we start handling events.
	 */
	v4_sock = socket(AF_ROUTE, SOCK_RAW, AF_INET);
	if (v4_sock == -1)
		pfail("failed to open v4 routing socket: %m");

	v6_sock = socket(AF_ROUTE, SOCK_RAW, AF_INET6);
	if (v6_sock == -1)
		pfail("failed to open v6 routing socket: %m");

	(void) pthread_attr_init(&attr);
	(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	if (pthread_create(&v4_routing, &attr, routing_events_v4, NULL) != 0 ||
	    pthread_create(&v6_routing, &attr, routing_events_v6, NULL) != 0)
		pfail("routing thread creation failed");
	(void) pthread_attr_destroy(&attr);
}

void
nwamd_routing_events_fini(void)
{
	(void) pthread_cancel(v4_routing);
	(void) pthread_cancel(v6_routing);
}

void
nwamd_add_route(struct sockaddr *dest, struct sockaddr *mask,
    struct sockaddr *gateway, const char *ifname)
{
	char rtbuf[RTMBUFSZ];
	/* LINTED E_BAD_PTR_CAST_ALIGN */
	struct rt_msghdr *rtm = (struct rt_msghdr *)rtbuf;
	void *addrs = rtbuf + sizeof (struct rt_msghdr);
	struct sockaddr_dl sdl;
	int rlen, index;
	int af;

	af = gateway->sa_family;

	/* retrieve the index value for the interface */
	if ((index = if_nametoindex(ifname)) == 0) {
		nlog(LOG_ERR, "nwamd_add_route: if_nametoindex failed on %s",
		    ifname);
		return;
	}

	(void) bzero(&sdl, sizeof (struct sockaddr_dl));
	sdl.sdl_family = AF_LINK;
	sdl.sdl_index = index;

	(void) bzero(rtm, RTMBUFSZ);
	rtm->rtm_pid = getpid();
	rtm->rtm_type = RTM_ADD;
	rtm->rtm_flags = RTF_UP | RTF_STATIC | RTF_GATEWAY;
	rtm->rtm_version = RTM_VERSION;
	rtm->rtm_seq = ++seq;
	rtm->rtm_msglen = sizeof (rtbuf);
	setaddr(RTA_DST, &rtm->rtm_addrs, &addrs, dest);
	setaddr(RTA_GATEWAY, &rtm->rtm_addrs, &addrs, gateway);
	setaddr(RTA_NETMASK, &rtm->rtm_addrs, &addrs, mask);
	setaddr(RTA_IFP, &rtm->rtm_addrs, &addrs, (struct sockaddr *)&sdl);

	if ((rlen = write(af == AF_INET ? v4_sock : v6_sock,
	    rtbuf, rtm->rtm_msglen)) < 0) {
		nlog(LOG_ERR, "nwamd_add_route: "
		    "got error %s writing to routing socket", strerror(errno));
	} else if (rlen < rtm->rtm_msglen) {
		nlog(LOG_ERR, "nwamd_add_route: "
		    "only wrote %d bytes of %d to routing socket\n",
		    rlen, rtm->rtm_msglen);
	}
}

static char *
printaddr(void **address)
{
	static char buffer[80];
	sa_family_t family = *(sa_family_t *)*address;
	struct sockaddr_in *s4 = *address;
	struct sockaddr_in6 *s6 = *address;
	struct sockaddr_dl *dl = *address;

	switch (family) {
	case AF_UNSPEC:
		(void) inet_ntop(AF_UNSPEC, &s4->sin_addr, buffer,
		    sizeof (buffer));
		*address = (char *)*address + sizeof (*s4);
		break;
	case AF_INET:
		(void) inet_ntop(AF_INET, &s4->sin_addr, buffer,
		    sizeof (buffer));
		*address = (char *)*address + sizeof (*s4);
		break;
	case AF_INET6:
		(void) inet_ntop(AF_INET6, &s6->sin6_addr, buffer,
		    sizeof (buffer));
		*address = (char *)*address + sizeof (*s6);
		break;
	case AF_LINK:
		(void) snprintf(buffer, sizeof (buffer), "link %.*s",
		    dl->sdl_nlen, dl->sdl_data);
		*address = (char *)*address + sizeof (*dl);
		break;
	default:
		/*
		 * We can't reliably update the size of this thing
		 * because we don't know what its type is.  So bump
		 * it by a sockaddr_in and see what happens.  The
		 * caller should really make sure this never happens.
		 */
		*address = (char *)*address + sizeof (*s4);
		(void) snprintf(buffer, sizeof (buffer),
		    "unknown address family %d", family);
		break;
	}
	return (buffer);
}

static void
printaddrs(int mask, void *address)
{
	if (mask == 0)
		return;
	if (mask & RTA_DST)
		nlog(LOG_DEBUG, "destination address: %s", printaddr(&address));
	if (mask & RTA_GATEWAY)
		nlog(LOG_DEBUG, "gateway address: %s", printaddr(&address));
	if (mask & RTA_NETMASK)
		nlog(LOG_DEBUG, "netmask: %s", printaddr(&address));
	if (mask & RTA_GENMASK)
		nlog(LOG_DEBUG, "cloning mask: %s", printaddr(&address));
	if (mask & RTA_IFP)
		nlog(LOG_DEBUG, "interface name: %s", printaddr(&address));
	if (mask & RTA_IFA)
		nlog(LOG_DEBUG, "interface address: %s", printaddr(&address));
	if (mask & RTA_AUTHOR)
		nlog(LOG_DEBUG, "author: %s", printaddr(&address));
	if (mask & RTA_BRD)
		nlog(LOG_DEBUG, "broadcast address: %s", printaddr(&address));
}

static void
nextaddr(void **address)
{
	sa_family_t family = *(sa_family_t *)*address;

	switch (family) {
	case AF_UNSPEC:
	case AF_INET:
		*address = (char *)*address + sizeof (struct sockaddr_in);
		break;
	case AF_INET6:
		*address = (char *)*address + sizeof (struct sockaddr_in6);
		break;
	case AF_LINK:
		*address = (char *)*address + sizeof (struct sockaddr_dl);
		break;
	default:
		nlog(LOG_ERR, "unknown af (%d) while parsing rtm", family);
		break;
	}
}

static void *
getaddr(int addrid, int mask, void *addresses)
{
	int i;
	void *p = addresses;

	if ((mask & addrid) == 0)
		return (NULL);

	for (i = 1; i < addrid; i <<= 1) {
		if (i & mask)
			nextaddr(&p);
	}
	return (p);
}

static void
setaddr(int addrid, int *maskp, void *addressesp, struct sockaddr *address)
{
	struct sockaddr *p = *((struct sockaddr **)addressesp);

	*maskp |= addrid;

	switch (address->sa_family) {
	case AF_INET:
		(void) memcpy(p, address, sizeof (struct sockaddr_in));
		break;
	case AF_INET6:
		(void) memcpy(p, address, sizeof (struct sockaddr_in6));
		break;
	case AF_LINK:
		(void) memcpy(p, address, sizeof (struct sockaddr_dl));
		break;
	default:
		nlog(LOG_ERR, "setaddr: unknown af (%d) while setting addr",
		    address->sa_family);
		break;
	}
	nextaddr(addressesp);
}
/*
 * 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.
 */

#include <assert.h>
#include <errno.h>
#include <libsysevent.h>
#include <sys/sysevent/eventdefs.h>
#include <sys/sysevent/dev.h>
#include <sys/types.h>
#include <libnvpair.h>
#include <string.h>
#include <unistd.h>

#include "events.h"
#include "ncp.h"
#include "ncu.h"
#include "objects.h"
#include "util.h"

/*
 * sysevent_events.c - this file contains routines to retrieve sysevents
 * from the system and package them for high level processing.
 */

static sysevent_handle_t *sysevent_handle;

/*
 * At present, we only handle EC_DEV_ADD/EC_DEV_REMOVE sysevents of
 * subclass ESC_NETWORK.  These signify hotplug addition/removal.
 * For EC_DEV_ADD, we:
 *      - extract the driver/instance sysevent attributes
 *      - combine these to get interface name and create associated NCUs
 *      at the link/IP level if required
 *      - enable those instances
 * For EC_DEV_REMOVE, we:
 *      - disable the associated link/IP NCUs
 */
static void
sysevent_handler(sysevent_t *ev)
{
	int32_t instance;
	char *driver;
	char if_name[LIFNAMSIZ];
	boolean_t link_added;
	nvlist_t *attr_list;
	char *event_class = sysevent_get_class_name(ev);
	char *event_subclass = sysevent_get_subclass_name(ev);
	nwamd_event_t link_event = NULL;

	nlog(LOG_DEBUG, "sysevent_handler: event %s/%s", event_class,
	    event_subclass);

	/* Make sure sysevent is of expected class/subclass */
	if ((strcmp(event_class, EC_DEV_ADD) != 0 &&
	    strcmp(event_class, EC_DEV_REMOVE) != 0) ||
	    strcmp(event_subclass, ESC_NETWORK) != 0) {
		nlog(LOG_ERR, "sysevent_handler: unexpected sysevent "
		    "class/subclass %s/%s", event_class, event_subclass);
		return;
	}

	link_added = (strcmp(event_class, EC_DEV_ADD) == 0);

	/*
	 * Retrieve driver name and instance attributes, and combine to
	 * get interface name.
	 */
	if (sysevent_get_attr_list(ev, &attr_list) != 0) {
		nlog(LOG_ERR, "sysevent_handler: sysevent_get_attr_list: %m");
		return;
	}
	if (nvlist_lookup_string(attr_list, DEV_DRIVER_NAME, &driver) != 0 ||
	    nvlist_lookup_int32(attr_list, DEV_INSTANCE, &instance) != 0) {
		nlog(LOG_ERR, "sysevent_handler: nvlist_lookup "
		    "of attributes failed: %m");
		nvlist_free(attr_list);
		return;
	}
	(void) snprintf(if_name, LIFNAMSIZ, "%s%d", driver, instance);
	nvlist_free(attr_list);

	/* Ignore sysevent events for other zones */
	if (!nwamd_link_belongs_to_this_zone(if_name))
		return;

	/* Create event for link */
	link_event = nwamd_event_init_link_action(if_name,
	    link_added ? NWAM_ACTION_ADD : NWAM_ACTION_REMOVE);
	if (link_event != NULL)
		nwamd_event_enqueue(link_event);
}

/* ARGSUSED0 */
static void *
sysevent_initialization(void *arg)
{
	const char *subclass = ESC_NETWORK;

	do {
		nwamd_escalate();
		sysevent_handle = sysevent_bind_handle(sysevent_handler);
		nwamd_deescalate();

		(void) sleep(1);
	} while (sysevent_handle == NULL);

	/*
	 * Subscribe to ESC_NETWORK subclass of EC_DEV_ADD and EC_DEV_REMOVE
	 * events.  As a result,  we get sysevent notification of hotplug
	 * add/remove events,  which we handle above in sysevent_handler().
	 */
	if (sysevent_subscribe_event(sysevent_handle, EC_DEV_ADD, &subclass, 1)
	    != 0 ||
	    sysevent_subscribe_event(sysevent_handle, EC_DEV_REMOVE, &subclass,
	    1) != 0)
		pfail("sysevent_subscribe_event: %s", strerror(errno));

	return (NULL);
}

/*
 * We can't initialize in the main thread because we may need to wait until
 * svc:/system/sysevent:default finishes starting up.  So we create a thread to
 * initialize in.
 */
void
nwamd_sysevent_events_init(void)
{
	int rc;
	pthread_attr_t attr;

	rc = pthread_attr_init(&attr);
	if (rc != 0) {
		pfail("nwamd_sysevents_init: pthread_attr_init failed: %s",
		    strerror(rc));
	}

	rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	if (rc != 0) {
		pfail("nwamd_sysevents_init: pthread_attr_setdetachstate "
		    "failed: %s", strerror(rc));
	}

	rc = pthread_create(NULL, &attr, sysevent_initialization, NULL);
	if (rc != 0) {
		pfail("nwamd_sysevents_init: couldn't start sysevent init "
		    "thread: %s", strerror(rc));
	}

	(void) pthread_attr_destroy(&attr);
}

void
nwamd_sysevent_events_fini(void)
{
	if (sysevent_handle != NULL) {
		nwamd_escalate();
		sysevent_unbind_handle(sysevent_handle);
		nwamd_deescalate();
	}
	sysevent_handle = NULL;
}
/*
 * 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.
 */

/*
 * util.c contains a set of miscellaneous utility functions which,
 * among other things:
 * - start a child process
 * - look up the zone name
 * - look up/set SMF properties
 * - drop/escalate privs
 */

#include <assert.h>
#include <errno.h>
#include <libdllink.h>
#include <limits.h>
#include <libscf.h>
#include <net/if.h>
#include <pthread.h>
#include <pwd.h>
#include <spawn.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stropts.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
#include <zone.h>

#include "util.h"
#include "llp.h"

extern char **environ;
extern sigset_t original_sigmask;

/*
 * A holder for all the resources needed to get a property value
 * using libscf.
 */
typedef struct scf_resources {
	scf_handle_t *sr_handle;
	scf_instance_t *sr_inst;
	scf_snapshot_t *sr_snap;
	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;

static pthread_mutex_t uid_mutex = PTHREAD_MUTEX_INITIALIZER;
static uid_t uid;
static int uid_cnt;

void
nwamd_escalate(void) {
	priv_set_t *priv_set;
	priv_set = priv_str_to_set("zone", ",", NULL);

	if (priv_set == NULL)
		pfail("creating privilege set: %s", strerror(errno));

	(void) pthread_mutex_lock(&uid_mutex);
	if (uid == 0)
		uid = getuid();
	if (uid_cnt++ == 0) {
		if (setppriv(PRIV_SET, PRIV_EFFECTIVE, priv_set) == -1) {
			priv_freeset(priv_set);
			pfail("setppriv effective: %s", strerror(errno));
		}
	}
	(void) pthread_mutex_unlock(&uid_mutex);

	priv_freeset(priv_set);
}

void
nwamd_deescalate(void) {
	(void) pthread_mutex_lock(&uid_mutex);

	assert(uid_cnt > 0);
	if (--uid_cnt == 0) {
		priv_set_t *priv_set, *allpriv_set;

		/* build up our minimal set of privs. */
		priv_set = priv_str_to_set("basic", ",", NULL);
		allpriv_set = priv_str_to_set("zone", ",", NULL);
		if (priv_set == NULL || allpriv_set == NULL)
			pfail("converting privilege sets: %s", strerror(errno));

		(void) priv_addset(priv_set, PRIV_FILE_CHOWN_SELF);
		(void) priv_addset(priv_set, PRIV_FILE_DAC_READ);
		(void) priv_addset(priv_set, PRIV_FILE_DAC_WRITE);
		(void) priv_addset(priv_set, PRIV_NET_RAWACCESS);
		(void) priv_addset(priv_set, PRIV_NET_PRIVADDR);
		(void) priv_addset(priv_set, PRIV_PROC_AUDIT);
		(void) priv_addset(priv_set, PRIV_PROC_OWNER);
		(void) priv_addset(priv_set, PRIV_PROC_SETID);
		(void) priv_addset(priv_set, PRIV_SYS_CONFIG);
		(void) priv_addset(priv_set, PRIV_SYS_IP_CONFIG);
		(void) priv_addset(priv_set, PRIV_SYS_IPC_CONFIG);
		(void) priv_addset(priv_set, PRIV_SYS_MOUNT);
		(void) priv_addset(priv_set, PRIV_SYS_NET_CONFIG);
		(void) priv_addset(priv_set, PRIV_SYS_RES_CONFIG);
		(void) priv_addset(priv_set, PRIV_SYS_RESOURCE);

		/*
		 * Since our zone might not have all these privs,
		 * just ask for those that are available.
		 */
		priv_intersect(allpriv_set, priv_set);

		if (setppriv(PRIV_SET, PRIV_INHERITABLE, priv_set) == -1) {
			priv_freeset(allpriv_set);
			priv_freeset(priv_set);
			pfail("setppriv inheritable: %s", strerror(errno));
		}
		/*
		 * Need to ensure permitted set contains all privs so we can
		 * escalate later.
		 */
		if (setppriv(PRIV_SET, PRIV_PERMITTED, allpriv_set) == -1) {
			priv_freeset(allpriv_set);
			priv_freeset(priv_set);
			pfail("setppriv permitted: %s", strerror(errno));
		}
		/*
		 * We need to find a smaller set of privs that are important to
		 * us.  Otherwise we really are not gaining much by doing this.
		 */
		if (setppriv(PRIV_SET, PRIV_EFFECTIVE, priv_set) == -1) {
			priv_freeset(allpriv_set);
			priv_freeset(priv_set);
			pfail("setppriv effective: %s", strerror(errno));
		}

		priv_freeset(priv_set);
		priv_freeset(allpriv_set);
	}
	(void) pthread_mutex_unlock(&uid_mutex);
}

/*
 *
 * This starts a child process determined by command.  If command contains a
 * slash then it is assumed to be a full path; otherwise the path is searched
 * for an executable file with the name command.  Command is also used as
 * argv[0] of the new process.  The rest of the arguments of the function
 * up to the first NULL make up pointers to arguments of the new process.
 *
 * This function returns child exit status on success and -1 on failure.
 *
 * NOTE: original_sigmask must be set before this function is called.
 */
int
nwamd_start_childv(const char *command, char const * const *argv)
{
	posix_spawnattr_t attr;
	sigset_t fullset;
	int i, rc, status, n;
	pid_t pid;
	char vbuf[1024];

	vbuf[0] = 0;
	n = sizeof (vbuf);
	for (i = 1; argv[i] != NULL && n > 2; i++) {
		n -= strlcat(vbuf, " ", n);
		n -= strlcat(vbuf, argv[i], n);
	}
	if (argv[i] != NULL || n < 0)
		nlog(LOG_ERR, "nwamd_start_childv can't log full arg vector");

	if ((rc = posix_spawnattr_init(&attr)) != 0) {
		nlog(LOG_DEBUG, "posix_spawnattr_init %d %s\n",
		    rc, strerror(rc));
		return (-1);
	}
	(void) sigfillset(&fullset);
	if ((rc = posix_spawnattr_setsigdefault(&attr, &fullset)) != 0) {
		nlog(LOG_DEBUG, "setsigdefault %d %s\n", rc, strerror(rc));
		return (-1);
	}
	if ((rc = posix_spawnattr_setsigmask(&attr, &original_sigmask)) != 0) {
		nlog(LOG_DEBUG, "setsigmask %d %s\n", rc, strerror(rc));
		return (-1);
	}
	if ((rc = posix_spawnattr_setflags(&attr,
	    POSIX_SPAWN_SETSIGDEF|POSIX_SPAWN_SETSIGMASK)) != 0) {
		nlog(LOG_DEBUG, "setflags %d %s\n", rc, strerror(rc));
		return (-1);
	}

	if ((rc = posix_spawnp(&pid, command, NULL, &attr, (char * const *)argv,
	    environ)) > 0) {
		nlog(LOG_DEBUG, "posix_spawnp failed errno %d", rc);
		return (-1);
	}

	if ((rc = posix_spawnattr_destroy(&attr)) != 0) {
		nlog(LOG_DEBUG, "posix_spawn_attr_destroy %d %s\n",
		    rc, strerror(rc));
		return (-1);
	}

	(void) waitpid(pid, &status, 0);
	if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
		i = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
		nlog(LOG_ERR, "'%s%s' %s with signal %d (%s)", command, vbuf,
		    (WIFSIGNALED(status) ? "terminated" : "stopped"), i,
		    strsignal(i));
		return (-2);
	} else {
		nlog(LOG_INFO, "'%s%s' completed normally: %d", command, vbuf,
		    WEXITSTATUS(status));
		return (WEXITSTATUS(status));
	}
}

/*
 * For global zone, check if the link is used by a non-global
 * zone, note that the non-global zones doesn't need this check,
 * because zoneadm has taken care of this when the zone boots.
 * In the global zone, we ignore events for local-zone-owned links
 * since these are taken care of by the local zone's network
 * configuration services.
 */
boolean_t
nwamd_link_belongs_to_this_zone(const char *linkname)
{
	zoneid_t zoneid;
	char zonename[ZONENAME_MAX];
	int ret;

	zoneid = getzoneid();
	if (zoneid == GLOBAL_ZONEID) {
		datalink_id_t linkid;
		dladm_status_t status;
		char errstr[DLADM_STRSIZE];

		if ((status = dladm_name2info(dld_handle, linkname, &linkid,
		    NULL, NULL, NULL)) != DLADM_STATUS_OK) {
			nlog(LOG_DEBUG, "nwamd_link_belongs_to_this_zone: "
			    "could not get linkid for %s: %s",
			    linkname, dladm_status2str(status, errstr));
			return (B_FALSE);
		}
		zoneid = ALL_ZONES;
		ret = zone_check_datalink(&zoneid, linkid);
		if (ret == 0) {
			(void) getzonenamebyid(zoneid, zonename, ZONENAME_MAX);
			nlog(LOG_DEBUG, "nwamd_link_belongs_to_this_zone: "
			    "%s is used by non-global zone: %s",
			    linkname, zonename);
			return (B_FALSE);
		}
	}
	return (B_TRUE);
}

/*
 * Inputs:
 *   res is a pointer to the scf_resources_t to be released.
 */
static void
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_snapshot_destroy(res->sr_snap);
	scf_instance_destroy(res->sr_inst);
	(void) scf_handle_unbind(res->sr_handle);
	scf_handle_destroy(res->sr_handle);
}

/*
 * Inputs:
 *   fmri is the instance to look up
 * Outputs:
 *   res is a pointer to an scf_resources_t.  This is an internal
 *   structure that holds all the handles needed to get a specific
 *   property from the running snapshot; on a successful return it
 *   contains the scf_value_t that should be passed to the desired
 *   scf_value_get_foo() function, and must be freed after use by
 *   calling release_scf_resources().  On a failure return, any
 *   resources that may have been assigned to res are released, so
 *   the caller does not need to do any cleanup in the failure case.
 * Returns:
 *    0 on success
 *   -1 on failure
 */

static int
create_scf_resources(const char *fmri, scf_resources_t *res)
{
	res->sr_tx = NULL;
	res->sr_ent = NULL;
	res->sr_inst = NULL;
	res->sr_snap = 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;
	}
	if ((res->sr_snap = scf_snapshot_create(res->sr_handle)) == NULL) {
		goto failure;
	}
	if (scf_instance_get_snapshot(res->sr_inst, "running",
	    res->sr_snap) != 0) {
		goto failure;
	}
	if ((res->sr_pg = scf_pg_create(res->sr_handle)) == NULL) {
		goto failure;
	}
	if ((res->sr_prop = scf_property_create(res->sr_handle)) == NULL) {
		goto failure;
	}
	if ((res->sr_val = scf_value_create(res->sr_handle)) == NULL) {
		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;
	}
	return (0);

failure:
	nlog(LOG_ERR, "create_scf_resources failed: %s",
	    scf_strerror(scf_error()));
	release_scf_resources(res);
	return (-1);
}

/*
 * Inputs:
 *   fmri is the instance to look up
 *   pg is the property group to look up
 *   prop is the property within that group to look up
 *   running specifies if running snapshot is to be used
 * Outputs:
 *   res is a pointer to an scf_resources_t.  This is an internal
 *   structure that holds all the handles needed to get a specific
 *   property from the running snapshot; on a successful return it
 *   contains the scf_value_t that should be passed to the desired
 *   scf_value_get_foo() function, and must be freed after use by
 *   calling release_scf_resources().  On a failure return, any
 *   resources that may have been assigned to res are released, so
 *   the caller does not need to do any cleanup in the failure case.
 * Returns:
 *    0 on success
 *   -1 on failure
 */
static int
get_property_value(const char *fmri, const char *pg, const char *prop,
    boolean_t running, scf_resources_t *res)
{
	if (create_scf_resources(fmri, res) != 0)
		return (-1);

	if (scf_instance_get_pg_composed(res->sr_inst,
	    running ? res->sr_snap : NULL, pg, res->sr_pg) != 0) {
		goto failure;
	}
	if (scf_pg_get_property(res->sr_pg, prop, res->sr_prop) != 0) {
		goto failure;
	}
	if (scf_property_get_value(res->sr_prop, res->sr_val) != 0) {
		goto failure;
	}
	return (0);

failure:
	release_scf_resources(res);
	return (-1);
}

/*
 * Inputs:
 *   lfmri is the instance fmri to look up
 *   lpg is the property group to look up
 *   lprop is the property within that group to look up
 * Outputs:
 *   answer is a pointer to the property value
 * Returns:
 *    0 on success
 *   -1 on failure
 * If successful, the property value is retured in *answer.
 * Otherwise, *answer is undefined, and it is up to the caller to decide
 * how to handle that case.
 */
int
nwamd_lookup_boolean_property(const char *lfmri, const char *lpg,
    const char *lprop, boolean_t *answer)
{
	int result = -1;
	scf_resources_t res;
	uint8_t prop_val;

	if (get_property_value(lfmri, lpg, lprop, B_TRUE, &res) != 0) {

		/*
		 * an error was already logged by get_property_value,
		 * and it released any resources assigned to res before
		 * returning.
		 */
		return (result);
	}
	if (scf_value_get_boolean(res.sr_val, &prop_val) != 0) {
		goto cleanup;
	}
	*answer = (boolean_t)prop_val;
	result = 0;
cleanup:
	release_scf_resources(&res);
	return (result);
}

/*
 * Inputs:
 *   lfmri is the instance fmri to look up
 *   lpg is the property group to look up
 *   lprop is the property within that group to look up
 *   buf is the place to put the answer
 *   bufsz is the size of buf
 * Outputs:
 *
 * Returns:
 *    0 on success
 *   -1 on failure
 * If successful, the property value is retured in buf.
 * Otherwise, buf is undefined, and it is up to the caller to decide
 * how to handle that case.
 */
int
nwamd_lookup_string_property(const char *lfmri, const char *lpg,
    const char *lprop, char *buf, size_t bufsz)
{
	int result = -1;
	scf_resources_t res;

	if (get_property_value(lfmri, lpg, lprop, B_TRUE, &res) != 0) {
		/*
		 * The above function fails when trying to get a
		 * non-persistent property group from the running snapshot.
		 * Try going for the non-running snapshot.
		 */
		if (get_property_value(lfmri, lpg, lprop, B_FALSE, &res) != 0) {
			/*
			 * an error was already logged by get_property_value,
			 * and it released any resources assigned to res before
			 * returning.
			 */
			return (result);
		}
	}
	if (scf_value_get_astring(res.sr_val, buf, bufsz) == 0)
		goto cleanup;

	result = 0;
cleanup:
	release_scf_resources(&res);
	return (result);
}

/*
 * Inputs:
 *   lfmri is the instance fmri to look up
 *   lpg is the property group to look up
 *   lprop is the property within that group to look up
 * Outputs:
 *   answer is a pointer to the property value
 * Returns:
 *    0 on success
 *   -1 on failure
 * If successful, the property value is retured in *answer.
 * Otherwise, *answer is undefined, and it is up to the caller to decide
 * how to handle that case.
 */
int
nwamd_lookup_count_property(const char *lfmri, const char *lpg,
    const char *lprop, uint64_t *answer)
{
	int result = -1;
	scf_resources_t res;

	if (get_property_value(lfmri, lpg, lprop, B_TRUE, &res) != 0) {

		/*
		 * an error was already logged by get_property_value,
		 * and it released any resources assigned to res before
		 * returning.
		 */
		return (result);
	}
	if (scf_value_get_count(res.sr_val, answer) != 0) {
		goto cleanup;
	}
	result = 0;
cleanup:
	release_scf_resources(&res);
	return (result);
}

static int
set_property_value(scf_resources_t *res, const char *propname,
    scf_type_t proptype)
{
	int result = -1;
	boolean_t new;

retry:
	new = (scf_pg_get_property(res->sr_pg, propname, 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,
		    propname, proptype) == -1) {
			goto failure;
		}
	} else {
		if (scf_transaction_property_change(res->sr_tx, res->sr_ent,
		    propname, proptype) == -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;
		}
		nlog(LOG_INFO, "set_property_value: transaction commit failed "
		    "for %s; retrying", propname);
		goto retry;
	}
	if (result == -1)
		goto failure;
	return (0);

failure:
	return (-1);
}

int
nwamd_set_count_property(const char *fmri, const char *pg, const char *prop,
    uint64_t count)
{
	scf_resources_t res;

	if (create_scf_resources(fmri, &res) != 0)
		return (-1);

	if (scf_instance_add_pg(res.sr_inst, pg, SCF_GROUP_APPLICATION,
	    SCF_PG_FLAG_NONPERSISTENT, res.sr_pg) != 0) {
		if (scf_error() != SCF_ERROR_EXISTS)
			goto failure;
		if (scf_instance_get_pg_composed(res.sr_inst, NULL, pg,
		    res.sr_pg) != 0)
			goto failure;
	}

	scf_value_set_count(res.sr_val, (uint64_t)count);

	if (set_property_value(&res, prop, SCF_TYPE_COUNT) != 0)
		goto failure;

	release_scf_resources(&res);
	return (0);

failure:
	nlog(LOG_INFO, "nwamd_set_count_property: scf failure %s while "
	    "setting %s", scf_strerror(scf_error()), prop);
	release_scf_resources(&res);
	return (-1);
}

int
nwamd_set_string_property(const char *fmri, const char *pg, const char *prop,
    const char *str)
{
	scf_resources_t res;

	if (create_scf_resources(fmri, &res) != 0)
		return (-1);

	if (scf_instance_add_pg(res.sr_inst, pg, SCF_GROUP_APPLICATION,
	    SCF_PG_FLAG_NONPERSISTENT, res.sr_pg) != 0) {
		if (scf_error() != SCF_ERROR_EXISTS)
			goto failure;
		if (scf_instance_get_pg_composed(res.sr_inst, NULL, pg,
		    res.sr_pg) != 0)
			goto failure;
	}

	if (scf_value_set_astring(res.sr_val, str) != 0)
		goto failure;

	if (set_property_value(&res, prop, SCF_TYPE_ASTRING) != 0)
		goto failure;

	release_scf_resources(&res);
	return (0);

failure:
	nlog(LOG_INFO, "nwamd_set_string_property: scf failure %s while "
	    "setting %s", scf_strerror(scf_error()), prop);
	release_scf_resources(&res);
	return (-1);
}

/*
 * Deletes property prop from property group pg in SMF instance fmri.
 * Returns 0 on success, -1 on failure.
 */
int
nwamd_delete_scf_property(const char *fmri, const char *pg, const char *prop)
{
	scf_resources_t res;
	int result = -1;

	if (create_scf_resources(fmri, &res) != 0)
		return (-1);

	if (scf_instance_add_pg(res.sr_inst, pg, SCF_GROUP_APPLICATION,
	    SCF_PG_FLAG_NONPERSISTENT, res.sr_pg) != 0) {
		if (scf_error() != SCF_ERROR_EXISTS)
			goto failure;
		if (scf_instance_get_pg_composed(res.sr_inst, NULL, pg,
		    res.sr_pg) != 0)
			goto failure;
	}

	if (scf_pg_get_property(res.sr_pg, prop, res.sr_prop) != 0)
		goto failure;
retry:
	if (scf_transaction_start(res.sr_tx, res.sr_pg) == -1)
		goto failure;

	if (scf_transaction_property_delete(res.sr_tx, res.sr_ent, prop) == -1)
		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;

	release_scf_resources(&res);
	return (0);
failure:
	release_scf_resources(&res);
	return (-1);
}
/*
 * 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.
 */

#ifndef _UTIL_H
#define	_UTIL_H

#include <dhcpagent_ipc.h>
#include <libdlwlan.h>
#include <libnwam.h>
#include <pthread.h>
#include <string.h>
#include <sys/note.h>
#include <sys/time.h>
#include <sys/zone.h>
#include <syslog.h>

#include "events.h"
#include "llp.h"
#include "ncu.h"

/*
 * A few functions here from files other than util.c, saves having
 * .h files for one or two functions.
 */

#define	OUR_FMRI				NWAM_FMRI
#define	OUR_PG					NWAM_PG
#define	OUR_DEBUG_PROP_NAME			"debug"
#define	OUR_AUTOCONF_PROP_NAME			"autoconf"
#define	OUR_STRICT_BSSID_PROP_NAME		"strict_bssid"
#define	OUR_ACTIVE_NCP_PROP_NAME		NWAM_PROP_ACTIVE_NCP
#define	OUR_CONDITION_CHECK_INTERVAL_PROP_NAME	"condition_check_interval"
#define	OUR_WIRELESS_SCAN_INTERVAL_PROP_NAME	"scan_interval"
#define	OUR_WIRELESS_SCAN_LEVEL_PROP_NAME	"scan_level"
#define	OUR_NCU_WAIT_TIME_PROP_NAME		"ncu_wait_time"
#define	OUR_VERSION_PROP_NAME			"version"
#define	NET_LOC_FMRI				"svc:/network/location:default"
#define	NET_LOC_PG				"location"
#define	NET_LOC_SELECTED_PROP			"selected"

#define	NSEC_TO_SEC(nsec)	(nsec) / (long)NANOSEC
#define	NSEC_TO_FRACNSEC(nsec)	(nsec) % (long)NANOSEC
#define	SEC_TO_NSEC(sec)	(sec) * (long)NANOSEC

extern boolean_t debug;
extern boolean_t shutting_down;

/* logging.c: log support functions */
extern void nlog(int, const char *, ...);
extern void pfail(const char *fmt, ...);
extern int syslog_stack(uintptr_t addr, int sig, void *arg);

/* door_if.c: door interface functions */
extern void nwamd_door_init(void);
extern void nwamd_door_fini(void);

/* util.c: utility & ipc functions */
extern int nwamd_start_childv(const char *, const char * const *);
extern boolean_t nwamd_link_belongs_to_this_zone(const char *);
extern void nwamd_escalate(void);
extern void nwamd_deescalate(void);
extern void nwamd_drop_unneeded_privs(void);
extern void nwamd_escalate_privs(void);

/* SCF helper functions */
extern int nwamd_lookup_boolean_property(const char *, const char *,
    const char *, boolean_t *);
extern int nwamd_lookup_count_property(const char *, const char *, const char *,
    uint64_t *);
extern int nwamd_lookup_string_property(const char *, const char *,
    const char *, char *, size_t);

extern int nwamd_set_count_property(const char *, const char *, const char *,
    uint64_t);
extern int nwamd_set_string_property(const char *, const char *, const char *,
    const char *);

extern int nwamd_delete_scf_property(const char *, const char *, const char *);

#endif /* _UTIL_H */