|
root / base / usr / src / contrib / mDNSResponder / mDNSPosix
mDNSPosix Plain Text 4006 lines 135.4 KB
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
/*
 * Copyright (c) 2003-2019 Apple Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.

    File:		daemon.c

    Contains:	main & associated Application layer for mDNSResponder on Linux.

 */

#if __APPLE__
// In Mac OS X 10.5 and later trying to use the daemon function gives a “‘daemon’ is deprecated”
// error, which prevents compilation because we build with "-Werror".
// Since this is supposed to be portable cross-platform code, we don't care that daemon is
// deprecated on Mac OS X 10.5, so we use this preprocessor trick to eliminate the error message.
#define daemon yes_we_know_that_daemon_is_deprecated_in_os_x_10_5_thankyou
#endif

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <sys/types.h>
#include <sys/socket.h>

#if __APPLE__
#undef daemon
extern int daemon(int, int);
#endif

#include "mDNSEmbeddedAPI.h"
#include "mDNSPosix.h"
#include "mDNSUNP.h"        // For daemon()
#include "uds_daemon.h"
#include "PlatformCommon.h"
#include "posix_utilities.h"    // For getLocalTimestamp()

#ifndef MDNSD_USER
#define	MDNSD_USER "nobody"
#endif

#define CONFIG_FILE "/etc/mdnsd.conf"
static domainname DynDNSZone;                // Default wide-area zone for service registration
static domainname DynDNSHostname;

#define RR_CACHE_SIZE 500
static CacheEntity gRRCache[RR_CACHE_SIZE];
static mDNS_PlatformSupport PlatformStorage;

mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result)
{
    (void)m; // Unused
    if (result == mStatus_NoError)
    {
        // On successful registration of dot-local mDNS host name, daemon may want to check if
        // any name conflict and automatic renaming took place, and if so, record the newly negotiated
        // name in persistent storage for next time. It should also inform the user of the name change.
        // On Mac OS X we store the current dot-local mDNS host name in the SCPreferences store,
        // and notify the user with a CFUserNotification.
    }
    else if (result == mStatus_ConfigChanged)
    {
        udsserver_handle_configchange(m);
    }
    else if (result == mStatus_GrowCache)
    {
        // Allocate another chunk of cache storage
        CacheEntity *storage = malloc(sizeof(CacheEntity) * RR_CACHE_SIZE);
        if (storage) mDNS_GrowCache(m, storage, RR_CACHE_SIZE);
    }
}

// %%% Reconfigure() probably belongs in the platform support layer (mDNSPosix.c), not the daemon cde
// -- all client layers running on top of mDNSPosix.c need to handle network configuration changes,
// not only the Unix Domain Socket Daemon

static void Reconfigure(mDNS *m)
{
    mDNSAddr DynDNSIP;
    const mDNSAddr dummy = { mDNSAddrType_IPv4, { { { 1, 1, 1, 1 } } } };;
    mDNS_SetPrimaryInterfaceInfo(m, NULL, NULL, NULL);
    if (ParseDNSServers(m, uDNS_SERVERS_FILE) < 0)
        LogMsg("Unable to parse DNS server list. Unicast DNS-SD unavailable");
    ReadDDNSSettingsFromConfFile(m, CONFIG_FILE, &DynDNSHostname, &DynDNSZone, NULL);
    mDNSPlatformSourceAddrForDest(&DynDNSIP, &dummy);
    if (DynDNSHostname.c[0]) mDNS_AddDynDNSHostName(m, &DynDNSHostname, NULL, NULL);
    if (DynDNSIP.type) mDNS_SetPrimaryInterfaceInfo(m, &DynDNSIP, NULL, NULL);
    mDNS_ConfigChanged(m);
}

// Do appropriate things at startup with command line arguments. Calls exit() if unhappy.
mDNSlocal void ParseCmdLinArgs(int argc, char **argv)
{
    if (argc > 1)
    {
        if (0 == strcmp(argv[1], "-debug")) mDNS_DebugMode = mDNStrue;
        else printf("Usage: %s [-debug]\n", argv[0]);
    }

    if (!mDNS_DebugMode)
    {
        int result = daemon(0, 0);
        if (result != 0) { LogMsg("Could not run as daemon - exiting"); exit(result); }
#if __APPLE__
        LogMsg("The POSIX mdnsd should only be used on OS X for testing - exiting");
        exit(-1);
#endif
    }
}

mDNSlocal void ToggleLog(void)
{
    mDNS_LoggingEnabled = !mDNS_LoggingEnabled;
}

mDNSlocal void ToggleLogPacket(void)
{
    mDNS_PacketLoggingEnabled = !mDNS_PacketLoggingEnabled;
}

// Dump a little log of what we've been up to.
mDNSlocal void DumpStateLog()
{
    char timestamp[64]; // 64 is enough to store the UTC timestmp
    
    mDNSu32 major_version = _DNS_SD_H / 10000;
    mDNSu32 minor_version1 = (_DNS_SD_H - major_version * 10000) / 100;
    mDNSu32 minor_version2 = _DNS_SD_H % 100;

    getLocalTimestamp(timestamp, sizeof(timestamp));
    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "---- BEGIN STATE LOG ---- (%s mDNSResponder Build %d.%02d.%02d)", timestamp, major_version, minor_version1, minor_version2);

    udsserver_info_dump_to_fd(STDERR_FILENO);

    getLocalTimestamp(timestamp, sizeof(timestamp));
    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "---- END STATE LOG ---- (%s mDNSResponder Build %d.%02d.%02d)", timestamp, major_version, minor_version1, minor_version2);
}

mDNSlocal mStatus MainLoop(mDNS *m) // Loop until we quit.
{
    sigset_t signals;
    mDNSBool gotData = mDNSfalse;

    mDNSPosixListenForSignalInEventLoop(SIGINT);
    mDNSPosixListenForSignalInEventLoop(SIGTERM);
    mDNSPosixListenForSignalInEventLoop(SIGUSR1);
    mDNSPosixListenForSignalInEventLoop(SIGUSR2);
    mDNSPosixListenForSignalInEventLoop(SIGINFO);
    mDNSPosixListenForSignalInEventLoop(SIGPIPE);
    mDNSPosixListenForSignalInEventLoop(SIGHUP) ;

    for (; ;)
    {
        // Work out how long we expect to sleep before the next scheduled task
        struct timeval timeout;
        mDNSs32 ticks;

        // Only idle if we didn't find any data the last time around
        if (!gotData)
        {
            mDNSs32 nextTimerEvent = mDNS_Execute(m);
            nextTimerEvent = udsserver_idle(nextTimerEvent);
            ticks = nextTimerEvent - mDNS_TimeNow(m);
            if (ticks < 1) ticks = 1;
        }
        else    // otherwise call EventLoop again with 0 timemout
            ticks = 0;

        timeout.tv_sec = ticks / mDNSPlatformOneSecond;
        timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * 1000000 / mDNSPlatformOneSecond;

        (void) mDNSPosixRunEventLoopOnce(m, &timeout, &signals, &gotData);

        if (sigismember(&signals, SIGHUP )) Reconfigure(m);
        if (sigismember(&signals, SIGINFO)) DumpStateLog();
        if (sigismember(&signals, SIGUSR1)) ToggleLog();
        if (sigismember(&signals, SIGUSR2)) ToggleLogPacket();
        // SIGPIPE happens when we try to write to a dead client; death should be detected soon in request_callback() and cleaned up.
        if (sigismember(&signals, SIGPIPE)) LogMsg("Received SIGPIPE - ignoring");
        if (sigismember(&signals, SIGINT) || sigismember(&signals, SIGTERM)) break;
    }
    return EINTR;
}

int main(int argc, char **argv)
{
    mStatus err;

    ParseCmdLinArgs(argc, argv);

    LogInfo("%s starting", mDNSResponderVersionString);

    err = mDNS_Init(&mDNSStorage, &PlatformStorage, gRRCache, RR_CACHE_SIZE, mDNS_Init_AdvertiseLocalAddresses,
                    mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);

    if (mStatus_NoError == err)
        err = udsserver_init(mDNSNULL, 0);

    Reconfigure(&mDNSStorage);

    // Now that we're finished with anything privileged, switch over to running as "nobody"
    if (mStatus_NoError == err)
    {
        const struct passwd *pw = getpwnam(MDNSD_USER);
        if (pw != NULL)
        {
            if (setgid(pw->pw_gid) < 0)
            {
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                          "WARNING: mdnsd continuing as group root because setgid to \""MDNSD_USER"\" failed with " PUB_S, strerror(errno));
            }
            if (setuid(pw->pw_uid) < 0)
            {
                LogMsg("WARNING: mdnsd continuing as root because setuid to \""MDNSD_USER"\" failed with %s", strerror(errno));
            }
        }
        else
        {
            LogMsg("WARNING: mdnsd continuing as root because user \""MDNSD_USER"\" does not exist");
        }
    }

    if (mStatus_NoError == err)
        err = MainLoop(&mDNSStorage);

    LogInfo("%s stopping", mDNSResponderVersionString);

    mDNS_Close(&mDNSStorage);

    if (udsserver_exit() < 0)
        LogMsg("ExitCallback: udsserver_exit failed");

 #if MDNS_DEBUGMSGS > 0
    printf("mDNSResponder exiting normally with %d\n", err);
 #endif

    return err;
}

//		uds_daemon support		////////////////////////////////////////////////////////////

mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context, void **platform_data)
/* Support routine for uds_daemon.c */
{
    // Depends on the fact that udsEventCallback == mDNSPosixEventCallback
    (void) platform_data;
    return mDNSPosixAddFDToEventLoop(fd, callback, context);
}

int udsSupportReadFD(dnssd_sock_t fd, char *buf, int len, int flags, void *platform_data)
{
    (void) platform_data;
    return recv(fd, buf, len, flags);
}

mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data)        // Note: This also CLOSES the file descriptor
{
    mStatus err = mDNSPosixRemoveFDFromEventLoop(fd);
    (void) platform_data;
    close(fd);
    return err;
}

mDNSexport void RecordUpdatedNiceLabel(mDNSs32 delay)
{
    (void)delay;
    // No-op, for now
}

#if _BUILDING_XCODE_PROJECT_
// If the process crashes, then this string will be magically included in the automatically-generated crash log
const char *__crashreporter_info__ = mDNSResponderVersionString_SCCS + 5;
asm (".desc ___crashreporter_info__, 0x10");
#endif

// For convenience when using the "strings" command, this is the last thing in the file
#if defined(mDNSResponderVersion)
// Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
// e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
// To expand "version" to its value before making the string, use STRINGIFY(version) instead
#define	STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) # s
#define	STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)

mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder-" STRINGIFY(mDNSResponderVersion);
#elif MDNS_VERSIONSTR_NODTS
mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder (Engineering Build)";
#else
mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder (Engineering Build) (" __DATE__ " " __TIME__ ")";
#endif
/* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*-
 *
 * Copyright (c) 2002-2019 Apple Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "mDNSEmbeddedAPI.h"           // Defines the interface provided to the client layer above
#include "DNSCommon.h"
#include "mDNSPosix.h"               // Defines the specific types needed to run mDNS on this platform
#include "PlatformCommon.h"
#include "dns_sd.h"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <stdarg.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>                   // platform support for UTC time
#include <ifaddrs.h>

#if USES_NETLINK
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#else // USES_NETLINK
#include <net/route.h>
#include <net/if.h>
#endif // USES_NETLINK

#include "mDNSUNP.h"
#include "GenLinkedList.h"
#include "dnsproxy.h"

// ***************************************************************************
// Structures

// Context record for interface change callback
struct IfChangeRec
{
    int NotifySD;
    mDNS *mDNS;
};
typedef struct IfChangeRec IfChangeRec;

// Note that static data is initialized to zero in (modern) C.
static PosixEventSource *gEventSources;             // linked list of PosixEventSource's
static sigset_t gEventSignalSet;                // Signals which event loop listens for
static sigset_t gEventSignals;                  // Signals which were received while inside loop

static PosixNetworkInterface *gRecentInterfaces;

// ***************************************************************************
// Globals (for debugging)

static int num_registered_interfaces = 0;
static int num_pkts_accepted = 0;
static int num_pkts_rejected = 0;

// ***************************************************************************
// Locals
mDNSlocal void requestReadEvents(PosixEventSource *eventSource,
                                    const char *taskName, mDNSPosixEventCallback callback, void *context);
mDNSlocal mStatus stopReadOrWriteEvents(int fd, mDNSBool freeSource, mDNSBool removeSource, int flags);
mDNSlocal void requestWriteEvents(PosixEventSource *eventSource,
                                     const char *taskName, mDNSPosixEventCallback callback, void *context);
// ***************************************************************************
// Functions

#if MDNS_MALLOC_DEBUGGING
mDNSexport void mDNSPlatformValidateLists(void)
{
    // This should validate gEventSources and any other Posix-specific stuff that gets allocated.
}
#endif

int gMDNSPlatformPosixVerboseLevel = 0;

#define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)

mDNSlocal void SockAddrTomDNSAddr(const struct sockaddr *const sa, mDNSAddr *ipAddr, mDNSIPPort *ipPort)
{
    switch (sa->sa_family)
    {
    case AF_INET:
    {
        struct sockaddr_in *sin          = (struct sockaddr_in*)sa;
        ipAddr->type                     = mDNSAddrType_IPv4;
        ipAddr->ip.v4.NotAnInteger       = sin->sin_addr.s_addr;
        if (ipPort) ipPort->NotAnInteger = sin->sin_port;
        break;
    }

#if HAVE_IPV6
    case AF_INET6:
    {
        struct sockaddr_in6 *sin6        = (struct sockaddr_in6*)sa;
#ifndef NOT_HAVE_SA_LEN
        assert(sin6->sin6_len == sizeof(*sin6));
#endif
        ipAddr->type                     = mDNSAddrType_IPv6;
        ipAddr->ip.v6                    = *(mDNSv6Addr*)&sin6->sin6_addr;
        if (ipPort) ipPort->NotAnInteger = sin6->sin6_port;
        break;
    }
#endif

    default:
        verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa->sa_family);
        ipAddr->type = mDNSAddrType_None;
        if (ipPort) ipPort->NotAnInteger = 0;
        break;
    }
}

#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark ***** Send and Receive
#endif

// mDNS core calls this routine when it needs to send a packet.
mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
                                       mDNSInterfaceID InterfaceID, UDPSocket *src, const mDNSAddr *dst,
                                       mDNSIPPort dstPort, mDNSBool useBackgroundTrafficClass)
{
    int err = 0;
    struct sockaddr_storage to;
    PosixNetworkInterface * thisIntf = (PosixNetworkInterface *)(InterfaceID);
    int sendingsocket = -1;

    (void)src;  // Will need to use this parameter once we implement mDNSPlatformUDPSocket/mDNSPlatformUDPClose
    (void) useBackgroundTrafficClass;

    assert(m != NULL);
    assert(msg != NULL);
    assert(end != NULL);
    assert((((char *) end) - ((char *) msg)) > 0);

    if (dstPort.NotAnInteger == 0)
    {
        LogMsg("mDNSPlatformSendUDP: Invalid argument -dstPort is set to 0");
        return PosixErrorToStatus(EINVAL);
    }
    if (dst->type == mDNSAddrType_IPv4)
    {
        struct sockaddr_in *sin = (struct sockaddr_in*)&to;
#ifndef NOT_HAVE_SA_LEN
        sin->sin_len            = sizeof(*sin);
#endif
        sin->sin_family         = AF_INET;
        sin->sin_port           = dstPort.NotAnInteger;
        sin->sin_addr.s_addr    = dst->ip.v4.NotAnInteger;
        sendingsocket           = thisIntf ? thisIntf->multicastSocket4 : m->p->unicastSocket4;
    }

#if HAVE_IPV6
    else if (dst->type == mDNSAddrType_IPv6)
    {
        struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&to;
        mDNSPlatformMemZero(sin6, sizeof(*sin6));
#ifndef NOT_HAVE_SA_LEN
        sin6->sin6_len            = sizeof(*sin6);
#endif
        sin6->sin6_family         = AF_INET6;
        sin6->sin6_port           = dstPort.NotAnInteger;
        sin6->sin6_addr           = *(struct in6_addr*)&dst->ip.v6;
        sendingsocket             = thisIntf ? thisIntf->multicastSocket6 : m->p->unicastSocket6;
    }
#endif

    if (sendingsocket >= 0)
        err = sendto(sendingsocket, msg, (char*)end - (char*)msg, 0, (struct sockaddr *)&to, GET_SA_LEN(to));

    if      (err > 0) err = 0;
    else if (err < 0)
    {
        static int MessageCount = 0;
        // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
        if (!mDNSAddressIsAllDNSLinkGroup(dst))
            if (errno == EHOSTDOWN || errno == ENETDOWN || errno == EHOSTUNREACH || errno == ENETUNREACH) return(mStatus_TransientErr);

	/* dont report ENETUNREACH */
	if (errno == ENETUNREACH) return(mStatus_TransientErr);

        if (MessageCount < 1000)
        {
            MessageCount++;
            if (thisIntf)
                LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
                       errno, strerror(errno), dst, &thisIntf->coreIntf.ip, thisIntf->intfName, thisIntf->index);
            else
                LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno, strerror(errno), dst);
        }
    }

    return PosixErrorToStatus(err);
}

