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

include ../Makefile.lib

HDRS =		libinetutil.h
HDRDIR =	common
# Hammerhead: amd64-only
SUBDIRS = $(MACH64)

all :		TARGET = all
clean :	TARGET = clean
clobber :	TARGET = clobber
install	:	TARGET = install

.KEEP_STATE:

all clean clobber install: $(SUBDIRS)

install_h:	$(ROOTHDRS)

check:		$(CHECKHDRS)

$(SUBDIRS): FRC
	@cd $@; pwd; $(MAKE) $(TARGET)

FRC:

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 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# Copyright (c) 2018, Joyent, Inc.

LIBRARY = libinetutil.a
VERS =	  .1
OBJECTS = octet.o inetutil.o ifspec.o ifaddrlist.o ifaddrlistx.o eh.o tq.o

include ../../Makefile.lib

# install this library in the root filesystem
include ../../Makefile.rootfs

LIBS =		$(DYNLIB)

SRCDIR =	../common
COMDIR =	$(SRC)/common/net/dhcp
SRCS =		$(COMDIR)/octet.c $(SRCDIR)/inetutil.c \
		$(SRCDIR)/ifspec.c $(SRCDIR)/eh.c $(SRCDIR)/tq.c \
		$(SRCDIR)/ifaddrlist.c $(SRCDIR)/ifaddrlistx.c

LDLIBS +=	-lsocket -lc

CFLAGS +=	$(CCVERBOSE)
CPPFLAGS +=	-I$(SRCDIR)

CERRWARN +=	-Wno-parentheses

SMOFF += index_overflow

.KEEP_STATE:

all: $(LIBS)


pics/%.o: $(COMDIR)/%.c
	$(COMPILE.c) -o $@ $<
	$(POST_PROCESS_O)