mDNSlocal void TCPReadCallback(int fd, void *context)
{
    TCPSocket *sock = context;
    (void)fd;

    if (sock->flags & kTCPSocketFlags_UseTLS)
    {
        // implement
    }
    else
    {
        sock->callback(sock, sock->context, mDNSfalse, sock->err);
    }
}

mDNSlocal void tcpConnectCallback(int fd, void *context)
{
    TCPSocket *sock = context;
    mDNSBool c = !sock->connected;
    int result;
    socklen_t len = sizeof result;

    sock->connected = mDNStrue;

    if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &result, &len) < 0)
    {
        LogInfo("ERROR: TCPConnectCallback - unable to get connect error: socket %d: Error %d (%s)",
               sock->events.fd, result, strerror(result));
        sock->err = mStatus_ConnFailed;
    }
    else
    {
        if (result != 0)
        {
            sock->err = mStatus_ConnFailed;
            if (result == EHOSTUNREACH || result == EADDRNOTAVAIL || result == ENETDOWN)
            {
                LogInfo("ERROR: TCPConnectCallback - connect failed: socket %d: Error %d (%s)",
                        sock->events.fd, result, strerror(result));
            }
            else
            {
                LogMsg("ERROR: TCPConnectCallback - connect failed: socket %d: Error %d (%s)",
                       sock->events.fd, result, strerror(result));
            }
        }
        else
        {
            // The connection succeeded.
            sock->connected = mDNStrue;
            // Select for read events.
            sock->events.fd = fd;
            requestReadEvents(&sock->events, "mDNSPosix::tcpConnectCallback", TCPReadCallback, sock);
        }
    }

    if (sock->callback)
    {
        sock->callback(sock, sock->context, c, sock->err);
        // Here sock must be assumed to be invalid, in case the callback freed it.
        return;
    }
}

// This routine is called when the main loop detects that data is available on a socket.
mDNSlocal void SocketDataReady(mDNS *const m, PosixNetworkInterface *intf, int skt)
{
    mDNSAddr senderAddr, destAddr;
    mDNSIPPort senderPort;
    ssize_t packetLen;
    DNSMessage packet;
    struct my_in_pktinfo packetInfo;
    struct sockaddr_storage from;
    socklen_t fromLen;
    int flags;
    mDNSu8 ttl;
    mDNSBool reject;
    const mDNSInterfaceID InterfaceID = intf ? intf->coreIntf.InterfaceID : NULL;

    assert(m    != NULL);
    assert(skt  >= 0);

    fromLen = sizeof(from);
    flags   = 0;
    packetLen = recvfrom_flags(skt, &packet, sizeof(packet), &flags, (struct sockaddr *) &from, &fromLen, &packetInfo, &ttl);

    if (packetLen >= 0)
    {
        SockAddrTomDNSAddr((struct sockaddr*)&from, &senderAddr, &senderPort);
        SockAddrTomDNSAddr((struct sockaddr*)&packetInfo.ipi_addr, &destAddr, NULL);

        // If we have broken IP_RECVDSTADDR functionality (so far
        // I've only seen this on OpenBSD) then apply a hack to
        // convince mDNS Core that this isn't a spoof packet.
        // Basically what we do is check to see whether the
        // packet arrived as a multicast and, if so, set its
        // destAddr to the mDNS address.
        //
        // I must admit that I could just be doing something
        // wrong on OpenBSD and hence triggering this problem
        // but I'm at a loss as to how.
        //
        // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
        // no way to tell the destination address or interface this packet arrived on,
        // so all we can do is just assume it's a multicast

        #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
        if ((destAddr.NotAnInteger == 0) && (flags & MSG_MCAST))
        {
            destAddr.type = senderAddr.type;
            if      (senderAddr.type == mDNSAddrType_IPv4) destAddr.ip.v4 = AllDNSLinkGroup_v4.ip.v4;
            else if (senderAddr.type == mDNSAddrType_IPv6) destAddr.ip.v6 = AllDNSLinkGroup_v6.ip.v6;
        }
        #endif

        // We only accept the packet if the interface on which it came
        // in matches the interface associated with this socket.
        // We do this match by name or by index, depending on which
        // information is available.  recvfrom_flags sets the name
        // to "" if the name isn't available, or the index to -1
        // if the index is available.  This accomodates the various
        // different capabilities of our target platforms.

        reject = mDNSfalse;
        if (!intf)
        {
            // Ignore multicasts accidentally delivered to our unicast receiving socket
            if (mDNSAddrIsDNSMulticast(&destAddr)) packetLen = -1;
        }
        else
        {
            if      (packetInfo.ipi_ifname[0] != 0) reject = (strcmp(packetInfo.ipi_ifname, intf->intfName) != 0);
            else if (packetInfo.ipi_ifindex != -1) reject = (packetInfo.ipi_ifindex != intf->index);

            if (reject)
            {
                verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
                              &senderAddr, &destAddr, packetInfo.ipi_ifname, packetInfo.ipi_ifindex,
                              &intf->coreIntf.ip, intf->intfName, intf->index, skt);
                packetLen = -1;
                num_pkts_rejected++;
                if (num_pkts_rejected > (num_pkts_accepted + 1) * (num_registered_interfaces + 1) * 2)
                {
                    fprintf(stderr,
                            "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
                            num_pkts_accepted + num_pkts_rejected, num_pkts_accepted, num_pkts_rejected);
                    num_pkts_accepted = 0;
                    num_pkts_rejected = 0;
                }
            }
            else
            {
                verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
                              &senderAddr, &destAddr, &intf->coreIntf.ip, intf->intfName, intf->index, skt);
                num_pkts_accepted++;
            }
        }
    }

    if (packetLen >= 0)
        mDNSCoreReceive(m, &packet, (mDNSu8 *)&packet + packetLen,
                        &senderAddr, senderPort, &destAddr, MulticastDNSPort, InterfaceID);
}

mDNSexport TCPSocket *mDNSPlatformTCPSocket(TCPSocketFlags flags, mDNSAddr_Type addrType, mDNSIPPort * port,
                                            domainname *hostname, mDNSBool useBackgroundTrafficClass)
{
    TCPSocket *sock;
    int len = sizeof (TCPSocket);

    (void)useBackgroundTrafficClass;

    if (hostname)
    {
        len += sizeof (domainname);
    }
    sock = malloc(len);

    if (sock == NULL)
    {
        LogMsg("mDNSPlatformTCPSocket: no memory for socket");
        return NULL;
    }
    memset(sock, 0, sizeof *sock);

    if (hostname)
    {
        sock->hostname = (domainname *)(sock + 1);
        LogMsg("mDNSPlatformTCPSocket: hostname %##s", hostname->c);
        AssignDomainName(sock->hostname, hostname);
    }

    sock->events.fd = -1;
    if (!mDNSPosixTCPSocketSetup(&sock->events.fd, addrType, port, &sock->port))
    {
      if (sock->events.fd != -1) close(sock->events.fd);
      free(sock);
      return mDNSNULL;
    }

    // Set up the other fields in the structure.
    sock->flags = flags;
    sock->err = mStatus_NoError;
    sock->setup = mDNSfalse;
    sock->connected = mDNSfalse;
    return sock;
}

mDNSexport mStatus mDNSPlatformTCPSocketSetCallback(TCPSocket *sock, TCPConnectionCallback callback, void *context)
{
    sock->callback = callback;
    sock->context = context;
    return mStatus_NoError;
}

mDNSexport TCPSocket *mDNSPlatformTCPAccept(TCPSocketFlags flags, int fd)
{
    TCPSocket *sock;

    // XXX Add!
    if (flags & kTCPSocketFlags_UseTLS)
    {
    return mDNSNULL; // not supported yet.
    }

    sock = (TCPSocket *) mDNSPlatformMemAllocateClear(sizeof *sock);
    if (!sock)
    {
        return mDNSNULL;
    }

    sock->events.fd = fd;
    sock->flags = flags;
    sock->connected = mDNStrue;
    return sock;
}


mDNSlocal void tcpListenCallback(int fd, void *context)
{
    TCPListener *listener = context;
    TCPSocket *sock;

    sock = mDNSPosixDoTCPListenCallback(fd, listener->addressType, listener->socketFlags,
                                 listener->callback, listener->context);
    if (sock != NULL)
    {
        requestReadEvents(&sock->events, "mDNSPosix::tcpListenCallback", TCPReadCallback, sock);
    }
}

mDNSexport TCPListener *mDNSPlatformTCPListen(mDNSAddr_Type addrType, mDNSIPPort *port, mDNSAddr *addr,
                                              TCPSocketFlags socketFlags, mDNSBool reuseAddr, int queueLength,
                                              TCPAcceptedCallback callback, void *context)
{
    TCPListener *ret;
    int fd = -1;

    if (!mDNSPosixTCPListen(&fd, addrType, port, addr, reuseAddr, queueLength))
    {
        if (fd != -1)
        {
            close(fd);
        }
        return mDNSNULL;
    }

    // Allocate a listener structure
    ret = (TCPListener *) mDNSPlatformMemAllocateClear(sizeof *ret);
    if (ret == NULL)
    {
        LogMsg("mDNSPlatformTCPListen: no memory for TCPListener struct.");
        close(fd);
        return mDNSNULL;
    }
    ret->events.fd = fd;
    ret->callback = callback;
    ret->context = context;
    ret->addressType = addrType;
    ret->socketFlags = socketFlags;

    // When we get a connection, mDNSPosixListenCallback will be called, and it will invoke the
    // callback we were passed.
    requestReadEvents(&ret->events, "tcpListenCallback", tcpListenCallback, ret);
    return ret;
}

mDNSexport int mDNSPlatformTCPGetFD(TCPSocket *sock)
{
    return sock->events.fd;
}

mDNSexport mStatus mDNSPlatformTCPConnect(TCPSocket *sock, const mDNSAddr *dst, mDNSOpaque16 dstport,
                                          mDNSInterfaceID InterfaceID, TCPConnectionCallback callback, void *context)
{
    int result;
    union {
        struct sockaddr sa;
        struct sockaddr_in sin;
        struct sockaddr_in6 sin6;
    } addr;
    socklen_t len;

    sock->callback = callback;
    sock->context = context;
    sock->setup = mDNSfalse;
    sock->connected = mDNSfalse;
    sock->err = mStatus_NoError;

    result = fcntl(sock->events.fd, F_GETFL, 0);
    if (result < 0)
    {
        LogMsg("mDNSPlatformTCPConnect: F_GETFL failed: %s", strerror(errno));
        return mStatus_UnknownErr;
    }

    result = fcntl(sock->events.fd, F_SETFL, result | O_NONBLOCK);
    if (result < 0)
    {
        LogMsg("mDNSPlatformTCPConnect: F_SETFL failed: %s", strerror(errno));
        return mStatus_UnknownErr;
    }

    // If we've been asked to bind to a single interface, do it.  See comment in mDNSMacOSX.c for more info.
    if (InterfaceID)
    {
        PosixNetworkInterface *iface = (PosixNetworkInterface *)InterfaceID;
#if defined(SO_BINDTODEVICE)
        result = setsockopt(sock->events.fd,
                            SOL_SOCKET, SO_BINDTODEVICE, iface->intfName, strlen(iface->intfName));
        if (result < 0)
        {
            LogMsg("mDNSPlatformTCPConnect: SO_BINDTODEVICE failed on %s: %s", iface->intfName, strerror(errno));
            return mStatus_BadParamErr;
        }
#else
        if (dst->type == mDNSAddrType_IPv4)
        {
#if defined(IP_BOUND_IF)
            result = setsockopt(sock->events.fd, IPPROTO_IP, IP_BOUND_IF, &iface->index, sizeof iface->index);
            if (result < 0)
            {
                LogMsg("mDNSPlatformTCPConnect: IP_BOUND_IF failed on %s (%d): %s",
                       iface->intfName, iface->index, strerror(errno));
                return mStatus_BadParamErr;
            }
#else
            (void)iface;
#endif // IP_BOUND_IF
        }
        else
        { // IPv6
#if defined(IPV6_BOUND_IF)
            result = setsockopt(sock->events.fd, IPPROTO_IPV6, IPV6_BOUND_IF, &iface->index, sizeof iface->index);
            if (result < 0)
            {
                LogMsg("mDNSPlatformTCPConnect: IP_BOUND_IF failed on %s (%d): %s",
                       iface->intfName, iface->index, strerror(errno));
                return mStatus_BadParamErr;
            }
#else
            (void)iface;
#endif // IPV6_BOUND_IF
        }
#endif // SO_BINDTODEVICE
    }

    memset(&addr, 0, sizeof addr);
    if (dst->type == mDNSAddrType_IPv4)
    {
        addr.sa.sa_family = AF_INET;
        addr.sin.sin_port = dstport.NotAnInteger;
        len = sizeof (struct sockaddr_in);
        addr.sin.sin_addr.s_addr = dst->ip.v4.NotAnInteger;
    }
    else
    {
        addr.sa.sa_family = AF_INET6;
        len = sizeof (struct sockaddr_in6);
        addr.sin6.sin6_port = dstport.NotAnInteger;
        memcpy(&addr.sin6.sin6_addr.s6_addr, &dst->ip.v6, sizeof addr.sin6.sin6_addr.s6_addr);
    }
#ifndef NOT_HAVE_SA_LEN
    addr.sa.sa_len = len;
#endif

    result = connect(sock->events.fd, (struct sockaddr *)&addr, len);
    if (result < 0)
    {
        if (errno == EINPROGRESS)
        {
            requestWriteEvents(&sock->events, "mDNSPlatformConnect", tcpConnectCallback, sock);
            return mStatus_ConnPending;
        }
        if (errno == EHOSTUNREACH || errno == EADDRNOTAVAIL || errno == ENETDOWN)
        {
            LogInfo("ERROR: mDNSPlatformTCPConnect - connect failed: socket %d: Error %d (%s)",
                    sock->events.fd, errno, strerror(errno));
        }
        else
        {
            LogMsg("ERROR: mDNSPlatformTCPConnect - connect failed: socket %d: Error %d (%s) length %d",
                   sock->events.fd, errno, strerror(errno), len);
        }
        return mStatus_ConnFailed;
    }

    LogMsg("NOTE: mDNSPlatformTCPConnect completed synchronously");
    return mStatus_NoError;
}

mDNSexport void mDNSPlatformTCPCloseConnection(TCPSocket *sock)
{
    if (sock)
    { // can sock really be NULL when this is called?
        shutdown(sock->events.fd, SHUT_RDWR);
        stopReadOrWriteEvents(sock->events.fd, mDNSfalse, mDNStrue,
                              PosixEventFlag_Read | PosixEventFlag_Write);
        close(sock->events.fd);
        free(sock);
    }
}

mDNSexport long mDNSPlatformReadTCP(TCPSocket *sock, void *buf, unsigned long buflen, mDNSBool * closed)
{
    ssize_t nread;

    *closed = mDNSfalse;
    if (sock->flags & kTCPSocketFlags_UseTLS)
    {
        // Implement...
        nread = -1;
        *closed = mDNStrue;
    } else {
        nread = mDNSPosixReadTCP(sock->events.fd, buf, buflen, closed);
    }
    return nread;
}

mDNSexport mDNSBool mDNSPlatformTCPWritable(TCPSocket *sock)
{
    fd_set w = { 0 };
    int nfds = sock->events.fd + 1;
    int count;
    struct timeval tv;

    if (nfds > FD_SETSIZE)
    {
        LogMsg("ERROR: mDNSPlatformTCPWritable called on an fd that won't fit in an fd_set.");
        return mDNStrue; // hope for the best?
    }
    FD_SET(sock->events.fd, &w);
    tv.tv_sec = tv.tv_usec = 0;
    count = select(nfds, NULL, &w, NULL, &tv);
    if (count > 0)
    {
        return mDNStrue;
    }
    return mDNSfalse;
}

mDNSexport long mDNSPlatformWriteTCP(TCPSocket *sock, const char *msg, unsigned long len)
{
    if (sock->flags & kTCPSocketFlags_UseTLS)
    {
        // implement
        return -1;
    }
    else
    {
        return mDNSPosixWriteTCP(sock->events.fd, msg, len);
    }
}

mDNSexport UDPSocket *mDNSPlatformUDPSocket(mDNSIPPort port)
{
    (void)port;         // Unused
    return NULL;
}

mDNSexport void           mDNSPlatformUDPClose(UDPSocket *sock)
{
    (void)sock;         // Unused
}

mDNSexport void mDNSPlatformUpdateProxyList(const mDNSInterfaceID InterfaceID)
{
    (void)InterfaceID;          // Unused
}

mDNSexport void mDNSPlatformSendRawPacket(const void *const msg, const mDNSu8 *const end, mDNSInterfaceID InterfaceID)
{
    (void)msg;          // Unused
    (void)end;          // Unused
    (void)InterfaceID;          // Unused
}

mDNSexport void mDNSPlatformSetLocalAddressCacheEntry(const mDNSAddr *const tpa, const mDNSEthAddr *const tha, mDNSInterfaceID InterfaceID)
{
    (void)tpa;          // Unused
    (void)tha;          // Unused
    (void)InterfaceID;          // Unused
}

mDNSexport mStatus mDNSPlatformTLSSetupCerts(void)
{
    return(mStatus_UnsupportedErr);
}

mDNSexport void mDNSPlatformTLSTearDownCerts(void)
{
}

mDNSexport void mDNSPlatformSetAllowSleep(mDNSBool allowSleep, const char *reason)
{
    (void) allowSleep;
    (void) reason;
}

#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - /etc/hosts support
#endif

mDNSexport void FreeEtcHosts(mDNS *const m, AuthRecord *const rr, mStatus result)
{
    (void)m;  // unused
    (void)rr;
    (void)result;
}


#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark ***** DDNS Config Platform Functions
#endif

mDNSexport mDNSBool mDNSPlatformSetDNSConfig(mDNSBool setservers, mDNSBool setsearch, domainname *const fqdn, DNameListElem **RegDomains,
    DNameListElem **BrowseDomains, mDNSBool ackConfig)
{
    (void) setservers;
    (void) setsearch;
    (void) ackConfig;

    if (fqdn         ) fqdn->c[0]      = 0;
    if (RegDomains   ) *RegDomains     = NULL;
    if (BrowseDomains) *BrowseDomains  = NULL;

    return mDNStrue;
}

mDNSexport mStatus mDNSPlatformGetPrimaryInterface(mDNSAddr * v4, mDNSAddr * v6, mDNSAddr * router)
{
    (void) v4;
    (void) v6;
    (void) router;

    return mStatus_UnsupportedErr;
}

mDNSexport void mDNSPlatformDynDNSHostNameStatusChanged(const domainname *const dname, const mStatus status)
{
    (void) dname;
    (void) status;
}

#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark ***** Init and Term
#endif

// This gets the current hostname, truncating it at the first dot if necessary
mDNSlocal void GetUserSpecifiedRFC1034ComputerName(domainlabel *const namelabel)
{
    int len = 0;
    gethostname((char *)(&namelabel->c[1]), MAX_DOMAIN_LABEL);
    while (len < MAX_DOMAIN_LABEL && namelabel->c[len+1] && namelabel->c[len+1] != '.') len++;
    namelabel->c[0] = len;
}

// On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
// Other platforms can either get the information from the appropriate place,
// or they can alternatively just require all registering services to provide an explicit name
mDNSlocal void GetUserSpecifiedFriendlyComputerName(domainlabel *const namelabel)
{
    // On Unix we have no better name than the host name, so we just use that.
    GetUserSpecifiedRFC1034ComputerName(namelabel);
}

mDNSexport int ParseDNSServers(mDNS *m, const char *filePath)
{
    char line[256];
    char nameserver[16];
    char keyword[11];
    int numOfServers = 0;
    FILE *fp = fopen(filePath, "r");
    if (fp == NULL) return -1;
    while (fgets(line,sizeof(line),fp))
    {
        struct in_addr ina;
        line[255]='\0';     // just to be safe
        if (sscanf(line,"%10s %15s", keyword, nameserver) != 2) continue;   // it will skip whitespaces
        if (strncasecmp(keyword,"nameserver",10)) continue;
        if (inet_aton(nameserver, (struct in_addr *)&ina) != 0)
        {
            mDNSAddr DNSAddr;
            DNSAddr.type = mDNSAddrType_IPv4;
            DNSAddr.ip.v4.NotAnInteger = ina.s_addr;
            mDNS_AddDNSServer(m, NULL, mDNSInterface_Any, 0, &DNSAddr, UnicastDNSPort, kScopeNone, 0, mDNSfalse, mDNSfalse, mDNSfalse, mDNSfalse, 0, mDNStrue, mDNStrue, mDNSfalse);
            numOfServers++;
        }
    }
    fclose(fp);
    return (numOfServers > 0) ? 0 : -1;
}

// Searches the interface list looking for the named interface.
// Returns a pointer to if it found, or NULL otherwise.
mDNSlocal PosixNetworkInterface *SearchForInterfaceByName(mDNS *const m, const char *intfName)
{
    PosixNetworkInterface *intf;

    assert(m != NULL);
    assert(intfName != NULL);

    intf = (PosixNetworkInterface*)(m->HostInterfaces);
    while ((intf != NULL) && (strcmp(intf->intfName, intfName) != 0))
        intf = (PosixNetworkInterface *)(intf->coreIntf.next);

    return intf;
}

mDNSexport mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS *const m, mDNSu32 index)
{
    PosixNetworkInterface *intf;

    assert(m != NULL);

    if (index == kDNSServiceInterfaceIndexLocalOnly) return(mDNSInterface_LocalOnly);
    if (index == kDNSServiceInterfaceIndexP2P      ) return(mDNSInterface_P2P);
    if (index == kDNSServiceInterfaceIndexAny      ) return(mDNSInterface_Any);

    intf = (PosixNetworkInterface*)(m->HostInterfaces);
    while ((intf != NULL) && (mDNSu32) intf->index != index)
        intf = (PosixNetworkInterface *)(intf->coreIntf.next);

    return (mDNSInterfaceID) intf;
}

mDNSexport mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(mDNS *const m, mDNSInterfaceID id, mDNSBool suppressNetworkChange)
{
    PosixNetworkInterface *intf;
    (void) suppressNetworkChange; // Unused

    assert(m != NULL);

    if (id == mDNSInterface_LocalOnly) return(kDNSServiceInterfaceIndexLocalOnly);
    if (id == mDNSInterface_P2P      ) return(kDNSServiceInterfaceIndexP2P);
    if (id == mDNSInterface_Any      ) return(kDNSServiceInterfaceIndexAny);

    intf = (PosixNetworkInterface*)(m->HostInterfaces);
    while ((intf != NULL) && (mDNSInterfaceID) intf != id)
        intf = (PosixNetworkInterface *)(intf->coreIntf.next);

    if (intf) return intf->index;

    // If we didn't find the interface, check the RecentInterfaces list as well
    intf = gRecentInterfaces;
    while ((intf != NULL) && (mDNSInterfaceID) intf != id)
        intf = (PosixNetworkInterface *)(intf->coreIntf.next);

    return intf ? intf->index : 0;
}

// Frees the specified PosixNetworkInterface structure. The underlying
// interface must have already been deregistered with the mDNS core.
mDNSlocal void FreePosixNetworkInterface(PosixNetworkInterface *intf)
{
    int rv;
    assert(intf != NULL);
    if (intf->intfName != NULL) free((void *)intf->intfName);
    if (intf->multicastSocket4 != -1)
    {
        rv = close(intf->multicastSocket4);
        assert(rv == 0);
    }
#if HAVE_IPV6
    if (intf->multicastSocket6 != -1)
    {
        rv = close(intf->multicastSocket6);
        assert(rv == 0);
    }
#endif

    // Move interface to the RecentInterfaces list for a minute
    intf->LastSeen = mDNSPlatformUTC();
    intf->coreIntf.next = &gRecentInterfaces->coreIntf;
    gRecentInterfaces = intf;
}

// Grab the first interface, deregister it, free it, and repeat until done.
mDNSlocal void ClearInterfaceList(mDNS *const m)
{
    assert(m != NULL);

    while (m->HostInterfaces)
    {
        PosixNetworkInterface *intf = (PosixNetworkInterface*)(m->HostInterfaces);
        mDNS_DeregisterInterface(m, &intf->coreIntf, NormalActivation);
        if (gMDNSPlatformPosixVerboseLevel > 0) fprintf(stderr, "Deregistered interface %s\n", intf->intfName);
        FreePosixNetworkInterface(intf);
    }
    num_registered_interfaces = 0;
    num_pkts_accepted = 0;
    num_pkts_rejected = 0;
}

// Sets up a send/receive socket.
// If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
// If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
mDNSlocal int SetupSocket(struct sockaddr *intfAddr, mDNSIPPort port, int interfaceIndex, int *sktPtr)
{
    int err = 0;
    static const int kOn = 1;
    static const int kIntTwoFiveFive = 255;
    static const unsigned char kByteTwoFiveFive = 255;
    const mDNSBool JoinMulticastGroup = (port.NotAnInteger != 0);

    (void) interfaceIndex;  // This parameter unused on plaforms that don't have IPv6
    assert(intfAddr != NULL);
    assert(sktPtr != NULL);
    assert(*sktPtr == -1);

    // Open the socket...
    if      (intfAddr->sa_family == AF_INET) *sktPtr = socket(PF_INET,  SOCK_DGRAM, IPPROTO_UDP);
#if HAVE_IPV6
    else if (intfAddr->sa_family == AF_INET6) *sktPtr = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
#endif
    else return EINVAL;

    if (*sktPtr < 0) { err = errno; perror((intfAddr->sa_family == AF_INET) ? "socket AF_INET" : "socket AF_INET6"); }

    // ... with a shared UDP port, if it's for multicast receiving
    if (err == 0 && port.NotAnInteger)
    {
        // <rdar://problem/20946253> Suggestions from Jonny Törnbom at Axis Communications
        // We test for SO_REUSEADDR first, as suggested by Jonny Törnbom from Axis Communications
        // Linux kernel versions 3.9 introduces support for socket option
        // SO_REUSEPORT, however this is not implemented the same as on *BSD
        // systems. Linux version implements a "port hijacking" prevention
        // mechanism, limiting processes wanting to bind to an already existing
        // addr:port to have the same effective UID as the first who bound it. What
        // this meant for us was that the daemon ran as one user and when for
        // instance mDNSClientPosix was executed by another user, it wasn't allowed
        // to bind to the socket. Our suggestion was to switch the order in which
        // SO_REUSEPORT and SO_REUSEADDR was tested so that SO_REUSEADDR stays on
        // top and SO_REUSEPORT to be used only if SO_REUSEADDR doesn't exist.
        #if defined(SO_REUSEADDR) && !defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
        err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
        #elif defined(SO_REUSEPORT)
        err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEPORT, &kOn, sizeof(kOn));
        #else
            #error This platform has no way to avoid address busy errors on multicast.
        #endif
        if (err < 0) { err = errno; perror("setsockopt - SO_REUSExxxx"); }

#if TARGET_OS_MAC
        // Enable inbound packets on IFEF_AWDL interface.
        // Only done for multicast sockets, since we don't expect unicast socket operations
        // on the IFEF_AWDL interface. Operation is a no-op for other interface types.
        #ifndef SO_RECV_ANYIF
        #define SO_RECV_ANYIF   0x1104      /* unrestricted inbound processing */
        #endif
        if (setsockopt(*sktPtr, SOL_SOCKET, SO_RECV_ANYIF, &kOn, sizeof(kOn)) < 0) perror("setsockopt - SO_RECV_ANYIF");
#endif
    }

    // We want to receive destination addresses and interface identifiers.
    if (intfAddr->sa_family == AF_INET)
    {
        struct ip_mreq imr;
        struct sockaddr_in bindAddr;
        if (err == 0)
        {
            #if defined(IP_PKTINFO)                                 // Linux
            err = setsockopt(*sktPtr, IPPROTO_IP, IP_PKTINFO, &kOn, sizeof(kOn));
            if (err < 0) { err = errno; perror("setsockopt - IP_PKTINFO"); }
            #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF)     // BSD and Solaris
                #if defined(IP_RECVDSTADDR)
            err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVDSTADDR, &kOn, sizeof(kOn));
            if (err < 0) { err = errno; perror("setsockopt - IP_RECVDSTADDR"); }
                #endif
                #if defined(IP_RECVIF)
            if (err == 0)
            {
                err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVIF, &kOn, sizeof(kOn));
                if (err < 0) { err = errno; perror("setsockopt - IP_RECVIF"); }
            }
                #endif
            #else
                #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
            #endif
        }
    #if defined(IP_RECVTTL)                                 // Linux
        if (err == 0)
        {
            setsockopt(*sktPtr, IPPROTO_IP, IP_RECVTTL, &kOn, sizeof(kOn));
            // We no longer depend on being able to get the received TTL, so don't worry if the option fails
        }
    #endif

        // Add multicast group membership on this interface
        if (err == 0 && JoinMulticastGroup)
        {
            imr.imr_multiaddr.s_addr = AllDNSLinkGroup_v4.ip.v4.NotAnInteger;
            imr.imr_interface        = ((struct sockaddr_in*)intfAddr)->sin_addr;
            err = setsockopt(*sktPtr, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(imr));
            if (err < 0) { err = errno; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
        }

        // Specify outgoing interface too
        if (err == 0 && JoinMulticastGroup)
        {
            err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_IF, &((struct sockaddr_in*)intfAddr)->sin_addr, sizeof(struct in_addr));
            if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_IF"); }
        }

        // Per the mDNS spec, send unicast packets with TTL 255
        if (err == 0)
        {
            err = setsockopt(*sktPtr, IPPROTO_IP, IP_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
            if (err < 0) { err = errno; perror("setsockopt - IP_TTL"); }
        }

        // and multicast packets with TTL 255 too
        // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
        if (err == 0)
        {
            err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
            if (err < 0 && errno == EINVAL)
                err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
            if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_TTL"); }
        }

        // And start listening for packets
        if (err == 0)
        {
            bindAddr.sin_family      = AF_INET;
            bindAddr.sin_port        = port.NotAnInteger;
            bindAddr.sin_addr.s_addr = INADDR_ANY; // Want to receive multicasts AND unicasts on this socket
            err = bind(*sktPtr, (struct sockaddr *) &bindAddr, sizeof(bindAddr));
            if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
        }
    }     // endif (intfAddr->sa_family == AF_INET)

#if HAVE_IPV6
    else if (intfAddr->sa_family == AF_INET6)
    {
        struct ipv6_mreq imr6;
        struct sockaddr_in6 bindAddr6;
    #if defined(IPV6_RECVPKTINFO) // Solaris
	if (err == 0)
	{
	    err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_RECVPKTINFO, &kOn, sizeof(kOn));
	    if (err < 0) { err = errno; perror("setsockopt - IPV6_RECVPKTINFO"); }
	}
    #elif defined(IPV6_PKTINFO)
        if (err == 0)
        {
            err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_PKTINFO, &kOn, sizeof(kOn));
            if (err < 0) { err = errno; perror("setsockopt - IPV6_PKTINFO"); }
        }
    #else
        #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
    #endif
    #if defined(IPV6_RECVHOPLIMIT)
	if (err == 0)
	{
	    err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &kOn, sizeof(kOn));
	    if (err < 0) { err = errno; perror("setsockopt - IPV6_RECVHOPLIMIT"); }
	}
    #elif defined(IPV6_HOPLIMIT)
        if (err == 0)
        {
            err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_HOPLIMIT, &kOn, sizeof(kOn));
            if (err < 0) { err = errno; perror("setsockopt - IPV6_HOPLIMIT"); }
        }
    #endif

        // Add multicast group membership on this interface
        if (err == 0 && JoinMulticastGroup)
        {
            imr6.ipv6mr_multiaddr       = *(const struct in6_addr*)&AllDNSLinkGroup_v6.ip.v6;
            imr6.ipv6mr_interface       = interfaceIndex;
            //LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
            err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_JOIN_GROUP, &imr6, sizeof(imr6));
            if (err < 0)
            {
                err = errno;
                verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
                perror("setsockopt - IPV6_JOIN_GROUP");
            }
        }

        // Specify outgoing interface too
        if (err == 0 && JoinMulticastGroup)
        {
            u_int multicast_if = interfaceIndex;
            err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_IF, &multicast_if, sizeof(multicast_if));
            if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_IF"); }
        }

        // We want to receive only IPv6 packets on this socket.
        // Without this option, we may get IPv4 addresses as mapped addresses.
        if (err == 0)
        {
            err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_V6ONLY, &kOn, sizeof(kOn));
            if (err < 0) { err = errno; perror("setsockopt - IPV6_V6ONLY"); }
        }

        // Per the mDNS spec, send unicast packets with TTL 255
        if (err == 0)
        {
            err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
            if (err < 0) { err = errno; perror("setsockopt - IPV6_UNICAST_HOPS"); }
        }

        // and multicast packets with TTL 255 too
        // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
        if (err == 0)
        {
            err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
            if (err < 0 && errno == EINVAL)
                err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
            if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
        }

        // And start listening for packets
        if (err == 0)
        {
            mDNSPlatformMemZero(&bindAddr6, sizeof(bindAddr6));
#ifndef NOT_HAVE_SA_LEN
            bindAddr6.sin6_len         = sizeof(bindAddr6);
#endif
            bindAddr6.sin6_family      = AF_INET6;
            bindAddr6.sin6_port        = port.NotAnInteger;
            bindAddr6.sin6_flowinfo    = 0;
            bindAddr6.sin6_addr        = in6addr_any; // Want to receive multicasts AND unicasts on this socket
            bindAddr6.sin6_scope_id    = 0;
            err = bind(*sktPtr, (struct sockaddr *) &bindAddr6, sizeof(bindAddr6));
            if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
        }
    }     // endif (intfAddr->sa_family == AF_INET6)
#endif

    // Set the socket to non-blocking.
    if (err == 0)
    {
        err = fcntl(*sktPtr, F_GETFL, 0);
        if (err < 0) err = errno;
        else
        {
            err = fcntl(*sktPtr, F_SETFL, err | O_NONBLOCK);
            if (err < 0) err = errno;
        }
    }

    // Clean up
    if (err != 0 && *sktPtr != -1)
    {
        int rv;
        rv = close(*sktPtr);
        assert(rv == 0);
        *sktPtr = -1;
    }
    assert((err == 0) == (*sktPtr != -1));
    return err;
}