include ../../Makefile.targ
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (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 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

#

include ../Makefile.com
include ../../Makefile.lib.64

install: all $(ROOTLIBS64) $(ROOTLINKS64) $(ROOTCOMPATLINKS64)
 * Copyright (c) 1997
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the Computer Systems
 *	Engineering Group at Lawrence Berkeley Laboratory.
 * 4. Neither the name of the University nor of the Laboratory may be used
 *    to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
IFADDR FILES
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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 2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stropts.h>	/* INFTIM */

#include <libinetutil.h>
#include "libinetutil_impl.h"

static int	grow_fds(iu_eh_t *, int);

/*
 * signal_to_eh[] is pretty much useless, since the event handler is
 * really a singleton (we pass iu_eh_t *'s around to maintain an
 * abstraction, not to allow multiple event handlers to exist).  we
 * need some way to get back our event handler in post_signal(),
 * and since the signal model is too lame to provide opaque pointers,
 * we have to resort to global variables.
 */

static iu_eh_t *signal_to_eh[NSIG];

/*
 * iu_eh_create(): creates, initializes, and returns an event handler for use
 *
 *   input: void
 *  output: iu_eh_t *: the new event handler
 */

iu_eh_t *
iu_eh_create(void)
{
	iu_eh_t	*eh = malloc(sizeof (iu_eh_t));
	int	sig;

	if (eh == NULL)
		return (NULL);

	eh->iueh_pollfds	= NULL;
	eh->iueh_events		= NULL;
	eh->iueh_shutdown	= NULL;
	eh->iueh_num_fds	= 0;
	eh->iueh_stop		= B_FALSE;
	eh->iueh_reason		= 0;
	eh->iueh_shutdown_arg	= NULL;

	(void) sigemptyset(&eh->iueh_sig_regset);
	for (sig = 0; sig < NSIG; sig++) {
		eh->iueh_sig_info[sig].iues_pending = B_FALSE;
		eh->iueh_sig_info[sig].iues_handler = NULL;
		eh->iueh_sig_info[sig].iues_data = NULL;
	}

	return (eh);
}

/*
 * iu_eh_destroy(): destroys an existing event handler
 *
 *   input: iu_eh_t *: the event handler to destroy
 *  output: void
 *   notes: it is assumed all events related to this eh have been unregistered
 *          prior to calling iu_eh_destroy()
 */

void
iu_eh_destroy(iu_eh_t *eh)
{
	int	sig;

	for (sig = 0; sig < NSIG; sig++)
		if (signal_to_eh[sig] == eh)
			(void) iu_eh_unregister_signal(eh, sig, NULL);

	free(eh->iueh_pollfds);
	free(eh->iueh_events);
	free(eh);
}

/*
 * iu_stop_handling_events(): informs the event handler to stop handling events
 *
 *   input: iu_eh_t *: the event handler to stop.
 *	    unsigned int: the (user-defined) reason why
 *          iu_eh_shutdown_t *: the shutdown callback. if it is NULL,
 *				the event handler will stop right away;
 *				otherwise, the event handler will not
 *				stop until the callback returns B_TRUE
 *	    void *: data for the shutdown callback. it may be NULL
 *  output: void
 *   notes: the event handler in question must be in iu_handle_events()
 */

void
iu_stop_handling_events(iu_eh_t *eh, unsigned int reason,
    iu_eh_shutdown_t *shutdown, void *arg)
{
	eh->iueh_stop   = B_TRUE;
	eh->iueh_reason = reason;
	eh->iueh_shutdown = shutdown;
	eh->iueh_shutdown_arg = arg;
}

/*
 * grow_fds(): grows the internal file descriptor set used by the event
 *		  handler
 *
 *   input: iu_eh_t *: the event handler whose descriptor set needs to be grown
 *          int: the new total number of descriptors needed in the set
 *  output: int: zero on failure, success otherwise
 */

static int
grow_fds(iu_eh_t *eh, int total_fds)
{
	unsigned int	i;
	struct pollfd	*new_pollfds;
	iu_event_node_t	*new_events;

	if (total_fds <= eh->iueh_num_fds)
		return (1);

	new_pollfds = realloc(eh->iueh_pollfds,
	    total_fds * sizeof (struct pollfd));
	if (new_pollfds == NULL)
		return (0);

	eh->iueh_pollfds = new_pollfds;

	new_events = realloc(eh->iueh_events,
	    total_fds * sizeof (iu_event_node_t));
	if (new_events == NULL) {

		/*
		 * yow.  one realloc failed, but the other succeeded.
		 * we will just leave the descriptor size at the
		 * original size.  if the caller tries again, then the
		 * first realloc() will do nothing since the requested
		 * number of descriptors is already allocated.
		 */

		return (0);
	}

	for (i = eh->iueh_num_fds; i < total_fds; i++)
		eh->iueh_pollfds[i].fd = -1;

	eh->iueh_events  = new_events;
	eh->iueh_num_fds = total_fds;
	return (1);
}

/*
 * when increasing the file descriptor set size, how much to increase by:
 */

#define	EH_FD_SLACK	10

/*
 * iu_register_event(): adds an event to the set managed by an event handler
 *
 *   input: iu_eh_t *: the event handler to add the event to
 *          int: the descriptor on which to listen for events.  must be
 *		 a descriptor which has not yet been registered.
 *          short: the events to listen for on that descriptor
 *          iu_eh_callback_t: the callback to execute when the event happens
 *          void *: the argument to pass to the callback function
 *  output: iu_event_id_t: -1 on failure, the new event id otherwise
 */

iu_event_id_t
iu_register_event(iu_eh_t *eh, int fd, short events, iu_eh_callback_t *callback,
    void *arg)
{
	if (eh->iueh_num_fds <= fd)
		if (grow_fds(eh, fd + EH_FD_SLACK) == 0)
			return (-1);

	/*
	 * the current implementation uses the file descriptor itself
	 * as the iu_event_id_t, since we know the kernel's gonna be
	 * pretty smart about managing file descriptors and we know
	 * that they're per-process unique.  however, it does mean
	 * that the same descriptor cannot be registered multiple
	 * times for different callbacks depending on its events.  if
	 * this behavior is desired, either use dup(2) to get a unique
	 * descriptor, or demultiplex in the callback function based
	 * on `events'.
	 */

	if (eh->iueh_pollfds[fd].fd != -1)
		return (-1);

	eh->iueh_pollfds[fd].fd 		= fd;
	eh->iueh_pollfds[fd].events		= events;
	eh->iueh_events[fd].iuen_callback	= callback;
	eh->iueh_events[fd].iuen_arg		= arg;

	return (fd);
}

/*
 * iu_unregister_event(): removes an event from the set managed by an event
 *			  handler
 *
 *   input: iu_eh_t *: the event handler to remove the event from
 *          iu_event_id_t: the event to remove (from iu_register_event())
 *          void **: if non-NULL, will be set to point to the argument passed
 *                   into iu_register_event()
 *  output: int: zero on failure, success otherwise
 */

int
iu_unregister_event(iu_eh_t *eh, iu_event_id_t event_id, void **arg)
{
	if (event_id < 0 || event_id >= eh->iueh_num_fds ||
	    eh->iueh_pollfds[event_id].fd == -1)
		return (0);

	/*
	 * fringe condition: in case this event was about to be called
	 * back in iu_handle_events(), zero revents to prevent it.
	 * (having an unregistered event get called back could be
	 * disastrous depending on if `arg' is reference counted).
	 */

	eh->iueh_pollfds[event_id].revents = 0;
	eh->iueh_pollfds[event_id].fd = -1;
	if (arg != NULL)
		*arg = eh->iueh_events[event_id].iuen_arg;

	return (1);
}

/*
 * iu_handle_events(): begins handling events on an event handler
 *
 *   input: iu_eh_t *: the event handler to begin event handling on
 *          tq_t *: a timer queue of timers to process while handling events
 *                  (see timer_queue.h for details)
 *  output: int: the reason why we stopped, -1 if due to internal failure
 */

int
iu_handle_events(iu_eh_t *eh, iu_tq_t *tq)
{
	int		n_lit, timeout, sig, saved_errno;
	unsigned int	i;
	sigset_t	oset;

	eh->iueh_stop = B_FALSE;
	do {
		timeout = tq ? iu_earliest_timer(tq) : INFTIM;

		/*
		 * we only unblock registered signals around poll(); this
		 * way other parts of the code don't have to worry about
		 * restarting "non-restartable" system calls and so forth.
		 */

		(void) sigprocmask(SIG_UNBLOCK, &eh->iueh_sig_regset, &oset);
		n_lit = poll(eh->iueh_pollfds, eh->iueh_num_fds, timeout);
		saved_errno = errno;
		(void) sigprocmask(SIG_SETMASK, &oset, NULL);

		switch (n_lit) {

		case -1:
			if (saved_errno != EINTR)
				return (-1);

			for (sig = 0; sig < NSIG; sig++) {
				if (eh->iueh_sig_info[sig].iues_pending) {
					eh->iueh_sig_info[sig].iues_pending =
					    B_FALSE;
					eh->iueh_sig_info[sig].iues_handler(eh,
					    sig,
					    eh->iueh_sig_info[sig].iues_data);
				}
			}

			if (eh->iueh_shutdown != NULL)
				break;

			continue;

		case  0:
			/*
			 * timeout occurred.  we must have a valid tq pointer
			 * since that's the only way a timeout can happen.
			 */

			(void) iu_expire_timers(tq);
			continue;

		default:
			break;
		}

		/* file descriptors are lit; call 'em back */

		for (i = 0; i < eh->iueh_num_fds && n_lit > 0; i++) {

			if (eh->iueh_pollfds[i].revents == 0)
				continue;

			n_lit--;

			/*
			 * turn off any descriptors that have gone
			 * bad.  shouldn't happen, but...
			 */

			if (eh->iueh_pollfds[i].revents & (POLLNVAL|POLLERR)) {
				/* TODO: issue a warning here - but how? */
				(void) iu_unregister_event(eh, i, NULL);
				continue;
			}

			eh->iueh_events[i].iuen_callback(eh, i,
			    eh->iueh_pollfds[i].revents, i,
			    eh->iueh_events[i].iuen_arg);
		}

	} while (eh->iueh_stop == B_FALSE || (eh->iueh_shutdown != NULL &&
	    eh->iueh_shutdown(eh, eh->iueh_shutdown_arg) == B_FALSE));

	return (eh->iueh_reason);
}

/*
 * post_signal(): posts a signal for later consumption in iu_handle_events()
 *
 *   input: int: the signal that's been received
 *  output: void
 */

static void
post_signal(int sig)
{
	if (signal_to_eh[sig] != NULL)
		signal_to_eh[sig]->iueh_sig_info[sig].iues_pending = B_TRUE;
}

/*
 * iu_eh_register_signal(): registers a signal handler with an event handler
 *
 *   input: iu_eh_t *: the event handler to register the signal handler with
 *	    int: the signal to register
 *	    iu_eh_sighandler_t *: the signal handler to call back
 *	    void *: the argument to pass to the signal handler function
 *   output: int: zero on failure, success otherwise
 */

int
iu_eh_register_signal(iu_eh_t *eh, int sig, iu_eh_sighandler_t *handler,
    void *data)
{
	struct sigaction	act;

	if (sig < 0 || sig >= NSIG || signal_to_eh[sig] != NULL)
		return (0);

	act.sa_flags = 0;
	act.sa_handler = &post_signal;
	(void) sigemptyset(&act.sa_mask);
	(void) sigaddset(&act.sa_mask, sig); /* used for sigprocmask() */

	if (sigaction(sig, &act, NULL) == -1)
		return (0);

	(void) sigprocmask(SIG_BLOCK, &act.sa_mask, NULL);

	eh->iueh_sig_info[sig].iues_data = data;
	eh->iueh_sig_info[sig].iues_handler = handler;
	signal_to_eh[sig] = eh;

	(void) sigaddset(&eh->iueh_sig_regset, sig);
	return (0);
}

/*
 * iu_eh_unregister_signal(): unregisters a signal handler from an event handler
 *
 *   input: iu_eh_t *: the event handler to unregister the signal handler from
 *	    int: the signal to unregister
 *	    void **: if non-NULL, will be set to point to the argument passed
 *		     into iu_eh_register_signal()
 *  output: int: zero on failure, success otherwise
 */

int
iu_eh_unregister_signal(iu_eh_t *eh, int sig, void **datap)
{
	sigset_t	set;

	if (sig < 0 || sig >= NSIG || signal_to_eh[sig] != eh)
		return (0);

	if (signal(sig, SIG_DFL) == SIG_ERR)
		return (0);

	if (datap != NULL)
		*datap = eh->iueh_sig_info[sig].iues_data;

	(void) sigemptyset(&set);
	(void) sigaddset(&set, sig);
	(void) sigprocmask(SIG_UNBLOCK, &set, NULL);

	eh->iueh_sig_info[sig].iues_data = NULL;
	eh->iueh_sig_info[sig].iues_handler = NULL;
	eh->iueh_sig_info[sig].iues_pending = B_FALSE;
	signal_to_eh[sig] = NULL;

	(void) sigdelset(&eh->iueh_sig_regset, sig);
	return (1);
}
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 1997
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the Computer Systems
 *	Engineering Group at Lawrence Berkeley Laboratory.
 * 4. Neither the name of the University nor of the Laboratory may be used
 *    to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * @(#) $Header: ifaddrlist.c,v 1.2 97/04/22 13:31:05 leres Exp $ (LBL)
 */

#include <errno.h>
#include <libinetutil.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/sockio.h>

/*
 * See <libinetutil.h> for a description of the programming interface.
 */
int
ifaddrlist(struct ifaddrlist **ipaddrp, int family, uint_t flags, char *errbuf)
{
	struct ifaddrlist	*ifaddrlist = NULL, *al = NULL;
	struct sockaddr_in	*sin;
	struct sockaddr_in6	*sin6;
	struct lifconf		lifc;
	struct lifnum		lifn;
	struct lifreq		*lifrp;
	int			i, count, nlifr;
	int			fd;
	const char		*opstr;

	(void) memset(&lifc, 0, sizeof (lifc));
	if (family != AF_INET && family != AF_INET6) {
		(void) strlcpy(errbuf, "invalid address family", ERRBUFSIZE);
		return (-1);
	}

	if ((fd = socket(family, SOCK_DGRAM, 0)) == -1) {
		opstr = "socket";
		goto fail;
	}

	/*
	 * Get the number of network interfaces of type `family'.
	 */
	lifn.lifn_family = family;
	lifn.lifn_flags = flags;
again:
	if (ioctl(fd, SIOCGLIFNUM, &lifn) == -1) {
		opstr = "SIOCGLIFNUM";
		goto fail;
	}

	/*
	 * Pad the interface count to detect when additional interfaces have
	 * been configured between SIOCGLIFNUM and SIOCGLIFCONF.
	 */
	lifn.lifn_count += 4;

	lifc.lifc_flags = flags;
	lifc.lifc_family = family;
	lifc.lifc_len = lifn.lifn_count * sizeof (struct lifreq);
	if ((lifc.lifc_buf = realloc(lifc.lifc_buf, lifc.lifc_len)) == NULL) {
		opstr = "realloc";
		goto fail;
	}

	if (ioctl(fd, SIOCGLIFCONF, &lifc) == -1) {
		opstr = "SIOCGLIFCONF";
		goto fail;
	}

	/*
	 * If every lifr_req slot is taken, then additional interfaces must
	 * have been plumbed between the SIOCGLIFNUM and the SIOCGLIFCONF.
	 * Recalculate to make sure we didn't miss any interfaces.
	 */
	nlifr = lifc.lifc_len / sizeof (struct lifreq);
	if (nlifr >= lifn.lifn_count)
		goto again;

	/*
	 * Allocate the address list to return.
	 */
	if ((ifaddrlist = calloc(nlifr, sizeof (struct ifaddrlist))) == NULL) {
		opstr = "calloc";
		goto fail;
	}

	/*
	 * Populate the address list by querying each underlying interface.
	 * If a query ioctl returns ENXIO, then the interface must have been
	 * removed after the SIOCGLIFCONF completed -- so we just ignore it.
	 */
	al = ifaddrlist;
	count = 0;
	for (lifrp = lifc.lifc_req, i = 0; i < nlifr; i++, lifrp++) {
		(void) strlcpy(al->device, lifrp->lifr_name, LIFNAMSIZ);

		if (ioctl(fd, SIOCGLIFFLAGS, lifrp) == -1) {
			if (errno == ENXIO)
				continue;
			opstr = "SIOCGLIFFLAGS";
			goto fail;
		}
		al->flags = lifrp->lifr_flags;

		if (ioctl(fd, SIOCGLIFINDEX, lifrp) == -1) {
			if (errno == ENXIO)
				continue;
			opstr = "SIOCGLIFINDEX";
			goto fail;
		}
		al->index = lifrp->lifr_index;

		if (ioctl(fd, SIOCGLIFADDR, lifrp) == -1) {
			if (errno == ENXIO)
				continue;
			opstr = "SIOCGLIFADDR";
			goto fail;
		}

		if (family == AF_INET) {
			sin = (struct sockaddr_in *)&lifrp->lifr_addr;
			al->addr.addr = sin->sin_addr;
		} else {
			sin6 = (struct sockaddr_in6 *)&lifrp->lifr_addr;
			al->addr.addr6 = sin6->sin6_addr;
		}
		al++;
		count++;
	}

	(void) close(fd);
	free(lifc.lifc_buf);
	if (count == 0) {
		free(ifaddrlist);
		*ipaddrp = NULL;
		return (0);
	}

	*ipaddrp = ifaddrlist;
	return (count);
fail:
	if (al == NULL) {
		(void) snprintf(errbuf, ERRBUFSIZE, "%s: %s", opstr,
		    strerror(errno));
	} else {
		(void) snprintf(errbuf, ERRBUFSIZE, "%s: %s: %s", opstr,
		    al->device, strerror(errno));
	}
	free(lifc.lifc_buf);
	free(ifaddrlist);
	(void) close(fd);
	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 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <errno.h>
#include <libinetutil.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/sockio.h>

/*
 * Create a list of the addresses on physical interface `ifname' with at least
 * one of the flags in `set' set and all of the flags in `clear' clear.
 * Return the number of items in the list, or -1 on failure.
 */
int
ifaddrlistx(const char *ifname, uint64_t set, uint64_t clear,
    ifaddrlistx_t **ifaddrsp)
{
	struct lifconf	lifc;
	struct lifnum	lifn;
	struct lifreq	*lifrp;
	ifaddrlistx_t	*ifaddrp, *ifaddrs = NULL;
	int		i, nlifr, naddr = 0;
	char		*cp;
	uint_t		flags;
	int		s4, s6 = -1;
	boolean_t	isv6;
	int		save_errno;
	struct sockaddr_storage addr;

	(void) memset(&lifc, 0, sizeof (lifc));
	flags = LIFC_NOXMIT | LIFC_ALLZONES | LIFC_TEMPORARY | LIFC_UNDER_IPMP;

	/*
	 * We need both IPv4 and IPv6 sockets to query both IPv4 and IPv6
	 * interfaces below.
	 */
	if ((s4 = socket(AF_INET, SOCK_DGRAM, 0)) == -1 ||
	    (s6 = socket(AF_INET6, SOCK_DGRAM, 0)) == -1) {
		goto fail;
	}

	/*
	 * Get the number of network interfaces of type `family'.
	 */
	lifn.lifn_family = AF_UNSPEC;
	lifn.lifn_flags = flags;
again:
	if (ioctl(s4, SIOCGLIFNUM, &lifn) == -1)
		goto fail;

	/*
	 * Pad the interface count to detect when additional interfaces have
	 * been configured between SIOCGLIFNUM and SIOCGLIFCONF.
	 */
	lifn.lifn_count += 4;

	lifc.lifc_flags = flags;
	lifc.lifc_family = AF_UNSPEC;
	lifc.lifc_len = lifn.lifn_count * sizeof (struct lifreq);
	if ((lifc.lifc_buf = realloc(lifc.lifc_buf, lifc.lifc_len)) == NULL)
		goto fail;

	if (ioctl(s4, SIOCGLIFCONF, &lifc) == -1)
		goto fail;

	/*
	 * If every lifr_req slot is taken, then additional interfaces must
	 * have been plumbed between the SIOCGLIFNUM and the SIOCGLIFCONF.
	 * Recalculate to make sure we didn't miss any interfaces.
	 */
	nlifr = lifc.lifc_len / sizeof (struct lifreq);
	if (nlifr >= lifn.lifn_count)
		goto again;

	/*
	 * Populate the ifaddrlistx by querying each matching interface.  If a
	 * query ioctl returns ENXIO, then the interface must have been
	 * removed after the SIOCGLIFCONF completed -- so we just ignore it.
	 */
	for (lifrp = lifc.lifc_req, i = 0; i < nlifr; i++, lifrp++) {
		if ((cp = strchr(lifrp->lifr_name, ':')) != NULL)
			*cp = '\0';

		if (strcmp(lifrp->lifr_name, ifname) != 0)
			continue;

		if (cp != NULL)
			*cp = ':';

		addr = lifrp->lifr_addr;
		isv6 = addr.ss_family == AF_INET6;
		if (ioctl(isv6 ? s6 : s4, SIOCGLIFFLAGS, lifrp) == -1) {
			if (errno == ENXIO)
				continue;
			goto fail;
		}

		if (set != 0 && ((lifrp->lifr_flags & set) == 0) ||
		    (lifrp->lifr_flags & clear) != 0)
			continue;

		/*
		 * We've got a match; allocate a new record.
		 */
		if ((ifaddrp = malloc(sizeof (ifaddrlistx_t))) == NULL)
			goto fail;

		(void) strlcpy(ifaddrp->ia_name, lifrp->lifr_name, LIFNAMSIZ);
		ifaddrp->ia_flags = lifrp->lifr_flags;
		ifaddrp->ia_addr = addr;
		ifaddrp->ia_next = ifaddrs;
		ifaddrs = ifaddrp;
		naddr++;
	}

	(void) close(s4);
	(void) close(s6);
	free(lifc.lifc_buf);
	*ifaddrsp = ifaddrs;
	return (naddr);
fail:
	save_errno = errno;
	(void) close(s4);
	(void) close(s6);
	free(lifc.lifc_buf);
	ifaddrlistx_free(ifaddrs);
	errno = save_errno;
	return (-1);
}

/*
 * Free the provided ifaddrlistx_t.
 */
void
ifaddrlistx_free(ifaddrlistx_t *ifaddrp)
{
	ifaddrlistx_t *next_ifaddrp;

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

/*
 * This file contains a routine used to validate a ifconfig-style interface
 * specification
 */

#include <stdlib.h>
#include <ctype.h>
#include <alloca.h>
#include <errno.h>
#include <string.h>
#include <libinetutil.h>

/*
 * Given a token with a logical unit spec, return the logical unit converted
 * to a uint_t.
 *
 * Returns: 0 for success, nonzero if an error occurred. errno is set if
 * necessary.
 */
static int
getlun(const char *bp, int bpsize, uint_t *lun)
{
	char	*ep = (char *)&bp[bpsize - 1];
	char	*sp = strchr(bp, ':'), *tp;

	/* A logical unit spec looks like: <token>:<unsigned int>\0 */
	if (isdigit(*bp) || !isdigit(*ep) || sp == NULL ||
	    strchr(sp + 1, ':') != NULL) {
		errno = EINVAL;
		return (-1);
	}

	*sp++ = '\0';

	/* Lun must be all digits */
	for (tp = sp; tp < ep && isdigit(*tp); tp++)
		/* Null body */;
	if (tp != ep) {
		errno = EINVAL;
		return (-1);
	}

	*lun = atoi(sp);
	return (0);
}

/*
 * Given a single token ending with a ppa spec, return the ppa spec converted
 * to a uint_t.
 *
 * Returns: 0 for success, nonzero if an error occurred. errno is set if
 * necessary.
 */
static int
getppa(const char *bp, int bpsize, uint_t *ppa)
{
	char	*ep = (char *)&bp[bpsize - 1];
	char	*tp;

	if (!isdigit(*ep)) {
		errno = EINVAL;
		return (-1);
	}

	for (tp = ep; tp >= bp && isdigit(*tp); tp--)
		/* Null body */;

	if (*tp == ':') {
		errno = EINVAL;
		return (-1);
	}

	*ppa = atoi(tp + 1);
	return (0);
}

/*
 * Given an ifconfig-style inet relative-path interface specification
 * (e.g: bge0:2), validate its form and decompose the contents into a
 * dynamically allocated ifspec_t.
 *
 * Returns ifspec_t for success, NULL pointer if spec is malformed.
 */
boolean_t
ifparse_ifspec(const char *ifname, ifspec_t *ifsp)
{
	char	*lp, *tp;
	char	ifnamecp[LIFNAMSIZ];

	/* snag a copy we can modify */
	if (strlcpy(ifnamecp, ifname, LIFNAMSIZ) >= LIFNAMSIZ) {
		errno = EINVAL;
		return (B_FALSE);
	}

	ifsp->ifsp_lunvalid = B_FALSE;

	/*
	 * An interface name must have the format of:
	 * dev[ppa][:lun]
	 *
	 * lun - logical unit number.
	 */

	/* Any logical units? */
	lp = strchr(ifnamecp, ':');
	if (lp != NULL) {
		if (getlun(lp, strlen(lp), &ifsp->ifsp_lun) != 0)
			return (B_FALSE);
		ifsp->ifsp_lunvalid = B_TRUE;
	}

	(void) strlcpy(ifsp->ifsp_devnm, ifnamecp, LIFNAMSIZ);

	/* Find ppa  */
	if (getppa(ifsp->ifsp_devnm, strlen(ifsp->ifsp_devnm),
	    &ifsp->ifsp_ppa) != 0) {
		return (B_FALSE);
	}

	/* strip the ppa off of the device name if present */
	for (tp = &ifsp->ifsp_devnm[strlen(ifsp->ifsp_devnm) - 1];
	    tp >= ifsp->ifsp_devnm && isdigit(*tp); tp--) {
		*tp = '\0';
	}

	return (B_TRUE);
}
/*
 * 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#include <unistd.h>
#include <netinet/in.h>
#include <libinetutil.h>
#include <inet/ip.h>
#include <strings.h>
#include <stddef.h>
#include <errno.h>
#include <libsocket_priv.h>

/*
 * Internet utility functions.
 */

/*
 * Given a host-order address, calculate client's default net mask.
 * Consult netmasks database to see if net is further subnetted.
 * We'll only snag the first netmask that matches our criteria.
 * We return the resultant netmask in host order.
 */
void
get_netmask4(const struct in_addr *n_addrp, struct in_addr *s_addrp)
{
	struct in_addr	hp, tp;

	/*
	 * First check if VLSM is in use.
	 */
	hp.s_addr = htonl(n_addrp->s_addr);
	if (getnetmaskbyaddr(hp, &tp) == 0) {
		s_addrp->s_addr = ntohl(tp.s_addr);
		return;
	}

	/*
	 * Fall back on standard classed networks.
	 */
	if (IN_CLASSA(n_addrp->s_addr))
		s_addrp->s_addr = IN_CLASSA_NET;
	else if (IN_CLASSB(n_addrp->s_addr))
		s_addrp->s_addr = IN_CLASSB_NET;
	else if (IN_CLASSC(n_addrp->s_addr))
		s_addrp->s_addr = IN_CLASSC_NET;
	else
		s_addrp->s_addr = IN_CLASSE_NET;
}

/*
 * Checks if the IP addresses `ssp1' and `ssp2' are equal.
 */
boolean_t
sockaddrcmp(const struct sockaddr_storage *ssp1,
    const struct sockaddr_storage *ssp2)
{
	struct in_addr addr1, addr2;
	const struct in6_addr *addr6p1, *addr6p2;

	if (ssp1->ss_family != ssp2->ss_family)
		return (B_FALSE);

	if (ssp1 == ssp2)
		return (B_TRUE);

	switch (ssp1->ss_family) {
	case AF_INET:
		addr1 = ((const struct sockaddr_in *)ssp1)->sin_addr;
		addr2 = ((const struct sockaddr_in *)ssp2)->sin_addr;
		return (addr1.s_addr == addr2.s_addr);
	case AF_INET6:
		addr6p1 = &((const struct sockaddr_in6 *)ssp1)->sin6_addr;
		addr6p2 = &((const struct sockaddr_in6 *)ssp2)->sin6_addr;
		return (IN6_ARE_ADDR_EQUAL(addr6p1, addr6p2));
	}
	return (B_FALSE);
}

/*
 * Stores the netmask in `mask' for the given prefixlen `plen' and also sets
 * `sa_family' in `mask'. Because this function does not require aligned
 * access to the data inside of the sockaddr_in/6 structures, the code can
 * use offsetof() to find the right place in the incoming structure. Why is
 * using that beneficial? Less issues with lint. When using a direct cast
 * of the struct sockaddr_storage structure to sockaddr_in6, a lint warning
 * is generated because the former is composed of 16bit & 8bit elements whilst
 * sockaddr_in6 has a 32bit alignment requirement.
 */
int
plen2mask(uint_t prefixlen, sa_family_t af, struct sockaddr *mask)
{
	uint8_t	*addr;

	if (af == AF_INET) {
		if (prefixlen > IP_ABITS)
			return (EINVAL);
		bzero(mask, sizeof (struct sockaddr_in));
		addr = (uint8_t *)mask;
		addr += offsetof(struct sockaddr_in, sin_addr);
	} else {
		if (prefixlen > IPV6_ABITS)
			return (EINVAL);
		bzero(mask, sizeof (struct sockaddr_in6));
		addr = (uint8_t *)mask;
		addr += offsetof(struct sockaddr_in6, sin6_addr);
	}
	mask->sa_family = af;

	while (prefixlen > 0) {
		if (prefixlen >= 8) {
			*addr++ = 0xFF;
			prefixlen -= 8;
			continue;
		}
		*addr |= 1 << (8 - prefixlen);
		prefixlen--;
	}
	return (0);
}

/*
 * Convert a mask to a prefix length.
 * Returns prefix length on success, -1 otherwise.
 * The comments (above) for plen2mask about the use of `mask' also apply
 * to this function and the choice to use offsetof here too.
 */
int
mask2plen(const struct sockaddr *mask)
{
	int rc = 0;
	uint8_t last;
	uint8_t *addr;
	int limit;

	if (mask->sa_family == AF_INET) {
		limit = IP_ABITS;
		addr = (uint8_t *)mask;
		addr += offsetof(struct sockaddr_in, sin_addr);
	} else {
		limit = IPV6_ABITS;
		addr = (uint8_t *)mask;
		addr += offsetof(struct sockaddr_in6, sin6_addr);
	}

	while (*addr == 0xff) {
		rc += 8;
		if (rc == limit)
			return (limit);
		addr++;
	}

	last = *addr;
	while (last != 0) {
		rc++;
		last = (last << 1) & 0xff;
	}

	return (rc);
}

/*
 * Returns B_TRUE if the address in `ss' is INADDR_ANY for IPv4 or
 * :: for IPv6. Otherwise, returns B_FALSE.
 */
boolean_t
sockaddrunspec(const struct sockaddr *ss)
{
	struct sockaddr_storage data;

	switch (ss->sa_family) {
	case AF_INET:
		(void) memcpy(&data, ss, sizeof (struct sockaddr_in));
		return (((struct sockaddr_in *)&data)->sin_addr.s_addr ==
		    INADDR_ANY);
	case AF_INET6:
		(void) memcpy(&data, ss, sizeof (struct sockaddr_in6));
		return (IN6_IS_ADDR_UNSPECIFIED(
		    &((struct sockaddr_in6 *)&data)->sin6_addr));
	}

	return (B_FALSE);
}
/*
 * 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) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#ifndef _LIBINETUTIL_H
#define	_LIBINETUTIL_H

/*
 * Contains SMI-private API for general Internet functionality
 */

#ifdef	__cplusplus
extern "C" {
#endif

#include <netinet/inetutil.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>

#if !defined(_KERNEL) && !defined(_BOOT)

typedef struct {
	uint_t		ifsp_ppa;	/* Physical Point of Attachment */
	uint_t		ifsp_lun;	/* Logical Unit number */
	boolean_t	ifsp_lunvalid;	/* TRUE if lun is valid */
	char		ifsp_devnm[LIFNAMSIZ];	/* only the device name */
} ifspec_t;

extern boolean_t	ifparse_ifspec(const char *, ifspec_t *);
extern void		get_netmask4(const struct in_addr *, struct in_addr *);
extern boolean_t	sockaddrcmp(const struct sockaddr_storage *,
			    const struct sockaddr_storage *);
extern int		plen2mask(uint_t, sa_family_t, struct sockaddr *);
extern int		mask2plen(const struct sockaddr *);
extern boolean_t	sockaddrunspec(const struct sockaddr *);

/*
 * Extended version of the classic BSD ifaddrlist() interface:
 *
 *    int ifaddrlist(struct ifaddrlist **addrlistp, int af, uint_t flags,
 *	             char *errbuf);
 *
 * 	* addrlistp: Upon success, ifaddrlist() sets *addrlistp to a
 *	  dynamically-allocated array of addresses.
 *
 *	* af: Either AF_INET to obtain IPv4 addresses, or AF_INET6 to
 *	  obtain IPv6 addresses.
 *
 *	* flags: LIFC_* flags that control the classes of interfaces that
 *	  will be visible.
 *
 *	* errbuf: A caller-supplied buffer of ERRBUFSIZE.  Upon failure,
 *	  provides the reason for the failure.
 *
 * Upon success, ifaddrlist() returns the number of addresses in the array
 * pointed to by `addrlistp'.  If the count is 0, then `addrlistp' is NULL.
 */
union any_in_addr {
	struct in6_addr	addr6;
	struct in_addr	addr;
};

struct ifaddrlist {
	int		index;			/* interface index */
	union any_in_addr addr;			/* interface address */
	char		device[LIFNAMSIZ + 1];	/* interface name */
	uint64_t	flags;			/* interface flags */
};

#define	ERRBUFSIZE 128			/* expected size of fourth argument */

extern int ifaddrlist(struct ifaddrlist **, int, uint_t, char *);

/*
 * Similar to ifaddrlist(), but returns a linked-list of addresses for a
 * *specific* interface name, and allows specific address flags to be matched
 * against.  A linked list is used rather than an array so that information
 * can grow over time without affecting binary compatibility.  Also, leaves
 * error-handling up to the caller.  Returns the number of ifaddrlistx's
 * chained through ifaddrp.
 *
 *    int ifaddrlistx(const char *ifname, uint64_t set, uint64_t clear,
 *        ifaddrlistx_t **ifaddrp);
 *
 *	* ifname: Interface name to match against.
 *
 *	* set: One or more flags that must be set on the address for
 *	  it to be returned.
 *
 *	* clear: Flags that must be clear on the address for it to be
 *	  returned.
 *
 * 	* ifaddrp: Upon success, ifaddrlistx() sets *ifaddrp to the head
 *	  of a dynamically-allocated array of ifaddrlistx structures.
 *
 * Once done, the caller must free `ifaddrp' by calling ifaddrlistx_free().
 */
typedef struct ifaddrlistx {
	struct ifaddrlistx	*ia_next;
	char			ia_name[LIFNAMSIZ];
	uint64_t		ia_flags;
	struct sockaddr_storage	ia_addr;
} ifaddrlistx_t;

extern int ifaddrlistx(const char *, uint64_t, uint64_t, ifaddrlistx_t **);
extern void ifaddrlistx_free(ifaddrlistx_t *);

/*
 * Timer queues
 *
 * timer queues are a facility for managing timeouts in unix.  in the
 * event driven model, unix provides us with poll(2)/select(3C), which
 * allow us to coordinate waiting on multiple descriptors with an
 * optional timeout.  however, often (as is the case with the DHCP
 * agent), we want to manage multiple independent timeouts (say, one
 * for waiting for an OFFER to come back from a server in response to
 * a DISCOVER sent out on one interface, and another for waiting for
 * the T1 time on another interface).  timer queues allow us to do
 * this in the event-driven model.
 *
 * note that timer queues do not in and of themselves provide the
 * event driven model (for instance, there is no handle_events()
 * routine).  they merely provide the hooks to support multiple
 * independent timeouts.  this is done for both simplicity and
 * applicability (for instance, while one approach would be to use
 * this timer queue with poll(2), another one would be to use SIGALRM
 * to wake up periodically, and then process all the expired timers.)
 */

typedef struct iu_timer_queue iu_tq_t;

/*
 * a iu_timer_id_t refers to a given timer.  its value should not be
 * interpreted by the interface consumer.  it is a signed arithmetic
 * type, and no valid iu_timer_id_t has the value `-1'.
 */

typedef int iu_timer_id_t;

#define	IU_TIMER_ID_MAX	4096	/* max number of concurrent timers */

/*
 * a iu_tq_callback_t is a function that is called back in response to a
 * timer expiring.  it may then carry out any necessary work,
 * including rescheduling itself for callback or scheduling /
 * cancelling other timers.  the `void *' argument is the same value
 * that was passed into iu_schedule_timer(), and if it is dynamically
 * allocated, it is the callback's responsibility to know that, and to
 * free it.
 */

typedef void	iu_tq_callback_t(iu_tq_t *, void *);

iu_tq_t		*iu_tq_create(void);
void		iu_tq_destroy(iu_tq_t *);
iu_timer_id_t	iu_schedule_timer(iu_tq_t *, uint32_t, iu_tq_callback_t *,
		    void *);
iu_timer_id_t	iu_schedule_timer_ms(iu_tq_t *, uint64_t, iu_tq_callback_t *,
		    void *);
int		iu_adjust_timer(iu_tq_t *, iu_timer_id_t, uint32_t);
int		iu_cancel_timer(iu_tq_t *, iu_timer_id_t, void **);
int		iu_expire_timers(iu_tq_t *);
int		iu_earliest_timer(iu_tq_t *);

/*
 * Event Handler
 *
 * an event handler is an object-oriented "wrapper" for select(3C) /
 * poll(2), aimed to make the event demultiplexing system calls easier
 * to use and provide a generic reusable component.  instead of
 * applications directly using select(3C) / poll(2), they register
 * events that should be received with the event handler, providing a
 * callback function to call when the event occurs.  they then call
 * iu_handle_events() to wait and callback the registered functions
 * when events occur.  also called a `reactor'.
 */

typedef struct iu_event_handler iu_eh_t;

/*
 * an iu_event_id_t refers to a given event.  its value should not be
 * interpreted by the interface consumer.  it is a signed arithmetic
 * type, and no valid iu_event_id_t has the value `-1'.
 */

typedef int iu_event_id_t;

/*
 * an iu_eh_callback_t is a function that is called back in response to
 * an event occurring.  it may then carry out any work necessary in
 * response to the event.  it receives the file descriptor upon which
 * the event occurred, a bit array of events that occurred (the same
 * array used as the revents by poll(2)), and its context through the
 * `void *' that was originally passed into iu_register_event().
 *
 * NOTE: the same descriptor may not be registered multiple times for
 * different callbacks.  if this behavior is desired, either use dup(2)
 * to get a unique descriptor, or demultiplex in the callback function
 * based on the events.
 */

typedef void	iu_eh_callback_t(iu_eh_t *, int, short, iu_event_id_t, void *);
typedef void	iu_eh_sighandler_t(iu_eh_t *, int, void *);
typedef boolean_t iu_eh_shutdown_t(iu_eh_t *, void *);

iu_eh_t		*iu_eh_create(void);
void		iu_eh_destroy(iu_eh_t *);
iu_event_id_t	iu_register_event(iu_eh_t *, int, short, iu_eh_callback_t *,
		    void *);
int		iu_unregister_event(iu_eh_t *, iu_event_id_t, void **);
int		iu_handle_events(iu_eh_t *, iu_tq_t *);
void		iu_stop_handling_events(iu_eh_t *, unsigned int,
		    iu_eh_shutdown_t *, void *);
int		iu_eh_register_signal(iu_eh_t *, int, iu_eh_sighandler_t *,
		    void *);
int		iu_eh_unregister_signal(iu_eh_t *, int, void **);

#endif	/* !defined(_KERNEL) && !defined(_BOOT) */

#ifdef	__cplusplus
}
#endif

#endif	/* !_LIBINETUTIL_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _LIBINETUTIL_IMPL_H
#define	_LIBINETUTIL_IMPL_H

/*
 * Contains implementation-specific definitions for libinetutil.
 */

#ifdef	__cplusplus
extern "C" {
#endif

#include <netinet/inetutil.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <sys/poll.h>
#include <signal.h>
#include <limits.h>

/*
 * timer queue implementation-specific artifacts which may change.  A
 * `iu_tq_t' is an incomplete type as far as the consumer of timer queues
 * is concerned.
 */

typedef struct iu_timer_node {

	struct iu_timer_node		*iutn_prev;
	struct iu_timer_node		*iutn_next;
	struct iu_timer_node		*iutn_expire_next;
	hrtime_t			iutn_abs_timeout;
	iu_timer_id_t			iutn_timer_id;
	iu_tq_callback_t		*iutn_callback;
	void				*iutn_arg;
	int				iutn_pending_delete;

} iu_timer_node_t;

struct iu_timer_queue {
	iu_timer_id_t	iutq_next_timer_id;
	iu_timer_node_t	*iutq_head;		/* in order of time-to-fire */
	int		iutq_in_expire;	/* nonzero if in the expire function */
	uchar_t		iutq_timer_id_map[(IU_TIMER_ID_MAX + CHAR_BIT) /
				CHAR_BIT];
};

/*
 * event handler implementation-specific artifacts which may change.  An
 * `iu_eh_t' is an incomplete type as far as the consumer of event handlers is
 * concerned.
 */

typedef struct iu_event_node {

	iu_eh_callback_t	*iuen_callback;	/* callback to call */

	void			*iuen_arg;	/* argument to pass to the */
						/* callback */
} iu_event_node_t;

typedef struct iu_eh_sig_info  {

	boolean_t		iues_pending;	/* signal is currently */
						/* pending */

	iu_eh_sighandler_t	*iues_handler;	/* handler for a given signal */

	void			*iues_data; 	/* data to pass back to the */
						/* handler */
} iu_eh_sig_info_t;

struct iu_event_handler {

	struct pollfd		*iueh_pollfds;	/* array of pollfds */

	iu_event_node_t		*iueh_events;	/* corresponding pollfd info */

	unsigned int		iueh_num_fds;	/* number of pollfds/events */

	boolean_t		iueh_stop;	/* true when done */

	unsigned int		iueh_reason;	/* if stop is true, reason */

	sigset_t		iueh_sig_regset;	/* registered signal */
							/* set */

	iu_eh_sig_info_t	iueh_sig_info[NSIG];	/* signal handler */
							/* information */

	iu_eh_shutdown_t	*iueh_shutdown;	/* shutdown callback */

	void			*iueh_shutdown_arg;	/* data for shutdown */
							/* callback */
};

#ifdef	__cplusplus
}
#endif

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

#
# MAPFILE HEADER START
#
# WARNING:  STOP NOW.  DO NOT MODIFY THIS FILE.
# Object versioning must comply with the rules detailed in
#
#	usr/src/lib/README.mapfiles
#
# You should not be making modifications here until you've read the most current
# copy of that file. If you need help, contact a gatekeeper for guidance.
#
# MAPFILE HEADER END
#

$mapfile_version 2

SYMBOL_VERSION SUNWprivate_1.1 {
    global:
	get_netmask4;
	hexascii_to_octet;
	ifaddrlist;
	ifaddrlistx;
	ifaddrlistx_free;
	ifparse_ifspec;
	iu_adjust_timer;
	iu_cancel_timer;
	iu_earliest_timer;
	iu_eh_create;
	iu_eh_destroy;
	iu_eh_register_signal;
	iu_eh_unregister_signal;
	iu_expire_timers;
	iu_handle_events;
	iu_register_event;
	iu_schedule_timer;
	iu_schedule_timer_ms;
	iu_stop_handling_events;
	iu_tq_create;
	iu_tq_destroy;
	iu_unregister_event;
	octet_to_hexascii;
	ofmt_open		{ TYPE = FUNCTION; FILTER = libofmt.so.1 };
	ofmt_close		{ TYPE = FUNCTION; FILTER = libofmt.so.1 };
	ofmt_print		{ TYPE = FUNCTION; FILTER = libofmt.so.1 };
	ofmt_update_winsize	{ TYPE = FUNCTION; FILTER = libofmt.so.1 };
	ofmt_strerror		{ TYPE = FUNCTION; FILTER = libofmt.so.1 };
	mask2plen;
	plen2mask;
	sockaddrcmp;
	sockaddrunspec;
    local:
	*;
};
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdlib.h>
#include <limits.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/sysmacros.h>
#include <sys/stropts.h>	/* INFTIM */

#include <libinetutil.h>
#include "libinetutil_impl.h"

static iu_timer_node_t	*pending_delete_chain = NULL;

static void		destroy_timer(iu_tq_t *, iu_timer_node_t *);
static iu_timer_id_t	get_timer_id(iu_tq_t *);
static void		release_timer_id(iu_tq_t *, iu_timer_id_t);

/*
 * iu_tq_create(): creates, initializes and returns a timer queue for use
 *
 *   input: void
 *  output: iu_tq_t *: the new timer queue
 */

iu_tq_t *
iu_tq_create(void)
{
	return (calloc(1, sizeof (iu_tq_t)));
}

/*
 * iu_tq_destroy(): destroys an existing timer queue
 *
 *   input: iu_tq_t *: the timer queue to destroy
 *  output: void
 */

void
iu_tq_destroy(iu_tq_t *tq)
{
	iu_timer_node_t *node, *next_node;

	for (node = tq->iutq_head; node != NULL; node = next_node) {
		next_node = node->iutn_next;
		destroy_timer(tq, node);
	}

	free(tq);
}

/*
 * insert_timer(): inserts a timer node into a tq's timer list
 *
 *   input: iu_tq_t *: the timer queue
 *	    iu_timer_node_t *: the timer node to insert into the list
 *	    uint64_t: the number of milliseconds before this timer fires
 *  output: void
 */

static void
insert_timer(iu_tq_t *tq, iu_timer_node_t *node, uint64_t msec)
{
	iu_timer_node_t	*after = NULL;

	/*
	 * find the node to insert this new node "after".  we do this
	 * instead of the more intuitive "insert before" because with
	 * the insert before approach, a null `before' node pointer
	 * is overloaded in meaning (it could be null because there
	 * are no items in the list, or it could be null because this
	 * is the last item on the list, which are very different cases).
	 */

	node->iutn_abs_timeout = gethrtime() + MSEC2NSEC(msec);

	if (tq->iutq_head != NULL &&
	    tq->iutq_head->iutn_abs_timeout < node->iutn_abs_timeout)
		for (after = tq->iutq_head; after->iutn_next != NULL;
		    after = after->iutn_next)
			if (after->iutn_next->iutn_abs_timeout >
			    node->iutn_abs_timeout)
				break;

	node->iutn_next = after ? after->iutn_next : tq->iutq_head;
	node->iutn_prev = after;
	if (after == NULL)
		tq->iutq_head = node;
	else
		after->iutn_next = node;

	if (node->iutn_next != NULL)
		node->iutn_next->iutn_prev = node;
}

/*
 * remove_timer(): removes a timer node from the tq's timer list
 *
 *   input: iu_tq_t *: the timer queue
 *	    iu_timer_node_t *: the timer node to remove from the list
 *  output: void
 */

static void
remove_timer(iu_tq_t *tq, iu_timer_node_t *node)
{
	if (node->iutn_next != NULL)
		node->iutn_next->iutn_prev = node->iutn_prev;
	if (node->iutn_prev != NULL)
		node->iutn_prev->iutn_next = node->iutn_next;
	else
		tq->iutq_head = node->iutn_next;
}

/*
 * destroy_timer(): destroy a timer node
 *
 *  input: iu_tq_t *: the timer queue the timer node is associated with
 *	   iu_timer_node_t *: the node to free
 * output: void
 */

static void
destroy_timer(iu_tq_t *tq, iu_timer_node_t *node)
{
	release_timer_id(tq, node->iutn_timer_id);

	/*
	 * if we're in expire, don't delete the node yet, since it may
	 * still be referencing it (through the expire_next pointers)
	 */

	if (tq->iutq_in_expire) {
		node->iutn_pending_delete++;
		node->iutn_next = pending_delete_chain;
		pending_delete_chain = node;
	} else
		free(node);

}

/*
 * iu_schedule_timer(): creates and inserts a timer in the tq's timer list
 *
 *   input: iu_tq_t *: the timer queue
 *	    uint32_t: the number of seconds before this timer fires
 *	    iu_tq_callback_t *: the function to call when the timer fires
 *	    void *: an argument to pass to the called back function
 *  output: iu_timer_id_t: the new timer's timer id on success, -1 on failure
 */

iu_timer_id_t
iu_schedule_timer(iu_tq_t *tq, uint32_t sec, iu_tq_callback_t *callback,
    void *arg)
{
	return (iu_schedule_timer_ms(tq, sec * MILLISEC, callback, arg));
}

/*
 * iu_schedule_ms_timer(): creates and inserts a timer in the tq's timer list,
 *			   using millisecond granularity
 *
 *   input: iu_tq_t *: the timer queue
 *	    uint64_t: the number of milliseconds before this timer fires
 *	    iu_tq_callback_t *: the function to call when the timer fires
 *	    void *: an argument to pass to the called back function
 *  output: iu_timer_id_t: the new timer's timer id on success, -1 on failure
 */
iu_timer_id_t
iu_schedule_timer_ms(iu_tq_t *tq, uint64_t ms, iu_tq_callback_t *callback,
    void *arg)
{
	iu_timer_node_t	*node = calloc(1, sizeof (iu_timer_node_t));

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

	node->iutn_callback	= callback;
	node->iutn_arg	= arg;
	node->iutn_timer_id	= get_timer_id(tq);
	if (node->iutn_timer_id == -1) {
		free(node);
		return (-1);
	}

	insert_timer(tq, node, ms);

	return (node->iutn_timer_id);
}

/*
 * iu_cancel_timer(): cancels a pending timer from a timer queue's timer list
 *
 *   input: iu_tq_t *: the timer queue
 *	    iu_timer_id_t: the timer id returned from iu_schedule_timer
 *	    void **: if non-NULL, a place to return the argument passed to
 *		     iu_schedule_timer
 *  output: int: 1 on success, 0 on failure
 */

int
iu_cancel_timer(iu_tq_t *tq, iu_timer_id_t timer_id, void **arg)
{
	iu_timer_node_t	*node;

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

	for (node = tq->iutq_head; node != NULL; node = node->iutn_next) {
		if (node->iutn_timer_id == timer_id) {
			if (arg != NULL)
				*arg = node->iutn_arg;
			remove_timer(tq, node);
			destroy_timer(tq, node);
			return (1);
		}
	}
	return (0);
}

/*
 * iu_adjust_timer(): adjusts the fire time of a timer in the tq's timer list
 *
 *   input: iu_tq_t *: the timer queue
 *	    iu_timer_id_t: the timer id returned from iu_schedule_timer
 *	    uint32_t: the number of seconds before this timer fires
 *  output: int: 1 on success, 0 on failure
 */

int
iu_adjust_timer(iu_tq_t *tq, iu_timer_id_t timer_id, uint32_t sec)
{
	iu_timer_node_t	*node;

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

	for (node = tq->iutq_head; node != NULL; node = node->iutn_next) {
		if (node->iutn_timer_id == timer_id) {
			remove_timer(tq, node);
			insert_timer(tq, node, sec * MILLISEC);
			return (1);
		}
	}
	return (0);
}

/*
 * iu_earliest_timer(): returns the time until the next timer fires on a tq
 *
 *   input: iu_tq_t *: the timer queue
 *  output: int: the number of milliseconds until the next timer (up to
 *	    a maximum value of INT_MAX), or INFTIM if no timers are pending.
 */

int
iu_earliest_timer(iu_tq_t *tq)
{
	unsigned long long	timeout_interval;
	hrtime_t		current_time = gethrtime();

	if (tq->iutq_head == NULL)
		return (INFTIM);

	/*
	 * event might've already happened if we haven't gotten a chance to
	 * run in a while; return zero and pretend it just expired.
	 */

	if (tq->iutq_head->iutn_abs_timeout <= current_time)
		return (0);

	/*
	 * since the timers are ordered in absolute time-to-fire, just
	 * subtract from the head of the list.
	 */

	timeout_interval =
	    (tq->iutq_head->iutn_abs_timeout - current_time) / 1000000;

	return (MIN(timeout_interval, INT_MAX));
}

/*
 * iu_expire_timers(): expires all pending timers on a given timer queue
 *
 *   input: iu_tq_t *: the timer queue
 *  output: int: the number of timers expired
 */

int
iu_expire_timers(iu_tq_t *tq)
{
	iu_timer_node_t	*node, *next_node;
	int		n_expired = 0;
	hrtime_t	current_time = gethrtime();

	/*
	 * in_expire is in the iu_tq_t instead of being passed through as
	 * an argument to remove_timer() below since the callback
	 * function may call iu_cancel_timer() itself as well.
	 */

	tq->iutq_in_expire++;

	/*
	 * this function builds another linked list of timer nodes
	 * through `expire_next' because the normal linked list
	 * may be changed as a result of callbacks canceling and
	 * scheduling timeouts, and thus can't be trusted.
	 */

	for (node = tq->iutq_head; node != NULL; node = node->iutn_next)
		node->iutn_expire_next = node->iutn_next;

	for (node = tq->iutq_head; node != NULL;
	    node = node->iutn_expire_next) {

		/*
		 * If the timeout is within 1 millisec of current time,
		 * consider it as expired already.  We do this because
		 * iu_earliest_timer() only has millisec granularity.
		 * So we should also use millisec grandularity in
		 * comparing timeout values.
		 */
		if (node->iutn_abs_timeout - current_time > 1000000)
			break;

		/*
		 * fringe condition: two timers fire at the "same
		 * time" (i.e., they're both scheduled called back in
		 * this loop) and one cancels the other.  in this
		 * case, the timer which has already been "cancelled"
		 * should not be called back.
		 */

		if (node->iutn_pending_delete)
			continue;

		/*
		 * we remove the timer before calling back the callback
		 * so that a callback which accidentally tries to cancel
		 * itself (through whatever means) doesn't succeed.
		 */

		n_expired++;
		remove_timer(tq, node);
		destroy_timer(tq, node);
		node->iutn_callback(tq, node->iutn_arg);
	}

	tq->iutq_in_expire--;

	/*
	 * any cancels that took place whilst we were expiring timeouts
	 * ended up on the `pending_delete_chain'.  delete them now
	 * that it's safe.
	 */

	for (node = pending_delete_chain; node != NULL; node = next_node) {
		next_node = node->iutn_next;
		free(node);
	}
	pending_delete_chain = NULL;

	return (n_expired);
}

/*
 * get_timer_id(): allocates a timer id from the pool
 *
 *   input: iu_tq_t *: the timer queue
 *  output: iu_timer_id_t: the allocated timer id, or -1 if none available
 */

static iu_timer_id_t
get_timer_id(iu_tq_t *tq)
{
	unsigned int	map_index;
	unsigned char	map_bit;
	boolean_t	have_wrapped = B_FALSE;

	for (; ; tq->iutq_next_timer_id++) {

		if (tq->iutq_next_timer_id >= IU_TIMER_ID_MAX) {
			if (have_wrapped)
				return (-1);

			have_wrapped = B_TRUE;
			tq->iutq_next_timer_id = 0;
		}

		map_index = tq->iutq_next_timer_id / CHAR_BIT;
		map_bit   = tq->iutq_next_timer_id % CHAR_BIT;

		if ((tq->iutq_timer_id_map[map_index] & (1 << map_bit)) == 0)
			break;
	}

	tq->iutq_timer_id_map[map_index] |= (1 << map_bit);
	return (tq->iutq_next_timer_id++);
}

/*
 * release_timer_id(): releases a timer id back into the pool
 *
 *   input: iu_tq_t *: the timer queue
 *	    iu_timer_id_t: the timer id to release
 *  output: void
 */

static void
release_timer_id(iu_tq_t *tq, iu_timer_id_t timer_id)
{
	unsigned int	map_index = timer_id / CHAR_BIT;
	unsigned char	map_bit	  = timer_id % CHAR_BIT;

	tq->iutq_timer_id_map[map_index] &= ~(1 << map_bit);
}