// Creates a PosixNetworkInterface for the interface whose IP address is
// intfAddr and whose name is intfName and registers it with mDNS core.
mDNSlocal int SetupOneInterface(mDNS *const m, struct sockaddr *intfAddr, struct sockaddr *intfMask, const char *intfName, int intfIndex)
{
    int err = 0;
    PosixNetworkInterface *intf;
    PosixNetworkInterface *alias = NULL;

    assert(m != NULL);
    assert(intfAddr != NULL);
    assert(intfName != NULL);
    assert(intfMask != NULL);

    // Allocate the interface structure itself.
    intf = (PosixNetworkInterface*)calloc(1, sizeof(*intf));
    if (intf == NULL) { assert(0); err = ENOMEM; }

    // And make a copy of the intfName.
    if (err == 0)
    {
#ifdef LINUX
        char *s;
        int len;
        s = strchr(intfName, ':');
        if (s != NULL)
        {
            len = (s - intfName) + 1;
        }
        else
        {
            len = strlen(intfName) + 1;
        }
        intf->intfName = malloc(len);
        if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
        memcpy(intf->intfName, intfName, len - 1);
        intfName[len - 1] = 0;
#else
        intf->intfName = strdup(intfName);
        if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
#endif
    }

    if (err == 0)
    {
        // Set up the fields required by the mDNS core.
        SockAddrTomDNSAddr(intfAddr, &intf->coreIntf.ip, NULL);
        SockAddrTomDNSAddr(intfMask, &intf->coreIntf.mask, NULL);

        //LogMsg("SetupOneInterface: %#a %#a",  &intf->coreIntf.ip,  &intf->coreIntf.mask);
        strncpy(intf->coreIntf.ifname, intfName, sizeof(intf->coreIntf.ifname));
        intf->coreIntf.ifname[sizeof(intf->coreIntf.ifname)-1] = 0;

        intf->coreIntf.Advertise = m->AdvertiseLocalAddresses;
        intf->coreIntf.McastTxRx = mDNStrue;

        // Set up the extra fields in PosixNetworkInterface.
        assert(intf->intfName != NULL);         // intf->intfName already set up above
        intf->index                = intfIndex;
        intf->multicastSocket4     = -1;
#if HAVE_IPV6
        intf->multicastSocket6     = -1;
#endif
        alias                      = SearchForInterfaceByName(m, intf->intfName);
        if (alias == NULL) alias   = intf;
        intf->coreIntf.InterfaceID = (mDNSInterfaceID)alias;

        if (alias != intf)
            debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName, &intf->coreIntf.ip, &alias->coreIntf.ip);
    }

    // Set up the multicast socket
    if (err == 0)
    {
        if (alias->multicastSocket4 == -1 && intfAddr->sa_family == AF_INET)
            err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket4);
#if HAVE_IPV6
        else if (alias->multicastSocket6 == -1 && intfAddr->sa_family == AF_INET6)
            err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket6);
#endif
    }

    // If interface is a direct link, address record will be marked as kDNSRecordTypeKnownUnique
    // and skip the probe phase of the probe/announce packet sequence.
    intf->coreIntf.DirectLink = mDNSfalse;
#ifdef DIRECTLINK_INTERFACE_NAME
    if (strcmp(intfName, STRINGIFY(DIRECTLINK_INTERFACE_NAME)) == 0)
        intf->coreIntf.DirectLink = mDNStrue;
#endif
    intf->coreIntf.SupportsUnicastMDNSResponse = mDNStrue;

    // The interface is all ready to go, let's register it with the mDNS core.
    if (err == 0)
        err = mDNS_RegisterInterface(m, &intf->coreIntf, NormalActivation);

    // Clean up.
    if (err == 0)
    {
        num_registered_interfaces++;
        debugf("SetupOneInterface: %s %#a Registered", intf->intfName, &intf->coreIntf.ip);
        if (gMDNSPlatformPosixVerboseLevel > 0)
            fprintf(stderr, "Registered interface %s\n", intf->intfName);
    }
    else
    {
        // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
        debugf("SetupOneInterface: %s %#a failed to register %d", intfName, &intf->coreIntf.ip, err);
        if (intf) { FreePosixNetworkInterface(intf); intf = NULL; }
    }

    assert((err == 0) == (intf != NULL));

    return err;
}

// Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
mDNSlocal int SetupInterfaceList(mDNS *const m)
{
    mDNSBool foundav4       = mDNSfalse;
    int err            = 0;
    struct ifaddrs *intfList;
    struct ifaddrs *firstLoopback = NULL;
    int firstLoopbackIndex = 0;

    assert(m != NULL);
    debugf("SetupInterfaceList");

    if (getifaddrs(&intfList) < 0)
    {
        err = errno;
    }
    if (intfList == NULL) err = ENOENT;

    if (err == 0)
    {
        struct ifaddrs *i = intfList;
        while (i)
        {
            if (     i->ifa_addr != NULL &&
                     ((i->ifa_addr->sa_family == AF_INET)
#if HAVE_IPV6
                      || (i->ifa_addr->sa_family == AF_INET6)
#endif
                      ) &&  (i->ifa_flags & IFF_UP) && !(i->ifa_flags & IFF_POINTOPOINT))
            {
                int ifIndex = if_nametoindex(i->ifa_name);
                if (ifIndex == 0)
                {
                    i = i->ifa_next;
                    continue;
                }
                if (i->ifa_flags & IFF_LOOPBACK)
                {
                    if (firstLoopback == NULL)
                    {
                        firstLoopback = i;
                        firstLoopbackIndex = ifIndex;
                    }
                }
                else
                {
                    if (SetupOneInterface(m, i->ifa_addr, i->ifa_netmask, i->ifa_name, ifIndex) == 0)
                    {
                        if (i->ifa_addr->sa_family == AF_INET)
                        {
                            foundav4 = mDNStrue;
                        }
                    }
                }
            }
            i = i->ifa_next;
        }

        // If we found no normal interfaces but we did find a loopback interface, register the
        // loopback interface.  This allows self-discovery if no interfaces are configured.
        // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
        // In the interim, we skip loopback interface only if we found at least one v4 interface to use
        // if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
        if (!foundav4 && firstLoopback)
        {
            (void)SetupOneInterface(m, firstLoopback->ifa_addr, firstLoopback->ifa_netmask, firstLoopback->ifa_name,
                                    firstLoopbackIndex);
        }
    }

    // Clean up.
    if (intfList != NULL) freeifaddrs(intfList);

    // Clean up any interfaces that have been hanging around on the RecentInterfaces list for more than a minute
    PosixNetworkInterface **ri = &gRecentInterfaces;
    const mDNSs32 utc = mDNSPlatformUTC();
    while (*ri)
    {
        PosixNetworkInterface *pi = *ri;
        if (utc - pi->LastSeen < 60) ri = (PosixNetworkInterface **)&pi->coreIntf.next;
        else { *ri = (PosixNetworkInterface *)pi->coreIntf.next; free(pi); }
    }

    return err;
}

#if USES_NETLINK

// See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink

// Open a socket that will receive interface change notifications
mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
{
    mStatus err = mStatus_NoError;
    struct sockaddr_nl snl;
    int sock;
    int ret;

    sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
    if (sock < 0)
        return errno;

    // Configure read to be non-blocking because inbound msg size is not known in advance
    (void) fcntl(sock, F_SETFL, O_NONBLOCK);

    /* Subscribe the socket to Link & IP addr notifications. */
    mDNSPlatformMemZero(&snl, sizeof snl);
    snl.nl_family = AF_NETLINK;
    snl.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;
    ret = bind(sock, (struct sockaddr *) &snl, sizeof snl);
    if (0 == ret)
        *pFD = sock;
    else
        err = errno;

    return err;
}

#if MDNS_DEBUGMSGS
mDNSlocal void      PrintNetLinkMsg(const struct nlmsghdr *pNLMsg)
{
    const char *kNLMsgTypes[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
    const char *kNLRtMsgTypes[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };

    printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg->nlmsg_len,
           pNLMsg->nlmsg_type < RTM_BASE ? kNLMsgTypes[pNLMsg->nlmsg_type] : kNLRtMsgTypes[pNLMsg->nlmsg_type - RTM_BASE],
           pNLMsg->nlmsg_flags);

    if (RTM_NEWLINK <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETLINK)
    {
        struct ifinfomsg    *pIfInfo = (struct ifinfomsg*) NLMSG_DATA(pNLMsg);
        printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo->ifi_family,
               pIfInfo->ifi_type, pIfInfo->ifi_index, pIfInfo->ifi_flags, pIfInfo->ifi_change);

    }
    else if (RTM_NEWADDR <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETADDR)
    {
        struct ifaddrmsg    *pIfAddr = (struct ifaddrmsg*) NLMSG_DATA(pNLMsg);
        printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr->ifa_family,
               pIfAddr->ifa_index, pIfAddr->ifa_flags);
    }
    printf("\n");
}
#endif

mDNSlocal mDNSu32       ProcessRoutingNotification(int sd)
// Read through the messages on sd and if any indicate that any interface records should
// be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
{
    ssize_t readCount;
    char buff[4096];
    struct nlmsghdr         *pNLMsg = (struct nlmsghdr*) buff;
    mDNSu32 result = 0;

    // The structure here is more complex than it really ought to be because,
    // unfortunately, there's no good way to size a buffer in advance large
    // enough to hold all pending data and so avoid message fragmentation.
    // (Note that FIONREAD is not supported on AF_NETLINK.)

    readCount = read(sd, buff, sizeof buff);
    while (1)
    {
        // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
        // If not, discard already-processed messages in buffer and read more data.
        if (((char*) &pNLMsg[1] > (buff + readCount)) ||    // i.e. *pNLMsg extends off end of buffer
            ((char*) pNLMsg + pNLMsg->nlmsg_len > (buff + readCount)))
        {
            if (buff < (char*) pNLMsg)      // we have space to shuffle
            {
                // discard processed data
                readCount -= ((char*) pNLMsg - buff);
                memmove(buff, pNLMsg, readCount);
                pNLMsg = (struct nlmsghdr*) buff;

                // read more data
                readCount += read(sd, buff + readCount, sizeof buff - readCount);
                continue;                   // spin around and revalidate with new readCount
            }
            else
                break;  // Otherwise message does not fit in buffer
        }

#if MDNS_DEBUGMSGS
        PrintNetLinkMsg(pNLMsg);
#endif

        // Process the NetLink message
        if (pNLMsg->nlmsg_type == RTM_GETLINK || pNLMsg->nlmsg_type == RTM_NEWLINK)
            result |= 1 << ((struct ifinfomsg*) NLMSG_DATA(pNLMsg))->ifi_index;
        else if (pNLMsg->nlmsg_type == RTM_DELADDR || pNLMsg->nlmsg_type == RTM_NEWADDR)
            result |= 1 << ((struct ifaddrmsg*) NLMSG_DATA(pNLMsg))->ifa_index;

        // Advance pNLMsg to the next message in the buffer
        if ((pNLMsg->nlmsg_flags & NLM_F_MULTI) != 0 && pNLMsg->nlmsg_type != NLMSG_DONE)
        {
            ssize_t len = readCount - ((char*)pNLMsg - buff);
            pNLMsg = NLMSG_NEXT(pNLMsg, len);
        }
        else
            break;  // all done!
    }

    return result;
}

#else // USES_NETLINK

// Open a socket that will receive interface change notifications
mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
{
    *pFD = socket(AF_ROUTE, SOCK_RAW, 0);

    if (*pFD < 0)
        return mStatus_UnknownErr;

    // Configure read to be non-blocking because inbound msg size is not known in advance
    (void) fcntl(*pFD, F_SETFL, O_NONBLOCK);

    return mStatus_NoError;
}

#if MDNS_DEBUGMSGS
mDNSlocal void      PrintRoutingSocketMsg(const struct ifa_msghdr *pRSMsg)
{
    const char *kRSMsgTypes[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
                                  "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
                                  "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };

    int index = pRSMsg->ifam_type == RTM_IFINFO ? ((struct if_msghdr*) pRSMsg)->ifm_index : pRSMsg->ifam_index;

    printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg->ifam_msglen, kRSMsgTypes[pRSMsg->ifam_type], index);
}
#endif

mDNSlocal mDNSu32       ProcessRoutingNotification(int sd)
// Read through the messages on sd and if any indicate that any interface records should
// be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
{
    ssize_t readCount;
    char buff[4096];
    struct ifa_msghdr       *pRSMsg = (struct ifa_msghdr*) buff;
    mDNSu32 result = 0;

    readCount = read(sd, buff, sizeof buff);
    if (readCount < (ssize_t) sizeof(struct ifa_msghdr))
        return mStatus_UnsupportedErr;      // cannot decipher message

#if MDNS_DEBUGMSGS
    PrintRoutingSocketMsg(pRSMsg);
#endif

    // Process the message
    switch (pRSMsg->ifam_type)
    {
    case RTM_NEWADDR:
    case RTM_DELADDR:
    case RTM_IFINFO:
    /*
     * ADD & DELETE are happening when IPv6 announces are changing,
     * and for some reason it will stop mdnsd to announce IPv6
     * addresses. So we force mdnsd to check interfaces.
     */
    case RTM_ADD:
    case RTM_DELETE:
        if (pRSMsg->ifam_type == RTM_IFINFO)
            result |= 1 << ((struct if_msghdr*) pRSMsg)->ifm_index;
        else
            result |= 1 << pRSMsg->ifam_index;
    break;
    }

    return result;
}

#endif // USES_NETLINK

// Called when data appears on interface change notification socket
mDNSlocal void InterfaceChangeCallback(int fd, void *context)
{
    IfChangeRec     *pChgRec = (IfChangeRec*) context;
    fd_set readFDs;
    mDNSu32 changedInterfaces = 0;
    struct timeval zeroTimeout = { 0, 0 };

    (void)fd; // Unused

    FD_ZERO(&readFDs);
    FD_SET(pChgRec->NotifySD, &readFDs);

    do
    {
        changedInterfaces |= ProcessRoutingNotification(pChgRec->NotifySD);
    }
    while (0 < select(pChgRec->NotifySD + 1, &readFDs, (fd_set*) NULL, (fd_set*) NULL, &zeroTimeout));

    // Currently we rebuild the entire interface list whenever any interface change is
    // detected. If this ever proves to be a performance issue in a multi-homed
    // configuration, more care should be paid to changedInterfaces.
    if (changedInterfaces)
        mDNSPlatformPosixRefreshInterfaceList(pChgRec->mDNS);
}

// Register with either a Routing Socket or RtNetLink to listen for interface changes.
mDNSlocal mStatus WatchForInterfaceChange(mDNS *const m)
{
    mStatus err;
    IfChangeRec *pChgRec;

    pChgRec = (IfChangeRec*) mDNSPlatformMemAllocateClear(sizeof *pChgRec);
    if (pChgRec == NULL)
        return mStatus_NoMemoryErr;

    pChgRec->mDNS = m;
    err = OpenIfNotifySocket(&pChgRec->NotifySD);
    if (err == 0)
        err = mDNSPosixAddFDToEventLoop(pChgRec->NotifySD, InterfaceChangeCallback, pChgRec);
    if (err)
        mDNSPlatformMemFree(pChgRec);

    return err;
}

// Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
// If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
// we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
mDNSlocal mDNSBool mDNSPlatformInit_CanReceiveUnicast(void)
{
    int err;
    int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    struct sockaddr_in s5353;
    s5353.sin_family      = AF_INET;
    s5353.sin_port        = MulticastDNSPort.NotAnInteger;
    s5353.sin_addr.s_addr = 0;
    err = bind(s, (struct sockaddr *)&s5353, sizeof(s5353));
    close(s);
    if (err) debugf("No unicast UDP responses");
    else debugf("Unicast UDP responses okay");
    return(err == 0);
}

// mDNS core calls this routine to initialise the platform-specific data.
mDNSexport mStatus mDNSPlatformInit(mDNS *const m)
{
    int err = 0;
    struct sockaddr sa;
    assert(m != NULL);

    if (mDNSPlatformInit_CanReceiveUnicast()) m->CanReceiveUnicastOn5353 = mDNStrue;

    // Tell mDNS core the names of this machine.

    // Set up the nice label
    m->nicelabel.c[0] = 0;
    GetUserSpecifiedFriendlyComputerName(&m->nicelabel);
    if (m->nicelabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->nicelabel, "Computer");

    // Set up the RFC 1034-compliant label
    m->hostlabel.c[0] = 0;
    GetUserSpecifiedRFC1034ComputerName(&m->hostlabel);
    if (m->hostlabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->hostlabel, "Computer");

    mDNS_SetFQDN(m);

    sa.sa_family = AF_INET;
    m->p->unicastSocket4 = -1;
    if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket4);
#if HAVE_IPV6
    sa.sa_family = AF_INET6;
    m->p->unicastSocket6 = -1;
    if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket6);
#endif

    // Tell mDNS core about the network interfaces on this machine.
    if (err == mStatus_NoError) err = SetupInterfaceList(m);

    // Tell mDNS core about DNS Servers
    mDNS_Lock(m);
    if (err == mStatus_NoError) ParseDNSServers(m, uDNS_SERVERS_FILE);
    mDNS_Unlock(m);

    if (err == mStatus_NoError)
    {
        err = WatchForInterfaceChange(m);
        // Failure to observe interface changes is non-fatal.
        if (err != mStatus_NoError)
        {
            fprintf(stderr, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n",
		(int)getpid(), err);
            err = mStatus_NoError;
        }
    }

    // We don't do asynchronous initialization on the Posix platform, so by the time
    // we get here the setup will already have succeeded or failed.  If it succeeded,
    // we should just call mDNSCoreInitComplete() immediately.
    if (err == mStatus_NoError)
        mDNSCoreInitComplete(m, mStatus_NoError);

    return PosixErrorToStatus(err);
}

// mDNS core calls this routine to clean up the platform-specific data.
// In our case all we need to do is to tear down every network interface.
mDNSexport void mDNSPlatformClose(mDNS *const m)
{
    int rv;
    assert(m != NULL);
    ClearInterfaceList(m);
    if (m->p->unicastSocket4 != -1)
    {
        rv = close(m->p->unicastSocket4);
        assert(rv == 0);
    }
#if HAVE_IPV6
    if (m->p->unicastSocket6 != -1)
    {
        rv = close(m->p->unicastSocket6);
        assert(rv == 0);
    }
#endif
}

// This is used internally by InterfaceChangeCallback.
// It's also exported so that the Standalone Responder (mDNSResponderPosix)
// can call it in response to a SIGHUP (mainly for debugging purposes).
mDNSexport mStatus mDNSPlatformPosixRefreshInterfaceList(mDNS *const m)
{
    int err;
    // This is a pretty heavyweight way to process interface changes --
    // destroying the entire interface list and then making fresh one from scratch.
    // We should make it like the OS X version, which leaves unchanged interfaces alone.
    ClearInterfaceList(m);
    err = SetupInterfaceList(m);
    return PosixErrorToStatus(err);
}

#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark ***** Locking
#endif

// On the Posix platform, locking is a no-op because we only ever enter
// mDNS core on the main thread.

// mDNS core calls this routine when it wants to prevent
// the platform from reentering mDNS core code.
mDNSexport void    mDNSPlatformLock   (const mDNS *const m)
{
    (void) m;   // Unused
}

// mDNS core calls this routine when it release the lock taken by
// mDNSPlatformLock and allow the platform to reenter mDNS core code.
mDNSexport void    mDNSPlatformUnlock (const mDNS *const m)
{
    (void) m;   // Unused
}

#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark ***** Strings
#endif

mDNSexport mDNSu32  mDNSPlatformStrLCopy(void *dst, const void *src, mDNSu32 len)
{
#if HAVE_STRLCPY
    return ((mDNSu32)strlcpy((char *)dst, (const char *)src, len));
#else
    size_t srcLen;

    srcLen = strlen((const char *)src);
    if (srcLen < len)
    {
        memcpy(dst, src, srcLen + 1);
    }
    else if (len > 0)
    {
        memcpy(dst, src, len - 1);
        ((char *)dst)[len - 1] = '\0';
    }

    return ((mDNSu32)srcLen);
#endif
}

// mDNS core calls this routine to get the length of a C string.
// On the Posix platform this maps directly to the ANSI C strlen.
mDNSexport mDNSu32  mDNSPlatformStrLen (const void *src)
{
    return strlen((const char*)src);
}

// mDNS core calls this routine to copy memory.
// On the Posix platform this maps directly to the ANSI C memcpy.
mDNSexport void    mDNSPlatformMemCopy(void *dst, const void *src, mDNSu32 len)
{
    memcpy(dst, src, len);
}

// mDNS core calls this routine to test whether blocks of memory are byte-for-byte
// identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
mDNSexport mDNSBool mDNSPlatformMemSame(const void *dst, const void *src, mDNSu32 len)
{
    return memcmp(dst, src, len) == 0;
}

// If the caller wants to know the exact return of memcmp, then use this instead
// of mDNSPlatformMemSame
mDNSexport int mDNSPlatformMemCmp(const void *dst, const void *src, mDNSu32 len)
{
    return (memcmp(dst, src, len));
}

mDNSexport void mDNSPlatformQsort(void *base, int nel, int width, int (*compar)(const void *, const void *))
{
    (void)qsort(base, nel, width, compar);
}

// Proxy stub functions
mDNSexport mDNSu8 *DNSProxySetAttributes(DNSQuestion *q, DNSMessageHeader *h, DNSMessage *msg, mDNSu8 *ptr, mDNSu8 *limit)
{
    (void) q;
    (void) h;
    (void) msg;
    (void) ptr;
    (void) limit;

    return ptr;
}

mDNSexport void DNSProxyInit(mDNSu32 IpIfArr[MaxIp], mDNSu32 OpIf)
{
    (void) IpIfArr;
    (void) OpIf;
}

mDNSexport void DNSProxyTerminate(void)
{
}

// mDNS core calls this routine to clear blocks of memory.
// On the Posix platform this is a simple wrapper around ANSI C memset.
mDNSexport void  mDNSPlatformMemZero(void *dst, mDNSu32 len)
{
    memset(dst, 0, len);
}

#if !MDNS_MALLOC_DEBUGGING
mDNSexport void *mDNSPlatformMemAllocate(mDNSu32 len)      { return(mallocL("mDNSPlatformMemAllocate", len)); }
mDNSexport void *mDNSPlatformMemAllocateClear(mDNSu32 len) { return(callocL(name, len)); }
mDNSexport void  mDNSPlatformMemFree    (void *mem)        {          freeL("mDNSPlatformMemFree", mem); }
#endif

#if _PLATFORM_HAS_STRONG_PRNG_
mDNSexport mDNSu32 mDNSPlatformRandomNumber(void)
{
    return(arc4random());
}
#else
mDNSexport mDNSu32 mDNSPlatformRandomSeed(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return(tv.tv_usec);
}
#endif

mDNSexport mDNSs32 mDNSPlatformOneSecond = 1024;

mDNSexport mStatus mDNSPlatformTimeInit(void)
{
    // No special setup is required on Posix -- we just use gettimeofday();
    // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
    // We should find a better way to do this
    return(mStatus_NoError);
}

mDNSexport mDNSs32  mDNSPlatformRawTime()
{
    struct timespec tm;
    int ret = clock_gettime(CLOCK_MONOTONIC, &tm);
    assert(ret == 0); // This call will only fail if the number of seconds does not fit in an object of type time_t.

    // tm.tv_sec is seconds since some unspecified starting point (it is usually the system start up time)
    // tm.tv_nsec is nanoseconds since the start of this second (i.e. values 0 to 999999999)
    // We use the lower 22 bits of tm.tv_sec for the top 22 bits of our result
    // and we multiply tm.tv_nsec by 2 / 1953125 to get a value in the range 0-1023 to go in the bottom 10 bits.
    // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
    // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).

    return ((tm.tv_sec << 10) | (tm.tv_nsec * 2 / 1953125));
}

mDNSexport mDNSs32 mDNSPlatformUTC(void)
{
    return time(NULL);
}

mDNSexport void mDNSPlatformSendWakeupPacket(mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration)
{
    (void) InterfaceID;
    (void) EthAddr;
    (void) IPAddr;
    (void) iteration;
}

mDNSexport mDNSBool mDNSPlatformValidRecordForInterface(const AuthRecord *rr, mDNSInterfaceID InterfaceID)
{
    (void) rr;
    (void) InterfaceID;

    return 1;
}

mDNSexport mDNSBool mDNSPlatformValidQuestionForInterface(DNSQuestion *q, const NetworkInterfaceInfo *intf)
{
    (void) q;
    (void) intf;

    return 1;
}

// Used for debugging purposes. For now, just set the buffer to zero
mDNSexport void mDNSPlatformFormatTime(unsigned long te, mDNSu8 *buf, int bufsize)
{
    (void) te;
    if (bufsize) buf[0] = 0;
}

mDNSexport void mDNSPlatformSendKeepalive(mDNSAddr *sadd, mDNSAddr *dadd, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu32 seq, mDNSu32 ack, mDNSu16 win)
{
    (void) sadd;    // Unused
    (void) dadd;    // Unused
    (void) lport;   // Unused
    (void) rport;   // Unused
    (void) seq;     // Unused
    (void) ack;     // Unused
    (void) win;     // Unused
}

mDNSexport mStatus mDNSPlatformRetrieveTCPInfo(mDNSAddr *laddr, mDNSIPPort *lport, mDNSAddr *raddr, mDNSIPPort *rport, mDNSTCPInfo *mti)
{
    (void) laddr;   // Unused
    (void) raddr;   // Unused
    (void) lport;   // Unused
    (void) rport;   // Unused
    (void) mti;     // Unused

    return mStatus_NoError;
}

mDNSexport mStatus mDNSPlatformGetRemoteMacAddr(mDNSAddr *raddr)
{
    (void) raddr; // Unused

    return mStatus_NoError;
}

mDNSexport mStatus    mDNSPlatformStoreSPSMACAddr(mDNSAddr *spsaddr, char *ifname)
{
    (void) spsaddr; // Unused
    (void) ifname;  // Unused

    return mStatus_NoError;
}

mDNSexport mStatus    mDNSPlatformClearSPSData(void)
{
    return mStatus_NoError;
}

mDNSexport mStatus mDNSPlatformStoreOwnerOptRecord(char *ifname, DNSMessage *msg, int length)
{
    (void) ifname; // Unused
    (void) msg;    // Unused
    (void) length; // Unused
    return mStatus_UnsupportedErr;
}

mDNSexport mDNSu16 mDNSPlatformGetUDPPort(UDPSocket *sock)
{
    (void) sock; // unused

    return (mDNSu16)-1;
}

mDNSexport mDNSBool mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID)
{
    (void) InterfaceID; // unused

    return mDNSfalse;
}

mDNSexport void mDNSPlatformSetSocktOpt(void *sock, mDNSTransport_Type transType, mDNSAddr_Type addrType, const DNSQuestion *q)
{
    (void) sock;
    (void) transType;
    (void) addrType;
    (void) q;
}

mDNSexport mDNSs32 mDNSPlatformGetPID()
{
    return 0;
}

mDNSlocal void mDNSPosixAddToFDSet(int *nfds, fd_set *readfds, int s)
{
    if (*nfds < s + 1) *nfds = s + 1;
    FD_SET(s, readfds);
}

mDNSexport void mDNSPosixGetFDSetForSelect(mDNS *m, int *nfds, fd_set *readfds, fd_set *writefds)
{
    int numFDs = *nfds;
    PosixEventSource *iSource;

    // 2. Build our list of active file descriptors
    PosixNetworkInterface *info = (PosixNetworkInterface *)(m->HostInterfaces);
    if (m->p->unicastSocket4 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, m->p->unicastSocket4);
#if HAVE_IPV6
    if (m->p->unicastSocket6 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, m->p->unicastSocket6);
#endif
    while (info)
    {
        if (info->multicastSocket4 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, info->multicastSocket4);
#if HAVE_IPV6
        if (info->multicastSocket6 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, info->multicastSocket6);
#endif
        info = (PosixNetworkInterface *)(info->coreIntf.next);
    }

    // Copy over the event fds.   We have to do it this way because client-provided event loops expect
    // to initialize their FD sets first and then call mDNSPosixGetFDSet()
    for (iSource = gEventSources; iSource; iSource = iSource->next)
    {
        if (iSource->readCallback != NULL)
            FD_SET(iSource->fd, readfds);
        if (iSource->writeCallback != NULL)
            FD_SET(iSource->fd, writefds);
        if (numFDs <= iSource->fd)
            numFDs = iSource->fd + 1;
    }
    *nfds = numFDs;
}

mDNSexport void mDNSPosixGetNextDNSEventTime(mDNS *m, struct timeval *timeout)
{
    mDNSs32 ticks;
    struct timeval interval;

    // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
    mDNSs32 nextevent = mDNS_Execute(m);

    // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
    ticks = nextevent - mDNS_TimeNow(m);
    if (ticks < 1) ticks = 1;
    interval.tv_sec  = ticks >> 10;                     // The high 22 bits are seconds
    interval.tv_usec = ((ticks & 0x3FF) * 15625) / 16;  // The low 10 bits are 1024ths

    // 4. If client's proposed timeout is more than what we want, then reduce it
    if (timeout->tv_sec > interval.tv_sec ||
        (timeout->tv_sec == interval.tv_sec && timeout->tv_usec > interval.tv_usec))
        *timeout = interval;
}

mDNSexport void mDNSPosixGetFDSet(mDNS *m, int *nfds, fd_set *readfds, fd_set *writefds, struct timeval *timeout)
{
    mDNSPosixGetNextDNSEventTime(m, timeout);
    mDNSPosixGetFDSetForSelect(m, nfds, readfds, writefds);
}

mDNSexport void mDNSPosixProcessFDSet(mDNS *const m, fd_set *readfds, fd_set *writefds)
{
    PosixNetworkInterface *info;
    PosixEventSource    *iSource;
    assert(m       != NULL);
    assert(readfds != NULL);
    info = (PosixNetworkInterface *)(m->HostInterfaces);

    if (m->p->unicastSocket4 != -1 && FD_ISSET(m->p->unicastSocket4, readfds))
    {
        FD_CLR(m->p->unicastSocket4, readfds);
        SocketDataReady(m, NULL, m->p->unicastSocket4);
    }
#if HAVE_IPV6
    if (m->p->unicastSocket6 != -1 && FD_ISSET(m->p->unicastSocket6, readfds))
    {
        FD_CLR(m->p->unicastSocket6, readfds);
        SocketDataReady(m, NULL, m->p->unicastSocket6);
    }
#endif

    while (info)
    {
        if (info->multicastSocket4 != -1 && FD_ISSET(info->multicastSocket4, readfds))
        {
            FD_CLR(info->multicastSocket4, readfds);
            SocketDataReady(m, info, info->multicastSocket4);
        }
#if HAVE_IPV6
        if (info->multicastSocket6 != -1 && FD_ISSET(info->multicastSocket6, readfds))
        {
            FD_CLR(info->multicastSocket6, readfds);
            SocketDataReady(m, info, info->multicastSocket6);
        }
#endif
        info = (PosixNetworkInterface *)(info->coreIntf.next);
    }

    // Now process routing socket events, discovery relay events and anything else of that ilk.
    for (iSource = gEventSources; iSource; iSource = iSource->next)
    {
        if (iSource->readCallback != NULL && FD_ISSET(iSource->fd, readfds))
        {
            iSource->readCallback(iSource->fd, iSource->readContext);
            break;  // in case callback removed elements from gEventSources
        }
        else if (iSource->writeCallback != NULL && FD_ISSET(iSource->fd, writefds))
        {
            mDNSPosixEventCallback writeCallback = iSource->writeCallback;
            // Write events are one-shot: to get another event, the consumer has to put in a new request.
            // We reset this before calling the callback just in case the callback requests another write
            // callback, or deletes the event context from the list.
            iSource->writeCallback = NULL;
            writeCallback(iSource->fd, iSource->writeContext);
            break;  // in case callback removed elements from gEventSources
        }
    }
}

mDNSu32 mDNSPlatformEventContextSize = sizeof (PosixEventSource);

mDNSlocal void requestIOEvents(PosixEventSource *newSource, const char *taskName,
                                  mDNSPosixEventCallback callback, void *context, int flag)
{
    PosixEventSource **epp = &gEventSources;

    if (newSource->fd >= (int) FD_SETSIZE || newSource->fd < 0)
    {
        LogMsg("requestIOEvents called with fd %d > FD_SETSIZE %d.", newSource->fd, FD_SETSIZE);
        assert(0);
    }
    if (callback == NULL)
    {
        LogMsg("requestIOEvents called no callback.", newSource->fd, FD_SETSIZE);
        assert(0);
    }

    // See if this event context is already on the list; if it is, no need to scan the list.
    if (!(newSource->flags & PosixEventFlag_OnList))
    {
        while (*epp)
        {
            // This should never happen.
            if (newSource == *epp)
            {
                LogMsg("Event context marked not on list but is on list.");
                assert(0);
            }
            epp = &(*epp)->next;
        }
        if (*epp == NULL)
        {
            *epp = newSource;
            newSource->next = NULL;
            newSource->flags = PosixEventFlag_OnList;
        }
    }

    if (flag & PosixEventFlag_Read)
    {
        newSource->readCallback = callback;
        newSource->readContext = context;
        newSource->flags |= PosixEventFlag_Read;
        newSource->readTaskName = taskName;
    }
    if (flag & PosixEventFlag_Write)
    {
        newSource->writeCallback = callback;
        newSource->writeContext = context;
        newSource->flags |= PosixEventFlag_Write;
        newSource->writeTaskName = taskName;
    }
}

mDNSlocal void requestReadEvents(PosixEventSource *eventSource,
                                    const char *taskName, mDNSPosixEventCallback callback, void *context)
{
    requestIOEvents(eventSource, taskName, callback, context, PosixEventFlag_Read);
}

mDNSlocal void requestWriteEvents(PosixEventSource *eventSource,
                                     const char *taskName, mDNSPosixEventCallback callback, void *context)
{
    requestIOEvents(eventSource, taskName, callback, context, PosixEventFlag_Write);
}

// Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
mDNSlocal mStatus stopReadOrWriteEvents(int fd, mDNSBool freeContext, mDNSBool removeContext, int flags)
{
    PosixEventSource *iSource, **epp = &gEventSources;

    while (*epp)
    {
        iSource = *epp;
        if (fd == iSource->fd)
        {
            if (flags & PosixEventFlag_Read)
            {
                iSource->readCallback = NULL;
                iSource->readContext = NULL;
            }
            if (flags & PosixEventFlag_Write)
            {
                iSource->writeCallback = NULL;
                iSource->writeContext = NULL;
            }
            if (iSource->writeCallback == NULL && iSource->readCallback == NULL)
            {
                if (removeContext || freeContext)
                    *epp = iSource->next;
                if (freeContext)
                    free(iSource);
            }
            return mStatus_NoError;
        }
        epp = &(*epp)->next;
    }
    return mStatus_NoSuchNameErr;
}

// Some of the mDNSPosix client code relies on being able to add FDs to the event loop without
// providing storage for the event-related info.   mDNSPosixAddFDToEventLoop and
// mDNSPosixRemoveFDFromEventLoop handle the event structure storage automatically.
mStatus mDNSPosixAddFDToEventLoop(int fd, mDNSPosixEventCallback callback, void *context)
{
    PosixEventSource *newSource;

    newSource = (PosixEventSource*) malloc(sizeof *newSource);
    if (NULL == newSource)
        return mStatus_NoMemoryErr;
    memset(newSource, 0, sizeof *newSource);
    newSource->fd = fd;

    requestReadEvents(newSource, "mDNSPosixAddFDToEventLoop", callback, context);
    return mStatus_NoError;
}

mStatus mDNSPosixRemoveFDFromEventLoop(int fd)
{
    return stopReadOrWriteEvents(fd, mDNStrue, mDNStrue, PosixEventFlag_Read | PosixEventFlag_Write);
}

// Simply note the received signal in gEventSignals.
mDNSlocal void  NoteSignal(int signum)
{
    sigaddset(&gEventSignals, signum);
}

// Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
mStatus mDNSPosixListenForSignalInEventLoop(int signum)
{
    struct sigaction action;
    mStatus err;

    mDNSPlatformMemZero(&action, sizeof action);        // more portable than member-wise assignment
    action.sa_handler = NoteSignal;
    err = sigaction(signum, &action, (struct sigaction*) NULL);

    sigaddset(&gEventSignalSet, signum);

    return err;
}

// Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
mStatus mDNSPosixIgnoreSignalInEventLoop(int signum)
{
    struct sigaction action;
    mStatus err;

    mDNSPlatformMemZero(&action, sizeof action);        // more portable than member-wise assignment
    action.sa_handler = SIG_DFL;
    err = sigaction(signum, &action, (struct sigaction*) NULL);

    sigdelset(&gEventSignalSet, signum);

    return err;
}

// Do a single pass through the attendent event sources and dispatch any found to their callbacks.
// Return as soon as internal timeout expires, or a signal we're listening for is received.
mStatus mDNSPosixRunEventLoopOnce(mDNS *m, const struct timeval *pTimeout,
                                  sigset_t *pSignalsReceived, mDNSBool *pDataDispatched)
{
    fd_set listenFDs;
    fd_set writeFDs;
    int numFDs = 0, numReady;
    struct timeval timeout = *pTimeout;

    // 1. Set up the fd_set as usual here.
    // This example client has no file descriptors of its own,
    // but a real application would call FD_SET to add them to the set here
    FD_ZERO(&listenFDs);
    FD_ZERO(&writeFDs);

    // 2. Set up the timeout.
    mDNSPosixGetNextDNSEventTime(m, &timeout);

    // Include the sockets that are listening to the wire in our select() set
    mDNSPosixGetFDSetForSelect(m, &numFDs, &listenFDs, &writeFDs);
    numReady = select(numFDs, &listenFDs, &writeFDs, (fd_set*) NULL, &timeout);

    if (numReady > 0)
    {
        mDNSPosixProcessFDSet(m, &listenFDs, &writeFDs);
        *pDataDispatched = mDNStrue;
    }
    else if (numReady < 0)
    {
	if (errno != EINTR) {
            // This should never happen, represents a coding error, and is not recoverable, since
            // we'll just sit here spinning and never receive another event.   The usual reason for
            // it to happen is that an FD was closed but not removed from the event list.
            LogMsg("select failed: %s", strerror(errno));
            abort();
        }
    }
    else
        *pDataDispatched = mDNSfalse;

    (void) sigprocmask(SIG_BLOCK, &gEventSignalSet, (sigset_t*) NULL);
    *pSignalsReceived = gEventSignals;
    sigemptyset(&gEventSignals);
    (void) sigprocmask(SIG_UNBLOCK, &gEventSignalSet, (sigset_t*) NULL);

    return mStatus_NoError;
}
/* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*-
 *
 * Copyright (c) 2002-2004 Apple Computer, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef __mDNSPlatformPosix_h
#define __mDNSPlatformPosix_h

#include <signal.h>
#include <sys/time.h>

#ifdef  __cplusplus
extern "C" {
#endif

// PosixNetworkInterface is a record extension of the core NetworkInterfaceInfo
// type that supports extra fields needed by the Posix platform.
//
// IMPORTANT: coreIntf must be the first field in the structure because
// we cast between pointers to the two different types regularly.

typedef struct PosixNetworkInterface PosixNetworkInterface;

struct PosixNetworkInterface
{
    NetworkInterfaceInfo coreIntf;      // MUST be the first element in this structure
    mDNSs32 LastSeen;
    const char *            intfName;
    PosixNetworkInterface * aliasIntf;
    int index;
    int multicastSocket4;
#if HAVE_IPV6
    int multicastSocket6;
#endif
};

// This is a global because debugf_() needs to be able to check its value
extern int gMDNSPlatformPosixVerboseLevel;

struct mDNS_PlatformSupport_struct
{
    int unicastSocket4;
#if HAVE_IPV6
    int unicastSocket6;
#endif
};

// We keep a list of client-supplied event sources in PosixEventSource records
// Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
#define PosixEventFlag_OnList   1
#define PosixEventFlag_Read     2
#define PosixEventFlag_Write    4
    
typedef void (*mDNSPosixEventCallback)(int fd, void *context);
struct PosixEventSource
{
    struct PosixEventSource *next;
    mDNSPosixEventCallback readCallback;
    mDNSPosixEventCallback writeCallback;
    const char *readTaskName;
    const char *writeTaskName;
    void *readContext;
    void *writeContext;
    int fd;
    unsigned flags;
};
typedef struct PosixEventSource PosixEventSource;
    
struct TCPSocket_struct
{
    mDNSIPPort port;            // MUST BE FIRST FIELD -- mDNSCore expects every TCPSocket_struct to begin with mDNSIPPort
    TCPSocketFlags flags;       // MUST BE SECOND FIELD -- mDNSCore expects every TCPSocket_struct have TCPSocketFlags flags after mDNSIPPort
    TCPConnectionCallback callback;
    PosixEventSource events;
    // SSL context goes here.
    domainname *hostname;
    mDNSAddr remoteAddress;
    mDNSIPPort remotePort;
    void *context;
    mDNSBool setup;
    mDNSBool connected;
    mStatus err;
};

struct TCPListener_struct
{
    TCPAcceptedCallback callback;
    PosixEventSource events;
    void *context;
    mDNSAddr_Type addressType;
    TCPSocketFlags socketFlags;
};
    
#define uDNS_SERVERS_FILE "/etc/resolv.conf"
extern int ParseDNSServers(mDNS *m, const char *filePath);
extern mStatus mDNSPlatformPosixRefreshInterfaceList(mDNS *const m);
// See comment in implementation.

// Get the next upcoming mDNS (or DNS) event time as a posix timeval that can be passed to select.
// This will only update timeout if the next mDNS event is sooner than the value that was passed.
// Therefore, use { FutureTime, 0 } as an initializer if no other timer events are being managed.
extern void mDNSPosixGetNextDNSEventTime(mDNS *m, struct timeval *timeout);

// Returns all the FDs that the posix I/O event system expects to be passed to select.
extern void mDNSPosixGetFDSetForSelect(mDNS *m, int *nfds, fd_set *readfds, fd_set *writefds);

// Call mDNSPosixGetFDSet before calling select(), to update the parameters
// as may be necessary to meet the needs of the mDNSCore code.
// The timeout pointer MUST NOT be NULL.
// Set timeout->tv_sec to FutureTime if you want to have effectively no timeout
// After calling mDNSPosixGetFDSet(), call select(nfds, &readfds, NULL, NULL, &timeout); as usual
// After select() returns, call mDNSPosixProcessFDSet() to let mDNSCore do its work
// mDNSPosixGetFDSet simply calls mDNSPosixGetNextDNSEventTime and then mDNSPosixGetFDSetForSelect.
extern void mDNSPosixGetFDSet(mDNS *m, int *nfds, fd_set *readfds, fd_set *writefds, struct timeval *timeout);


extern void mDNSPosixProcessFDSet(mDNS *const m, fd_set *readfds, fd_set *writefds);

extern mStatus mDNSPosixAddFDToEventLoop( int fd, mDNSPosixEventCallback callback, void *context);
extern mStatus mDNSPosixRemoveFDFromEventLoop( int fd);
extern mStatus mDNSPosixListenForSignalInEventLoop( int signum);
extern mStatus mDNSPosixIgnoreSignalInEventLoop( int signum);
extern mStatus mDNSPosixRunEventLoopOnce( mDNS *m, const struct timeval *pTimeout, sigset_t *pSignalsReceived, mDNSBool *pDataDispatched);

extern mStatus mDNSPosixListenForSignalInEventLoop( int signum);
extern mStatus mDNSPosixIgnoreSignalInEventLoop( int signum);
extern mStatus mDNSPosixRunEventLoopOnce( mDNS *m, const struct timeval *pTimeout, sigset_t *pSignalsReceived, mDNSBool *pDataDispatched);

#ifdef  __cplusplus
}
#endif

#endif
/* -*- Mode: C; tab-width: 4 -*-
 *
 * Copyright (c) 2002-2018 Apple Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mDNSUNP.h"

#include <errno.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <sys/uio.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>

/* Some weird platforms derived from 4.4BSD Lite (e.g. EFI) need the ALIGN(P)
   macro, usually defined in <sys/param.h> or someplace like that, to make sure the
   CMSG_NXTHDR macro is well-formed. On such platforms, the symbol NEED_ALIGN_MACRO
   should be set to the name of the header to include to get the ALIGN(P) macro.
 */
#ifdef NEED_ALIGN_MACRO
#include NEED_ALIGN_MACRO
#endif

/* Solaris defined SIOCGIFCONF etc in <sys/sockio.h> but
   other platforms don't even have that include file.  So,
   if we haven't yet got a definition, let's try to find
   <sys/sockio.h>.
 */

#ifndef SIOCGIFCONF
    #include <sys/sockio.h>
#endif

/* sockaddr_dl is only referenced if we're using IP_RECVIF,
   so only include the header in that case.
 */

#ifdef  IP_RECVIF
    #include <net/if_dl.h>
#endif

#if defined(AF_INET6) && HAVE_IPV6 && !HAVE_LINUX
#if !HAVE_SOLARIS
#include <net/if_var.h>
#else
#include <alloca.h>
#endif /* !HAVE_SOLARIS */
#include <netinet/in_var.h>
// Note: netinet/in_var.h implicitly includes netinet6/in6_var.h for us
#endif

#if defined(AF_INET6) && HAVE_IPV6 && HAVE_LINUX
#include <netdb.h>
#include <arpa/inet.h>

/* Converts a prefix length to IPv6 network mask */
void plen_to_mask(int plen, char *addr) {
    int i;
    int colons=7; /* Number of colons in IPv6 address */
    int bits_in_block=16; /* Bits per IPv6 block */
    for(i=0; i<=colons; i++) {
        int block, ones=0xffff, ones_in_block;
        if (plen>bits_in_block) ones_in_block=bits_in_block;
        else ones_in_block=plen;
        block = ones & (ones << (bits_in_block-ones_in_block));
        i==0 ? sprintf(addr, "%x", block) : sprintf(addr, "%s:%x", addr, block);
        plen -= ones_in_block;
    }
}

/* Gets IPv6 interface information from the /proc filesystem in linux*/
struct ifi_info *get_ifi_info_linuxv6(int doaliases)
{
    struct ifi_info *ifi, *ifihead, **ifipnext, *ifipold, **ifiptr;
    FILE *fp = NULL;
    int i, nitems, flags, index, plen, scope;
    struct addrinfo hints, *res0;
    int err;
    int sockfd = -1;
    struct ifreq ifr;
    char ifnameFmt[16], addrStr[32 + 7 + 1], ifname[IFNAMSIZ], lastname[IFNAMSIZ];

    res0=NULL;
    ifihead = NULL;
    ifipnext = &ifihead;

    if ((fp = fopen(PROC_IFINET6_PATH, "r")) != NULL) {
        sockfd = socket(AF_INET6, SOCK_DGRAM, 0);
        if (sockfd < 0) {
            goto gotError;
        }

        // Parse /proc/net/if_inet6 according to <https://www.tldp.org/HOWTO/Linux+IPv6-HOWTO/ch11s04.html>.

        // Create a string specifier with a width of IFNAMSIZ - 1 ("%<IFNAMSIZ - 1>s") to scan the interface name. The
        // reason why we don't just use the string-ified macro expansion of IFNAMSIZ for the width is because the width
        // needs to be a decimal string and there's no guarantee that IFNAMSIZ will be defined as a decimal integer. For
        // example, it could be defined in hexadecimal or as an arithmetic expression.

        snprintf(ifnameFmt, sizeof(ifnameFmt), "%%%ds", IFNAMSIZ - 1);

        // Write the seven IPv6 address string colons and NUL terminator, i.e., "xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx".
        // The remaining 32 IPv6 address characters come from /proc/net/if_inet6.

        for (i = 4; i < 39; i += 5) addrStr[i] = ':';
        addrStr[39] = '\0';

        lastname[0] = '\0';
        for (;;) {
            nitems = fscanf(fp, " %4c%4c%4c%4c%4c%4c%4c%4c %x %x %x %x",
                &addrStr[0],  &addrStr[5],  &addrStr[10], &addrStr[15],
                &addrStr[20], &addrStr[25], &addrStr[30], &addrStr[35],
                &index, &plen, &scope, &flags);
            if (nitems != 12) break;

            nitems = fscanf(fp, ifnameFmt, ifname);
            if (nitems != 1) break;

            if (strcmp(lastname, ifname) == 0) {
                if (doaliases == 0)
                    continue;   /* already processed this interface */
            }
            memcpy(lastname, ifname, IFNAMSIZ);
            ifi = (struct ifi_info*)calloc(1, sizeof(struct ifi_info));
            if (ifi == NULL) {
                goto gotError;
            }

            ifipold   = *ifipnext;       /* need this later */
            ifiptr    = ifipnext;
            *ifipnext = ifi;            /* prev points to this new one */
            ifipnext = &ifi->ifi_next;  /* pointer to next one goes here */

            /* Add address of the interface */
            memset(&hints, 0, sizeof(hints));
            hints.ai_family = AF_INET6;
            hints.ai_flags = AI_NUMERICHOST;
            err = getaddrinfo(addrStr, NULL, &hints, &res0);
            if (err) {
                goto gotError;
            }
            ifi->ifi_addr = calloc(1, sizeof(struct sockaddr_in6));
            if (ifi->ifi_addr == NULL) {
                goto gotError;
            }
            memcpy(ifi->ifi_addr, res0->ai_addr, sizeof(struct sockaddr_in6));

            /* Add netmask of the interface */
            char ipv6addr[INET6_ADDRSTRLEN];
            plen_to_mask(plen, ipv6addr);
            ifi->ifi_netmask = calloc(1, sizeof(struct sockaddr_in6));
            if (ifi->ifi_netmask == NULL) {
                goto gotError;
            }

            ((struct sockaddr_in6 *)ifi->ifi_netmask)->sin6_family=AF_INET6;
            ((struct sockaddr_in6 *)ifi->ifi_netmask)->sin6_scope_id=scope;
            inet_pton(AF_INET6, ipv6addr, &((struct sockaddr_in6 *)ifi->ifi_netmask)->sin6_addr);

            /* Add interface name */
            memcpy(ifi->ifi_name, ifname, IFI_NAME);

            /* Add interface index */
            ifi->ifi_index = index;

            /* Add interface flags*/
            memcpy(ifr.ifr_name, ifname, IFNAMSIZ);
            if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
                if (errno == EADDRNOTAVAIL) {
                    /*
                     * If the main interface is configured with no IP address but
                     * an alias interface exists with an IP address, you get
                     * EADDRNOTAVAIL for the main interface
                     */
                    free(ifi->ifi_addr);
                    free(ifi->ifi_netmask);
                    free(ifi);
                    ifipnext  = ifiptr;
                    *ifipnext = ifipold;
                    continue;
                } else {
                    goto gotError;
                }
            }
            ifi->ifi_flags = ifr.ifr_flags;
            freeaddrinfo(res0);
            res0=NULL;
        }
    }
    goto done;

gotError:
    if (ifihead != NULL) {
        free_ifi_info(ifihead);
        ifihead = NULL;
    }
    if (res0 != NULL) {
        freeaddrinfo(res0);
        res0=NULL;
    }
done:
    if (sockfd != -1) {
        int rv;
        rv = close(sockfd);
        assert(rv == 0);
    }
    if (fp != NULL) {
        fclose(fp);
    }
    return(ifihead);    /* pointer to first structure in linked list */
}
#endif // defined(AF_INET6) && HAVE_IPV6 && HAVE_LINUX

#if HAVE_SOLARIS

/*
 * Converts prefix length to network mask. Assumes
 * addr points to a zeroed out buffer and prefix <= sizeof(addr)
 * Unlike plen_to_mask returns netmask in binary form and not
 * in text form.
 */
static void plen_to_netmask(int prefix, unsigned char *addr) {
    for (; prefix > 8; prefix -= 8)
        *addr++ = 0xff;
    for (; prefix > 0; prefix--)
        *addr = (*addr >> 1) | 0x80;
}

/*
 * This function goes through all the IP interfaces associated with a
 * physical interface and finds the best matched one for use by mDNS.
 * Returns NULL when none of the IP interfaces associated with a physical
 * interface are usable. Otherwise returns the best matched interface
 * information and a pointer to the best matched lifreq.
 */
struct ifi_info *
select_src_ifi_info_solaris(int sockfd, int numifs,
        struct lifreq *lifrlist, const char *curifname,
        struct lifreq **best_lifr)
{
    struct lifreq *lifr;
    struct lifreq lifrcopy;
    struct ifi_info *ifi;
    char *chptr;
    char cmpifname[LIFNAMSIZ];
    int i;
    uint64_t best_lifrflags = 0;
    uint64_t ifflags;

    *best_lifr = NULL;

    /*
     * Check all logical interfaces associated with the physical
     * interface and figure out which one works best for us.
     */
    for (i = numifs, lifr = lifrlist; i > 0; --i, ++lifr) {

        if (strlcpy(cmpifname, lifr->lifr_name, sizeof(cmpifname)) >= sizeof(cmpifname))
            continue; /* skip interface */

        /* Strip logical interface number before checking ifname */
        if ((chptr = strchr(cmpifname, ':')) != NULL)
            *chptr = '\0';

        /*
         * Check ifname to see if the logical interface is associated
         * with the physical interface we are interested in.
         */
        if (strcmp(cmpifname, curifname) != 0)
            continue;

        lifrcopy = *lifr;
        if (ioctl(sockfd, SIOCGLIFFLAGS, &lifrcopy) < 0) {
            /* interface removed */
            if (errno == ENXIO)
                continue;
            return(NULL);
        }
        ifflags = lifrcopy.lifr_flags;

        /* ignore address if not up */
        if ((ifflags & IFF_UP) == 0)
            continue;
        /*
         * Avoid address if any of the following flags are set:
         *  IFF_NOXMIT: no packets transmitted over interface
         *  IFF_NOLOCAL: no address
         *  IFF_PRIVATE: is not advertised
         */
        if (ifflags & (IFF_NOXMIT | IFF_NOLOCAL | IFF_PRIVATE))
            continue;

       /* A DHCP client will have IFF_UP set yet the address is zero. Ignore */
        if (lifr->lifr_addr.ss_family == AF_INET) {
               struct sockaddr_in *sinptr;

               sinptr = (struct sockaddr_in *) &lifr->lifr_addr;
               if (sinptr->sin_addr.s_addr == INADDR_ANY)
                       continue;
       }

        if (*best_lifr != NULL) {
            /*
             * Check if we found a better interface by checking
             * the flags. If flags are identical we prefer
             * the new found interface.
             */
            uint64_t diff_flags = best_lifrflags ^ ifflags;

            /* If interface has a different set of flags */
            if (diff_flags != 0) {
                /* Check flags in increasing order of ones we prefer */

                /* Address temporary? */
                if ((diff_flags & IFF_TEMPORARY) &&
                    (ifflags & IFF_TEMPORARY))
                    continue;
                /* Deprecated address? */
                if ((diff_flags & IFF_DEPRECATED) &&
                    (ifflags & IFF_DEPRECATED))
                    continue;
                /* Last best-matched interface address has preferred? */
                if ((diff_flags & IFF_PREFERRED) &&
                    ((ifflags & IFF_PREFERRED) == 0))
                    continue;
            }
        }

        /* Set best match interface & flags */
        *best_lifr = lifr;
        best_lifrflags = ifflags;
    }

    if (*best_lifr == NULL)
        return(NULL);

    /* Found a match: return the interface information */
    ifi = calloc(1, sizeof(struct ifi_info));
    if (ifi == NULL)
        return(NULL);

    ifi->ifi_flags = best_lifrflags;
    ifi->ifi_index = if_nametoindex((*best_lifr)->lifr_name);
    if (strlcpy(ifi->ifi_name, (*best_lifr)->lifr_name, sizeof(ifi->ifi_name)) >= sizeof(ifi->ifi_name)) {
        free(ifi);
        return(NULL);
    }
    return(ifi);
}

/*
 * Returns a list of IP interface information on Solaris. The function
 * returns all IP interfaces on the system with IPv4 address assigned
 * when passed AF_INET and returns IP interfaces with IPv6 address assigned
 * when AF_INET6 is passed.
 */
struct ifi_info *get_ifi_info_solaris(int family)
{
    struct ifi_info     *ifi, *ifihead, **ifipnext;
    int   sockfd;
    int  len;
    char  *buf;
    char *cptr;
    char  ifname[LIFNAMSIZ], cmpifname[LIFNAMSIZ];
    struct sockaddr_in *sinptr;
    struct lifnum lifn;
    struct lifconf lifc;
    struct lifreq *lifrp, *best_lifr;
    struct lifreq lifrcopy;
    int numifs, nlifr, n;
#if defined(AF_INET6) && HAVE_IPV6
    struct sockaddr_in6 *sinptr6;
#endif

    ifihead = NULL;

    sockfd = socket(family, SOCK_DGRAM, 0);
    if (sockfd < 0)
        goto gotError;

again:
    lifn.lifn_family = family;
    lifn.lifn_flags = 0;
    if (ioctl(sockfd, SIOCGLIFNUM, &lifn) < 0)
        goto gotError;
    /*
     * Pad interface count to detect & retrieve any
     * additional interfaces between IFNUM & IFCONF calls.
     */
    lifn.lifn_count += 4;
    numifs = lifn.lifn_count;
    len = numifs * sizeof (struct lifreq);
    buf = alloca(len);

    lifc.lifc_family = family;
    lifc.lifc_len = len;
    lifc.lifc_buf = buf;
    lifc.lifc_flags = 0;

    if (ioctl(sockfd, SIOCGLIFCONF, &lifc) < 0)
        goto gotError;

    nlifr = lifc.lifc_len / sizeof(struct lifreq);
    if (nlifr >= numifs)
        goto again;

    lifrp = lifc.lifc_req;
    ifipnext = &ifihead;

    for (n = nlifr; n > 0; n--, lifrp++) {

        if (lifrp->lifr_addr.ss_family != family)
            continue;

        /*
         * See if we have already processed the interface
         * by checking the interface names.
         */
        if (strlcpy(ifname, lifrp->lifr_name, sizeof(ifname)) >= sizeof(ifname))
            goto gotError;
        if ((cptr = strchr(ifname, ':')) != NULL)
            *cptr = '\0';

        /*
         * If any of the interfaces found so far share the physical
         * interface name then we have already processed the interface.
         */
        for (ifi = ifihead; ifi != NULL; ifi = ifi->ifi_next) {

            /* Retrieve physical interface name */
            (void) strlcpy(cmpifname, ifi->ifi_name, sizeof(cmpifname));

            /* Strip logical interface number before checking ifname */
            if ((cptr = strchr(cmpifname, ':')) != NULL)
                *cptr = '\0';

            if (strcmp(cmpifname, ifname) == 0)
                break;
        }
        if (ifi != NULL)
            continue; /* already processed */

        /*
         * New interface, find the one with the preferred source
         * address for our use in Multicast DNS.
         */
        if ((ifi = select_src_ifi_info_solaris(sockfd, nlifr,
            lifc.lifc_req, ifname, &best_lifr)) == NULL)
            continue;

        assert(best_lifr != NULL);
        assert((best_lifr->lifr_addr.ss_family == AF_INET6) ||
               (best_lifr->lifr_addr.ss_family == AF_INET));

        switch (best_lifr->lifr_addr.ss_family) {

#if defined(AF_INET6) && HAVE_IPV6
        case AF_INET6:
            sinptr6 = (struct sockaddr_in6 *) &best_lifr->lifr_addr;
            ifi->ifi_addr = malloc(sizeof(struct sockaddr_in6));
            if (ifi->ifi_addr == NULL)
                goto gotError;
            memcpy(ifi->ifi_addr, sinptr6, sizeof(struct sockaddr_in6));

            ifi->ifi_netmask = calloc(1, sizeof(struct sockaddr_in6));
            if (ifi->ifi_netmask == NULL)
                goto gotError;
            sinptr6 = (struct sockaddr_in6 *)(ifi->ifi_netmask);
            sinptr6->sin6_family = AF_INET6;
            plen_to_netmask(best_lifr->lifr_addrlen,
                    (unsigned char *) &(sinptr6->sin6_addr));
            break;
#endif

        case AF_INET:
            sinptr = (struct sockaddr_in *) &best_lifr->lifr_addr;
            ifi->ifi_addr = malloc(sizeof(struct sockaddr_in));
            if (ifi->ifi_addr == NULL)
                goto gotError;

            memcpy(ifi->ifi_addr, sinptr, sizeof(struct sockaddr_in));

            lifrcopy = *best_lifr;
            if (ioctl(sockfd, SIOCGLIFNETMASK, &lifrcopy) < 0) {
                /* interface removed */
                if (errno == ENXIO) {
                    free(ifi->ifi_addr);
                    free(ifi);
                    continue;
                }
                goto gotError;
            }

            ifi->ifi_netmask = malloc(sizeof(struct sockaddr_in));
            if (ifi->ifi_netmask == NULL)
                goto gotError;
            sinptr = (struct sockaddr_in *) &lifrcopy.lifr_addr;
            sinptr->sin_family = AF_INET;
            memcpy(ifi->ifi_netmask, sinptr, sizeof(struct sockaddr_in));
            break;

        default:
            /* never reached */
            break;
        }

        *ifipnext = ifi;            /* prev points to this new one */
        ifipnext = &ifi->ifi_next;  /* pointer to next one goes here */
    }

    (void) close(sockfd);
    return(ifihead);    /* pointer to first structure in linked list */

gotError:
    if (sockfd != -1)
        (void) close(sockfd);
    if (ifihead != NULL)
        free_ifi_info(ifihead);
    return(NULL);
}

#endif /* HAVE_SOLARIS */

struct ifi_info *get_ifi_info(int family, int doaliases)
{
    int junk;
    struct ifi_info     *ifi, *ifihead, **ifipnext, *ifipold, **ifiptr;
    int sockfd, sockf6, len, lastlen, flags, myflags;
#ifdef NOT_HAVE_IF_NAMETOINDEX
    int index = 200;
#endif
    char                *ptr, *buf, lastname[IFNAMSIZ], *cptr;
    struct ifconf ifc;
    struct ifreq        *ifr, ifrcopy;
    struct sockaddr_in  *sinptr;

#if defined(AF_INET6) && HAVE_IPV6
    struct sockaddr_in6 *sinptr6;
#endif

#if defined(AF_INET6) && HAVE_IPV6 && HAVE_LINUX
    if (family == AF_INET6) return get_ifi_info_linuxv6(doaliases);
#elif HAVE_SOLARIS
    return get_ifi_info_solaris(family);
#endif

    sockfd = -1;
    sockf6 = -1;
    buf = NULL;
    ifihead = NULL;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        goto gotError;
    }

    lastlen = 0;
    len = 100 * sizeof(struct ifreq);   /* initial buffer size guess */
    for ( ; ; ) {
        buf = (char*)malloc(len);
        if (buf == NULL) {
            goto gotError;
        }
        ifc.ifc_len = len;
        ifc.ifc_buf = buf;
        if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
            if (errno != EINVAL || lastlen != 0) {
                goto gotError;
            }
        } else {
            if (ifc.ifc_len == lastlen)
                break;      /* success, len has not changed */
            lastlen = ifc.ifc_len;
        }
        len += 10 * sizeof(struct ifreq);   /* increment */
        free(buf);
    }
    ifihead = NULL;
    ifipnext = &ifihead;
    lastname[0] = 0;
/* end get_ifi_info1 */

/* include get_ifi_info2 */
    for (ptr = buf; ptr < buf + ifc.ifc_len; ) {
        ifr = (struct ifreq *) ptr;

        /* Advance to next one in buffer */
        if (sizeof(struct ifreq) > sizeof(ifr->ifr_name) + GET_SA_LEN(ifr->ifr_addr))
            ptr += sizeof(struct ifreq);
        else
            ptr += sizeof(ifr->ifr_name) + GET_SA_LEN(ifr->ifr_addr);

//      fprintf(stderr, "intf %p name=%s AF=%d\n", index, ifr->ifr_name, ifr->ifr_addr.sa_family);

        if (ifr->ifr_addr.sa_family != family)
            continue;   /* ignore if not desired address family */

        myflags = 0;
        if ( (cptr = strchr(ifr->ifr_name, ':')) != NULL)
            *cptr = 0;      /* replace colon will null */
        if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) {
            if (doaliases == 0)
                continue;   /* already processed this interface */
            myflags = IFI_ALIAS;
        }
        memcpy(lastname, ifr->ifr_name, IFNAMSIZ);

        ifrcopy = *ifr;
        if (ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy) < 0) {
            goto gotError;
        }

        flags = ifrcopy.ifr_flags;
        if ((flags & IFF_UP) == 0)
            continue;   /* ignore if interface not up */

        ifi = (struct ifi_info*)calloc(1, sizeof(struct ifi_info));
        if (ifi == NULL) {
            goto gotError;
        }
        ifipold   = *ifipnext;       /* need this later */
        ifiptr    = ifipnext;
        *ifipnext = ifi;             /* prev points to this new one */
        ifipnext  = &ifi->ifi_next;  /* pointer to next one goes here */

        ifi->ifi_flags = flags;     /* IFF_xxx values */
        ifi->ifi_myflags = myflags; /* IFI_xxx values */
#ifndef NOT_HAVE_IF_NAMETOINDEX
        ifi->ifi_index = if_nametoindex(ifr->ifr_name);
#else
        ifrcopy = *ifr;
#ifdef SIOCGIFINDEX
        if ( 0 >= ioctl(sockfd, SIOCGIFINDEX, &ifrcopy))
            ifi->ifi_index = ifrcopy.ifr_index;
        else
#endif
        ifi->ifi_index = index++;       /* SIOCGIFINDEX is broken on Solaris 2.5ish, so fake it */
#endif
        memcpy(ifi->ifi_name, ifr->ifr_name, IFI_NAME);
        ifi->ifi_name[IFI_NAME-1] = '\0';
/* end get_ifi_info2 */
/* include get_ifi_info3 */
        switch (ifr->ifr_addr.sa_family) {
        case AF_INET:
            sinptr = (struct sockaddr_in *) &ifr->ifr_addr;
            if (ifi->ifi_addr == NULL) {
                ifi->ifi_addr = (struct sockaddr*)calloc(1, sizeof(struct sockaddr_in));
                if (ifi->ifi_addr == NULL) {
                    goto gotError;
                }
                memcpy(ifi->ifi_addr, sinptr, sizeof(struct sockaddr_in));

#ifdef  SIOCGIFNETMASK
                if (ioctl(sockfd, SIOCGIFNETMASK, &ifrcopy) < 0) {
                    if (errno == EADDRNOTAVAIL) {
                        /*
                         * If the main interface is configured with no IP address but
                         * an alias interface exists with an IP address, you get
                         * EADDRNOTAVAIL for the main interface
                         */
                        free(ifi->ifi_addr);
                        free(ifi);
                        ifipnext  = ifiptr;
                        *ifipnext = ifipold;
                        continue;
                    } else {
                        goto gotError;
                    }
                }

                ifi->ifi_netmask = (struct sockaddr*)calloc(1, sizeof(struct sockaddr_in));
                if (ifi->ifi_netmask == NULL) goto gotError;
                sinptr = (struct sockaddr_in *) &ifrcopy.ifr_addr;
                /* The BSD ioctls (including Mac OS X) stick some weird values in for sin_len and sin_family */
#ifndef NOT_HAVE_SA_LEN
                sinptr->sin_len    = sizeof(struct sockaddr_in);
#endif
                sinptr->sin_family = AF_INET;
                memcpy(ifi->ifi_netmask, sinptr, sizeof(struct sockaddr_in));
#endif

#ifdef  SIOCGIFBRDADDR
                if (flags & IFF_BROADCAST) {
                    if (ioctl(sockfd, SIOCGIFBRDADDR, &ifrcopy) < 0) {
                        goto gotError;
                    }
                    sinptr = (struct sockaddr_in *) &ifrcopy.ifr_broadaddr;
                    /* The BSD ioctls (including Mac OS X) stick some weird values in for sin_len and sin_family */
#ifndef NOT_HAVE_SA_LEN
                    sinptr->sin_len    = sizeof( struct sockaddr_in );
#endif
                    sinptr->sin_family = AF_INET;
                    ifi->ifi_brdaddr = (struct sockaddr*)calloc(1, sizeof(struct sockaddr_in));
                    if (ifi->ifi_brdaddr == NULL) {
                        goto gotError;
                    }
                    memcpy(ifi->ifi_brdaddr, sinptr, sizeof(struct sockaddr_in));
                }
#endif

#ifdef  SIOCGIFDSTADDR
                if (flags & IFF_POINTOPOINT) {
                    if (ioctl(sockfd, SIOCGIFDSTADDR, &ifrcopy) < 0) {
                        goto gotError;
                    }
                    sinptr = (struct sockaddr_in *) &ifrcopy.ifr_dstaddr;
                    /* The BSD ioctls (including Mac OS X) stick some weird values in for sin_len and sin_family */
#ifndef NOT_HAVE_SA_LEN
                    sinptr->sin_len    = sizeof( struct sockaddr_in );
#endif
                    sinptr->sin_family = AF_INET;
                    ifi->ifi_dstaddr = (struct sockaddr*)calloc(1, sizeof(struct sockaddr_in));
                    if (ifi->ifi_dstaddr == NULL) {
                        goto gotError;
                    }
                    memcpy(ifi->ifi_dstaddr, sinptr, sizeof(struct sockaddr_in));
                }
#endif
            }
            break;

#if defined(AF_INET6) && HAVE_IPV6
        case AF_INET6:
            sinptr6 = (struct sockaddr_in6 *) &ifr->ifr_addr;
            if (ifi->ifi_addr == NULL) {
                ifi->ifi_addr = calloc(1, sizeof(struct sockaddr_in6));
                if (ifi->ifi_addr == NULL) {
                    goto gotError;
                }

                /* Some platforms (*BSD) inject the prefix in IPv6LL addresses */
                /* We need to strip that out */
                if (IN6_IS_ADDR_LINKLOCAL(&sinptr6->sin6_addr))
                    sinptr6->sin6_addr.s6_addr[2] = sinptr6->sin6_addr.s6_addr[3] = 0;
                memcpy(ifi->ifi_addr, sinptr6, sizeof(struct sockaddr_in6));

#ifdef  SIOCGIFNETMASK_IN6
                {
                    struct in6_ifreq ifr6;
                    if (sockf6 == -1)
                        sockf6 = socket(AF_INET6, SOCK_DGRAM, 0);
                    memset(&ifr6, 0, sizeof(ifr6));
                    memcpy(&ifr6.ifr_name,           &ifr->ifr_name, sizeof(ifr6.ifr_name          ));
                    memcpy(&ifr6.ifr_ifru.ifru_addr, &ifr->ifr_addr, sizeof(ifr6.ifr_ifru.ifru_addr));
                    if (ioctl(sockf6, SIOCGIFNETMASK_IN6, &ifr6) < 0) {
                        if (errno == EADDRNOTAVAIL) {
                            /*
                             * If the main interface is configured with no IP address but
                             * an alias interface exists with an IP address, you get
                             * EADDRNOTAVAIL for the main interface
                             */
                            free(ifi->ifi_addr);
                            free(ifi);
                            ifipnext  = ifiptr;
                            *ifipnext = ifipold;
                            continue;
                        } else {
                            goto gotError;
                        }
                    }
                    ifi->ifi_netmask = (struct sockaddr*)calloc(1, sizeof(struct sockaddr_in6));
                    if (ifi->ifi_netmask == NULL) goto gotError;
                    sinptr6 = (struct sockaddr_in6 *) &ifr6.ifr_ifru.ifru_addr;
                    memcpy(ifi->ifi_netmask, sinptr6, sizeof(struct sockaddr_in6));
                }
#endif
            }
            break;
#endif

        default:
            break;
        }
    }
    goto done;

gotError:
    if (ifihead != NULL) {
        free_ifi_info(ifihead);
        ifihead = NULL;
    }

done:
    if (buf != NULL) {
        free(buf);
    }
    if (sockfd != -1) {
        junk = close(sockfd);
        assert(junk == 0);
    }
    if (sockf6 != -1) {
        junk = close(sockf6);
        assert(junk == 0);
    }
    return(ifihead);    /* pointer to first structure in linked list */
}
/* end get_ifi_info3 */

/* include free_ifi_info */
void
free_ifi_info(struct ifi_info *ifihead)
{
    struct ifi_info *ifi, *ifinext;

    for (ifi = ifihead; ifi != NULL; ifi = ifinext) {
        if (ifi->ifi_addr != NULL)
            free(ifi->ifi_addr);
        if (ifi->ifi_netmask != NULL)
            free(ifi->ifi_netmask);
        if (ifi->ifi_brdaddr != NULL)
            free(ifi->ifi_brdaddr);
        if (ifi->ifi_dstaddr != NULL)
            free(ifi->ifi_dstaddr);
        ifinext = ifi->ifi_next;    /* can't fetch ifi_next after free() */
        free(ifi);                  /* the ifi_info{} itself */
    }
}
/* end free_ifi_info */

ssize_t
recvfrom_flags(int fd, void *ptr, size_t nbytes, int *flagsp,
               struct sockaddr *sa, socklen_t *salenptr, struct my_in_pktinfo *pktp, u_char *ttl)
{
    struct msghdr msg;
    struct iovec iov[1];
    ssize_t n;

#ifdef CMSG_FIRSTHDR
    struct cmsghdr  *cmptr;
    union {
        struct cmsghdr cm;
        char control[1024];
	pad64_t align8; /* ensure structure is 8-byte aligned on sparc */
    } control_un;

    *ttl = 255;         // If kernel fails to provide TTL data then assume the TTL was 255 as it should be

    msg.msg_control = (void *) control_un.control;
    msg.msg_controllen = sizeof(control_un.control);
    msg.msg_flags = 0;
#else
    memset(&msg, 0, sizeof(msg));   /* make certain msg_accrightslen = 0 */
#endif /* CMSG_FIRSTHDR */

    msg.msg_name = (char *) sa;
    msg.msg_namelen = *salenptr;
    iov[0].iov_base = (char *)ptr;
    iov[0].iov_len = nbytes;
    msg.msg_iov = iov;
    msg.msg_iovlen = 1;

    if ( (n = recvmsg(fd, &msg, *flagsp)) < 0)
        return(n);

    *salenptr = msg.msg_namelen;    /* pass back results */
    if (pktp) {
        /* 0.0.0.0, i/f = -1 */
        /* We set the interface to -1 so that the caller can
           tell whether we returned a meaningful value or
           just some default.  Previously this code just
           set the value to 0, but I'm concerned that 0
           might be a valid interface value.
         */
        memset(pktp, 0, sizeof(struct my_in_pktinfo));
        pktp->ipi_ifindex = -1;
    }
/* end recvfrom_flags1 */

/* include recvfrom_flags2 */
#ifndef CMSG_FIRSTHDR
    #warning CMSG_FIRSTHDR not defined. Will not be able to determine destination address, received interface, etc.
    *flagsp = 0;                    /* pass back results */
    return(n);
#else

    *flagsp = msg.msg_flags;        /* pass back results */
    if (msg.msg_controllen < (socklen_t)sizeof(struct cmsghdr) ||
        (msg.msg_flags & MSG_CTRUNC) || pktp == NULL)
        return(n);

    for (cmptr = CMSG_FIRSTHDR(&msg); cmptr != NULL;
         cmptr = CMSG_NXTHDR(&msg, cmptr)) {

#ifdef  IP_PKTINFO
#if in_pktinfo_definition_is_missing
        struct in_pktinfo
        {
            int ipi_ifindex;
            struct in_addr ipi_spec_dst;
            struct in_addr ipi_addr;
        };
#endif
        if (cmptr->cmsg_level == IPPROTO_IP &&
            cmptr->cmsg_type == IP_PKTINFO) {
            struct in_pktinfo *tmp;
            struct sockaddr_in *sin = (struct sockaddr_in*)&pktp->ipi_addr;

            tmp = (struct in_pktinfo *) CMSG_DATA(cmptr);
            sin->sin_family = AF_INET;
            sin->sin_addr = tmp->ipi_addr;
            sin->sin_port = 0;
            pktp->ipi_ifindex = tmp->ipi_ifindex;
            continue;
        }
#endif

#ifdef  IP_RECVDSTADDR
        if (cmptr->cmsg_level == IPPROTO_IP &&
            cmptr->cmsg_type == IP_RECVDSTADDR) {
            struct sockaddr_in *sin = (struct sockaddr_in*)&pktp->ipi_addr;

            sin->sin_family = AF_INET;
            sin->sin_addr = *(struct in_addr*)CMSG_DATA(cmptr);
            sin->sin_port = 0;
            continue;
        }
#endif

#ifdef  IP_RECVIF
        if (cmptr->cmsg_level == IPPROTO_IP &&
            cmptr->cmsg_type == IP_RECVIF) {
            struct sockaddr_dl  *sdl = (struct sockaddr_dl *) CMSG_DATA(cmptr);
#ifndef HAVE_BROKEN_RECVIF_NAME
            int nameLen = (sdl->sdl_nlen < IFI_NAME - 1) ? sdl->sdl_nlen : (IFI_NAME - 1);
            strncpy(pktp->ipi_ifname, sdl->sdl_data, nameLen);
#endif
	    /*
	     * the is memcpy used for sparc? no idea;)
	     * pktp->ipi_ifindex = sdl->sdl_index;
	     */
	    (void) memcpy(&pktp->ipi_ifindex, CMSG_DATA(cmptr), sizeof(uint_t));
#ifdef HAVE_BROKEN_RECVIF_NAME
            if (sdl->sdl_index == 0) {
                pktp->ipi_ifindex = *(uint_t*)sdl;
            }
#endif
            assert(pktp->ipi_ifname[IFI_NAME - 1] == 0);
            // null terminated because of memset above
            continue;
        }
#endif

#ifdef  IP_RECVTTL
        if (cmptr->cmsg_level == IPPROTO_IP &&
            cmptr->cmsg_type == IP_RECVTTL) {
            *ttl = *(u_char*)CMSG_DATA(cmptr);
            continue;
        }
        else if (cmptr->cmsg_level == IPPROTO_IP &&
                 cmptr->cmsg_type == IP_TTL) {  // some implementations seem to send IP_TTL instead of IP_RECVTTL
            *ttl = *(int*)CMSG_DATA(cmptr);
            continue;
        }
#endif

#if defined(IPV6_PKTINFO) && HAVE_IPV6
        if (cmptr->cmsg_level == IPPROTO_IPV6 &&
            cmptr->cmsg_type  == IPV6_PKTINFO) {
            struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&pktp->ipi_addr;
            struct in6_pktinfo *ip6_info = (struct in6_pktinfo*)CMSG_DATA(cmptr);

            sin6->sin6_family   = AF_INET6;
#ifndef NOT_HAVE_SA_LEN
            sin6->sin6_len      = sizeof(*sin6);
#endif
            sin6->sin6_addr     = ip6_info->ipi6_addr;
            sin6->sin6_flowinfo = 0;
            sin6->sin6_scope_id = 0;
            sin6->sin6_port     = 0;
            pktp->ipi_ifindex   = ip6_info->ipi6_ifindex;
            continue;
        }
#endif

#if defined(IPV6_HOPLIMIT) && HAVE_IPV6
        if (cmptr->cmsg_level == IPPROTO_IPV6 &&
            cmptr->cmsg_type == IPV6_HOPLIMIT) {
            *ttl = *(int*)CMSG_DATA(cmptr);
            continue;
        }
#endif
        assert(0);  // unknown ancillary data
    }
    return(n);
#endif /* CMSG_FIRSTHDR */
}

// **********************************************************************************************

// daemonize the process. Adapted from "Unix Network Programming" vol 1 by Stevens, section 12.4.
// Returns 0 on success, -1 on failure.

#ifdef NOT_HAVE_DAEMON
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/signal.h>

int daemon(int nochdir, int noclose)
{
    switch (fork())
    {
    case -1: return (-1);       // Fork failed
    case 0:  break;             // Child -- continue
    default: _exit(0);          // Parent -- exit
    }

    if (setsid() == -1) return(-1);

    signal(SIGHUP, SIG_IGN);

    switch (fork())             // Fork again, primarily for reasons of Unix trivia
    {
    case -1: return (-1);       // Fork failed
    case 0:  break;             // Child -- continue
    default: _exit(0);          // Parent -- exit
    }

    if (!nochdir) (void)chdir("/");
    umask(0);

    if (!noclose)
    {
        int fd = open("/dev/null", O_RDWR, 0);
        if (fd != -1)
        {
            // Avoid unnecessarily duplicating a file descriptor to itself
            if (fd != STDIN_FILENO) (void)dup2(fd, STDIN_FILENO);
            if (fd != STDOUT_FILENO) (void)dup2(fd, STDOUT_FILENO);
            if (fd != STDERR_FILENO) (void)dup2(fd, STDERR_FILENO);
            if (fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO)
                (void)close (fd);
        }
    }
    return (0);
}
#endif /* NOT_HAVE_DAEMON */
/* -*- Mode: C; tab-width: 4 -*-
 *
 * Copyright (c) 2002-2018 Apple Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef __mDNSUNP_h
#define __mDNSUNP_h

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

#ifdef HAVE_LINUX
#include <linux/socket.h>
#define IPV6_2292_PKTINFO  IPV6_2292PKTINFO
#define IPV6_2292_HOPLIMIT IPV6_2292HOPLIMIT
#else
// The following are the supported non-linux posix OSes -
// netbsd, freebsd and openbsd.
#if HAVE_IPV6
#define IPV6_2292_PKTINFO  19
#define IPV6_2292_HOPLIMIT 20
#endif
#endif

#ifdef  __cplusplus
extern "C" {
#endif

#ifdef NOT_HAVE_SOCKLEN_T
typedef unsigned int socklen_t;
#endif

#ifndef NOT_HAVE_SA_LEN
#define GET_SA_LEN(X) (sizeof(struct sockaddr) > ((struct sockaddr*)&(X))->sa_len ? \
                       sizeof(struct sockaddr) : ((struct sockaddr*)&(X))->sa_len   )
#elif HAVE_IPV6
#define GET_SA_LEN(X) (((struct sockaddr*)&(X))->sa_family == AF_INET  ? sizeof(struct sockaddr_in) : \
                       ((struct sockaddr*)&(X))->sa_family == AF_INET6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr))
#else
#define GET_SA_LEN(X) (((struct sockaddr*)&(X))->sa_family == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr))
#endif

#define IFI_NAME    IFNAMSIZ    /* same as IFNAMSIZ in <net/if.h> */
#define IFI_HADDR   8           /* allow for 64-bit EUI-64 in future */

// Renamed from my_in_pktinfo because in_pktinfo is used by Linux.

struct my_in_pktinfo {
    struct sockaddr_storage ipi_addr;
    int ipi_ifindex;                                /* received interface index */
    char ipi_ifname[IFI_NAME];                      /* received interface name  */
};

/* From the text (Stevens, section 20.2): */
/* 'As an example of recvmsg we will write a function named recvfrom_flags that */
/* is similar to recvfrom but also returns: */
/*	1. the returned msg_flags value, */
/*	2. the destination addres of the received datagram (from the IP_RECVDSTADDR socket option, and */
/*	3. the index of the interface on which the datagram was received (the IP_RECVIF socket option).' */
extern ssize_t recvfrom_flags(int fd, void *ptr, size_t nbytes, int *flagsp,
                              struct sockaddr *sa, socklen_t *salenptr, struct my_in_pktinfo *pktp, u_char *ttl);

struct ifi_info {
    char ifi_name[IFI_NAME];    /* interface name, null terminated */
    u_char ifi_haddr[IFI_HADDR]; /* hardware address */
    u_short ifi_hlen;           /* #bytes in hardware address: 0, 6, 8 */
    short ifi_flags;            /* IFF_xxx constants from <net/if.h> */
    short ifi_myflags;          /* our own IFI_xxx flags */
    int ifi_index;              /* interface index */
    struct sockaddr  *ifi_addr; /* primary address */
    struct sockaddr  *ifi_netmask;
    struct sockaddr  *ifi_brdaddr; /* broadcast address */
    struct sockaddr  *ifi_dstaddr; /* destination address */
    struct ifi_info  *ifi_next; /* next of these structures */
};

#define IFI_ALIAS   1           /* ifi_addr is an alias */

/* From the text (Stevens, section 16.6): */
/* 'Since many programs need to know all the interfaces on a system, we will develop a */
/* function of our own named get_ifi_info that returns a linked list of structures, one */
/* for each interface that is currently "up."' */
extern struct ifi_info  *get_ifi_info(int family, int doaliases);

/* 'The free_ifi_info function, which takes a pointer that was */
/* returned by get_ifi_info and frees all the dynamic memory.' */
extern void free_ifi_info(struct ifi_info *);

#if defined(AF_INET6) && HAVE_IPV6
#define INET6_ADDRSTRLEN 46 /*Maximum length of IPv6 address */
#endif

#ifdef NOT_HAVE_DAEMON
extern int daemon(int nochdir, int noclose);
#endif

#ifdef  __cplusplus
}
#endif

#endif
//
//  posix_utilities.c
//  mDNSResponder
//
//  Copyright (c) 2019 Apple Inc. All rights reserved.
//

#include "posix_utilities.h"
#include "mDNSEmbeddedAPI.h"
#include <stdlib.h>                 // for NULL
#include <stdio.h>                  // for snprintf
#include <time.h>
#include <sys/time.h>               // for gettimeofday

mDNSexport void getLocalTimestamp(char * const buffer, mDNSu32 buffer_len)
{
    struct timeval      now;
    struct tm           local_time;
    char                date_time_str[32];
    char                time_zone_str[32];

    gettimeofday(&now, NULL);
    localtime_r(&now.tv_sec, &local_time);

    strftime(date_time_str, sizeof(date_time_str), "%F %T", &local_time);
    strftime(time_zone_str, sizeof(time_zone_str), "%z", &local_time);
    snprintf(buffer, buffer_len, "%s.%06lu%s", date_time_str, (unsigned long)now.tv_usec, time_zone_str);
}
//
//  posix_utilities.h
//  mDNSResponder
//
//  Copyright (c) 2019 Apple Inc. All rights reserved.
//

#ifndef posix_utilities_h
#define posix_utilities_h

#include "mDNSEmbeddedAPI.h"

// timestamp format: "2008-08-08 20:00:00.000000+0800", a 64-byte buffer is enough to store the result
extern void getLocalTimestamp(char * const buffer, mDNSu32 buffer_len);

#endif /* posix_utilities_h */