|
root / base / usr / src / contrib / mDNSResponder / mDNSShared
mDNSShared Plain Text 15569 lines 631.7 KB
    1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
  248
  249
  250
  251
  252
  253
  254
  255
  256
  257
  258
  259
  260
  261
  262
  263
  264
  265
  266
  267
  268
  269
  270
  271
  272
  273
  274
  275
  276
  277
  278
  279
  280
  281
  282
  283
  284
  285
  286
  287
  288
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311
  312
  313
  314
  315
  316
  317
  318
  319
  320
  321
  322
  323
  324
  325
  326
  327
  328
  329
  330
  331
  332
  333
  334
  335
  336
  337
  338
  339
  340
  341
  342
  343
  344
  345
  346
  347
  348
  349
  350
  351
  352
  353
  354
  355
  356
  357
  358
  359
  360
  361
  362
  363
  364
  365
  366
  367
  368
  369
  370
  371
  372
  373
  374
  375
  376
  377
  378
  379
  380
  381
  382
  383
  384
  385
  386
  387
  388
  389
  390
  391
  392
  393
  394
  395
  396
  397
  398
  399
  400
  401
  402
  403
  404
  405
  406
  407
  408
  409
  410
  411
  412
  413
  414
  415
  416
  417
  418
  419
  420
  421
  422
  423
  424
  425
  426
  427
  428
  429
  430
  431
  432
  433
  434
  435
  436
  437
  438
  439
  440
  441
  442
  443
  444
  445
  446
  447
  448
  449
  450
  451
  452
  453
  454
  455
  456
  457
  458
  459
  460
  461
  462
  463
  464
  465
  466
  467
  468
  469
  470
  471
  472
  473
  474
  475
  476
  477
  478
  479
  480
  481
  482
  483
  484
  485
  486
  487
  488
  489
  490
  491
  492
  493
  494
  495
  496
  497
  498
  499
  500
  501
  502
  503
  504
  505
  506
  507
  508
  509
  510
  511
  512
  513
  514
  515
  516
  517
  518
  519
  520
  521
  522
  523
  524
  525
  526
  527
  528
  529
  530
  531
  532
  533
  534
  535
  536
  537
  538
  539
  540
  541
  542
  543
  544
  545
  546
  547
  548
  549
  550
  551
  552
  553
  554
  555
  556
  557
  558
  559
  560
  561
  562
  563
  564
  565
  566
  567
  568
  569
  570
  571
  572
  573
  574
  575
  576
  577
  578
  579
  580
  581
  582
  583
  584
  585
  586
  587
  588
  589
  590
  591
  592
  593
  594
  595
  596
  597
  598
  599
  600
  601
  602
  603
  604
  605
  606
  607
  608
  609
  610
  611
  612
  613
  614
  615
  616
  617
  618
  619
  620
  621
  622
  623
  624
  625
  626
  627
  628
  629
  630
  631
  632
  633
  634
  635
  636
  637
  638
  639
  640
  641
  642
  643
  644
  645
  646
  647
  648
  649
  650
  651
  652
  653
  654
  655
  656
  657
  658
  659
  660
  661
  662
  663
  664
  665
  666
  667
  668
  669
  670
  671
  672
  673
  674
  675
  676
  677
  678
  679
  680
  681
  682
  683
  684
  685
  686
  687
  688
  689
  690
  691
  692
  693
  694
  695
  696
  697
  698
  699
  700
  701
  702
  703
  704
  705
  706
  707
  708
  709
  710
  711
  712
  713
  714
  715
  716
  717
  718
  719
  720
  721
  722
  723
  724
  725
  726
  727
  728
  729
  730
  731
  732
  733
  734
  735
  736
  737
  738
  739
  740
  741
  742
  743
  744
  745
  746
  747
  748
  749
  750
  751
  752
  753
  754
  755
  756
  757
  758
  759
  760
  761
  762
  763
  764
  765
  766
  767
  768
  769
  770
  771
  772
  773
  774
  775
  776
  777
  778
  779
  780
  781
  782
  783
  784
  785
  786
  787
  788
  789
  790
  791
  792
  793
  794
  795
  796
  797
  798
  799
  800
  801
  802
  803
  804
  805
  806
  807
  808
  809
  810
  811
  812
  813
  814
  815
  816
  817
  818
  819
  820
  821
  822
  823
  824
  825
  826
  827
  828
  829
  830
  831
  832
  833
  834
  835
  836
  837
  838
  839
  840
  841
  842
  843
  844
  845
  846
  847
  848
  849
  850
  851
  852
  853
  854
  855
  856
  857
  858
  859
  860
  861
  862
  863
  864
  865
  866
  867
  868
  869
  870
  871
  872
  873
  874
  875
  876
  877
  878
  879
  880
  881
  882
  883
  884
  885
  886
  887
  888
  889
  890
  891
  892
  893
  894
  895
  896
  897
  898
  899
  900
  901
  902
  903
  904
  905
  906
  907
  908
  909
  910
  911
  912
  913
  914
  915
  916
  917
  918
  919
  920
  921
  922
  923
  924
  925
  926
  927
  928
  929
  930
  931
  932
  933
  934
  935
  936
  937
  938
  939
  940
  941
  942
  943
  944
  945
  946
  947
  948
  949
  950
  951
  952
  953
  954
  955
  956
  957
  958
  959
  960
  961
  962
  963
  964
  965
  966
  967
  968
  969
  970
  971
  972
  973
  974
  975
  976
  977
  978
  979
  980
  981
  982
  983
  984
  985
  986
  987
  988
  989
  990
  991
  992
  993
  994
  995
  996
  997
  998
  999
 1000
 1001
 1002
 1003
 1004
 1005
 1006
 1007
 1008
 1009
 1010
 1011
 1012
 1013
 1014
 1015
 1016
 1017
 1018
 1019
 1020
 1021
 1022
 1023
 1024
 1025
 1026
 1027
 1028
 1029
 1030
 1031
 1032
 1033
 1034
 1035
 1036
 1037
 1038
 1039
 1040
 1041
 1042
 1043
 1044
 1045
 1046
 1047
 1048
 1049
 1050
 1051
 1052
 1053
 1054
 1055
 1056
 1057
 1058
 1059
 1060
 1061
 1062
 1063
 1064
 1065
 1066
 1067
 1068
 1069
 1070
 1071
 1072
 1073
 1074
 1075
 1076
 1077
 1078
 1079
 1080
 1081
 1082
 1083
 1084
 1085
 1086
 1087
 1088
 1089
 1090
 1091
 1092
 1093
 1094
 1095
 1096
 1097
 1098
 1099
 1100
 1101
 1102
 1103
 1104
 1105
 1106
 1107
 1108
 1109
 1110
 1111
 1112
 1113
 1114
 1115
 1116
 1117
 1118
 1119
 1120
 1121
 1122
 1123
 1124
 1125
 1126
 1127
 1128
 1129
 1130
 1131
 1132
 1133
 1134
 1135
 1136
 1137
 1138
 1139
 1140
 1141
 1142
 1143
 1144
 1145
 1146
 1147
 1148
 1149
 1150
 1151
 1152
 1153
 1154
 1155
 1156
 1157
 1158
 1159
 1160
 1161
 1162
 1163
 1164
 1165
 1166
 1167
 1168
 1169
 1170
 1171
 1172
 1173
 1174
 1175
 1176
 1177
 1178
 1179
 1180
 1181
 1182
 1183
 1184
 1185
 1186
 1187
 1188
 1189
 1190
 1191
 1192
 1193
 1194
 1195
 1196
 1197
 1198
 1199
 1200
 1201
 1202
 1203
 1204
 1205
 1206
 1207
 1208
 1209
 1210
 1211
 1212
 1213
 1214
 1215
 1216
 1217
 1218
 1219
 1220
 1221
 1222
 1223
 1224
 1225
 1226
 1227
 1228
 1229
 1230
 1231
 1232
 1233
 1234
 1235
 1236
 1237
 1238
 1239
 1240
 1241
 1242
 1243
 1244
 1245
 1246
 1247
 1248
 1249
 1250
 1251
 1252
 1253
 1254
 1255
 1256
 1257
 1258
 1259
 1260
 1261
 1262
 1263
 1264
 1265
 1266
 1267
 1268
 1269
 1270
 1271
 1272
 1273
 1274
 1275
 1276
 1277
 1278
 1279
 1280
 1281
 1282
 1283
 1284
 1285
 1286
 1287
 1288
 1289
 1290
 1291
 1292
 1293
 1294
 1295
 1296
 1297
 1298
 1299
 1300
 1301
 1302
 1303
 1304
 1305
 1306
 1307
 1308
 1309
 1310
 1311
 1312
 1313
 1314
 1315
 1316
 1317
 1318
 1319
 1320
 1321
 1322
 1323
 1324
 1325
 1326
 1327
 1328
 1329
 1330
 1331
 1332
 1333
 1334
 1335
 1336
 1337
 1338
 1339
 1340
 1341
 1342
 1343
 1344
 1345
 1346
 1347
 1348
 1349
 1350
 1351
 1352
 1353
 1354
 1355
 1356
 1357
 1358
 1359
 1360
 1361
 1362
 1363
 1364
 1365
 1366
 1367
 1368
 1369
 1370
 1371
 1372
 1373
 1374
 1375
 1376
 1377
 1378
 1379
 1380
 1381
 1382
 1383
 1384
 1385
 1386
 1387
 1388
 1389
 1390
 1391
 1392
 1393
 1394
 1395
 1396
 1397
 1398
 1399
 1400
 1401
 1402
 1403
 1404
 1405
 1406
 1407
 1408
 1409
 1410
 1411
 1412
 1413
 1414
 1415
 1416
 1417
 1418
 1419
 1420
 1421
 1422
 1423
 1424
 1425
 1426
 1427
 1428
 1429
 1430
 1431
 1432
 1433
 1434
 1435
 1436
 1437
 1438
 1439
 1440
 1441
 1442
 1443
 1444
 1445
 1446
 1447
 1448
 1449
 1450
 1451
 1452
 1453
 1454
 1455
 1456
 1457
 1458
 1459
 1460
 1461
 1462
 1463
 1464
 1465
 1466
 1467
 1468
 1469
 1470
 1471
 1472
 1473
 1474
 1475
 1476
 1477
 1478
 1479
 1480
 1481
 1482
 1483
 1484
 1485
 1486
 1487
 1488
 1489
 1490
 1491
 1492
 1493
 1494
 1495
 1496
 1497
 1498
 1499
 1500
 1501
 1502
 1503
 1504
 1505
 1506
 1507
 1508
 1509
 1510
 1511
 1512
 1513
 1514
 1515
 1516
 1517
 1518
 1519
 1520
 1521
 1522
 1523
 1524
 1525
 1526
 1527
 1528
 1529
 1530
 1531
 1532
 1533
 1534
 1535
 1536
 1537
 1538
 1539
 1540
 1541
 1542
 1543
 1544
 1545
 1546
 1547
 1548
 1549
 1550
 1551
 1552
 1553
 1554
 1555
 1556
 1557
 1558
 1559
 1560
 1561
 1562
 1563
 1564
 1565
 1566
 1567
 1568
 1569
 1570
 1571
 1572
 1573
 1574
 1575
 1576
 1577
 1578
 1579
 1580
 1581
 1582
 1583
 1584
 1585
 1586
 1587
 1588
 1589
 1590
 1591
 1592
 1593
 1594
 1595
 1596
 1597
 1598
 1599
 1600
 1601
 1602
 1603
 1604
 1605
 1606
 1607
 1608
 1609
 1610
 1611
 1612
 1613
 1614
 1615
 1616
 1617
 1618
 1619
 1620
 1621
 1622
 1623
 1624
 1625
 1626
 1627
 1628
 1629
 1630
 1631
 1632
 1633
 1634
 1635
 1636
 1637
 1638
 1639
 1640
 1641
 1642
 1643
 1644
 1645
 1646
 1647
 1648
 1649
 1650
 1651
 1652
 1653
 1654
 1655
 1656
 1657
 1658
 1659
 1660
 1661
 1662
 1663
 1664
 1665
 1666
 1667
 1668
 1669
 1670
 1671
 1672
 1673
 1674
 1675
 1676
 1677
 1678
 1679
 1680
 1681
 1682
 1683
 1684
 1685
 1686
 1687
 1688
 1689
 1690
 1691
 1692
 1693
 1694
 1695
 1696
 1697
 1698
 1699
 1700
 1701
 1702
 1703
 1704
 1705
 1706
 1707
 1708
 1709
 1710
 1711
 1712
 1713
 1714
 1715
 1716
 1717
 1718
 1719
 1720
 1721
 1722
 1723
 1724
 1725
 1726
 1727
 1728
 1729
 1730
 1731
 1732
 1733
 1734
 1735
 1736
 1737
 1738
 1739
 1740
 1741
 1742
 1743
 1744
 1745
 1746
 1747
 1748
 1749
 1750
 1751
 1752
 1753
 1754
 1755
 1756
 1757
 1758
 1759
 1760
 1761
 1762
 1763
 1764
 1765
 1766
 1767
 1768
 1769
 1770
 1771
 1772
 1773
 1774
 1775
 1776
 1777
 1778
 1779
 1780
 1781
 1782
 1783
 1784
 1785
 1786
 1787
 1788
 1789
 1790
 1791
 1792
 1793
 1794
 1795
 1796
 1797
 1798
 1799
 1800
 1801
 1802
 1803
 1804
 1805
 1806
 1807
 1808
 1809
 1810
 1811
 1812
 1813
 1814
 1815
 1816
 1817
 1818
 1819
 1820
 1821
 1822
 1823
 1824
 1825
 1826
 1827
 1828
 1829
 1830
 1831
 1832
 1833
 1834
 1835
 1836
 1837
 1838
 1839
 1840
 1841
 1842
 1843
 1844
 1845
 1846
 1847
 1848
 1849
 1850
 1851
 1852
 1853
 1854
 1855
 1856
 1857
 1858
 1859
 1860
 1861
 1862
 1863
 1864
 1865
 1866
 1867
 1868
 1869
 1870
 1871
 1872
 1873
 1874
 1875
 1876
 1877
 1878
 1879
 1880
 1881
 1882
 1883
 1884
 1885
 1886
 1887
 1888
 1889
 1890
 1891
 1892
 1893
 1894
 1895
 1896
 1897
 1898
 1899
 1900
 1901
 1902
 1903
 1904
 1905
 1906
 1907
 1908
 1909
 1910
 1911
 1912
 1913
 1914
 1915
 1916
 1917
 1918
 1919
 1920
 1921
 1922
 1923
 1924
 1925
 1926
 1927
 1928
 1929
 1930
 1931
 1932
 1933
 1934
 1935
 1936
 1937
 1938
 1939
 1940
 1941
 1942
 1943
 1944
 1945
 1946
 1947
 1948
 1949
 1950
 1951
 1952
 1953
 1954
 1955
 1956
 1957
 1958
 1959
 1960
 1961
 1962
 1963
 1964
 1965
 1966
 1967
 1968
 1969
 1970
 1971
 1972
 1973
 1974
 1975
 1976
 1977
 1978
 1979
 1980
 1981
 1982
 1983
 1984
 1985
 1986
 1987
 1988
 1989
 1990
 1991
 1992
 1993
 1994
 1995
 1996
 1997
 1998
 1999
 2000
 2001
 2002
 2003
 2004
 2005
 2006
 2007
 2008
 2009
 2010
 2011
 2012
 2013
 2014
 2015
 2016
 2017
 2018
 2019
 2020
 2021
 2022
 2023
 2024
 2025
 2026
 2027
 2028
 2029
 2030
 2031
 2032
 2033
 2034
 2035
 2036
 2037
 2038
 2039
 2040
 2041
 2042
 2043
 2044
 2045
 2046
 2047
 2048
 2049
 2050
 2051
 2052
 2053
 2054
 2055
 2056
 2057
 2058
 2059
 2060
 2061
 2062
 2063
 2064
 2065
 2066
 2067
 2068
 2069
 2070
 2071
 2072
 2073
 2074
 2075
 2076
 2077
 2078
 2079
 2080
 2081
 2082
 2083
 2084
 2085
 2086
 2087
 2088
 2089
 2090
 2091
 2092
 2093
 2094
 2095
 2096
 2097
 2098
 2099
 2100
 2101
 2102
 2103
 2104
 2105
 2106
 2107
 2108
 2109
 2110
 2111
 2112
 2113
 2114
 2115
 2116
 2117
 2118
 2119
 2120
 2121
 2122
 2123
 2124
 2125
 2126
 2127
 2128
 2129
 2130
 2131
 2132
 2133
 2134
 2135
 2136
 2137
 2138
 2139
 2140
 2141
 2142
 2143
 2144
 2145
 2146
 2147
 2148
 2149
 2150
 2151
 2152
 2153
 2154
 2155
 2156
 2157
 2158
 2159
 2160
 2161
 2162
 2163
 2164
 2165
 2166
 2167
 2168
 2169
 2170
 2171
 2172
 2173
 2174
 2175
 2176
 2177
 2178
 2179
 2180
 2181
 2182
 2183
 2184
 2185
 2186
 2187
 2188
 2189
 2190
 2191
 2192
 2193
 2194
 2195
 2196
 2197
 2198
 2199
 2200
 2201
 2202
 2203
 2204
 2205
 2206
 2207
 2208
 2209
 2210
 2211
 2212
 2213
 2214
 2215
 2216
 2217
 2218
 2219
 2220
 2221
 2222
 2223
 2224
 2225
 2226
 2227
 2228
 2229
 2230
 2231
 2232
 2233
 2234
 2235
 2236
 2237
 2238
 2239
 2240
 2241
 2242
 2243
 2244
 2245
 2246
 2247
 2248
 2249
 2250
 2251
 2252
 2253
 2254
 2255
 2256
 2257
 2258
 2259
 2260
 2261
 2262
 2263
 2264
 2265
 2266
 2267
 2268
 2269
 2270
 2271
 2272
 2273
 2274
 2275
 2276
 2277
 2278
 2279
 2280
 2281
 2282
 2283
 2284
 2285
 2286
 2287
 2288
 2289
 2290
 2291
 2292
 2293
 2294
 2295
 2296
 2297
 2298
 2299
 2300
 2301
 2302
 2303
 2304
 2305
 2306
 2307
 2308
 2309
 2310
 2311
 2312
 2313
 2314
 2315
 2316
 2317
 2318
 2319
 2320
 2321
 2322
 2323
 2324
 2325
 2326
 2327
 2328
 2329
 2330
 2331
 2332
 2333
 2334
 2335
 2336
 2337
 2338
 2339
 2340
 2341
 2342
 2343
 2344
 2345
 2346
 2347
 2348
 2349
 2350
 2351
 2352
 2353
 2354
 2355
 2356
 2357
 2358
 2359
 2360
 2361
 2362
 2363
 2364
 2365
 2366
 2367
 2368
 2369
 2370
 2371
 2372
 2373
 2374
 2375
 2376
 2377
 2378
 2379
 2380
 2381
 2382
 2383
 2384
 2385
 2386
 2387
 2388
 2389
 2390
 2391
 2392
 2393
 2394
 2395
 2396
 2397
 2398
 2399
 2400
 2401
 2402
 2403
 2404
 2405
 2406
 2407
 2408
 2409
 2410
 2411
 2412
 2413
 2414
 2415
 2416
 2417
 2418
 2419
 2420
 2421
 2422
 2423
 2424
 2425
 2426
 2427
 2428
 2429
 2430
 2431
 2432
 2433
 2434
 2435
 2436
 2437
 2438
 2439
 2440
 2441
 2442
 2443
 2444
 2445
 2446
 2447
 2448
 2449
 2450
 2451
 2452
 2453
 2454
 2455
 2456
 2457
 2458
 2459
 2460
 2461
 2462
 2463
 2464
 2465
 2466
 2467
 2468
 2469
 2470
 2471
 2472
 2473
 2474
 2475
 2476
 2477
 2478
 2479
 2480
 2481
 2482
 2483
 2484
 2485
 2486
 2487
 2488
 2489
 2490
 2491
 2492
 2493
 2494
 2495
 2496
 2497
 2498
 2499
 2500
 2501
 2502
 2503
 2504
 2505
 2506
 2507
 2508
 2509
 2510
 2511
 2512
 2513
 2514
 2515
 2516
 2517
 2518
 2519
 2520
 2521
 2522
 2523
 2524
 2525
 2526
 2527
 2528
 2529
 2530
 2531
 2532
 2533
 2534
 2535
 2536
 2537
 2538
 2539
 2540
 2541
 2542
 2543
 2544
 2545
 2546
 2547
 2548
 2549
 2550
 2551
 2552
 2553
 2554
 2555
 2556
 2557
 2558
 2559
 2560
 2561
 2562
 2563
 2564
 2565
 2566
 2567
 2568
 2569
 2570
 2571
 2572
 2573
 2574
 2575
 2576
 2577
 2578
 2579
 2580
 2581
 2582
 2583
 2584
 2585
 2586
 2587
 2588
 2589
 2590
 2591
 2592
 2593
 2594
 2595
 2596
 2597
 2598
 2599
 2600
 2601
 2602
 2603
 2604
 2605
 2606
 2607
 2608
 2609
 2610
 2611
 2612
 2613
 2614
 2615
 2616
 2617
 2618
 2619
 2620
 2621
 2622
 2623
 2624
 2625
 2626
 2627
 2628
 2629
 2630
 2631
 2632
 2633
 2634
 2635
 2636
 2637
 2638
 2639
 2640
 2641
 2642
 2643
 2644
 2645
 2646
 2647
 2648
 2649
 2650
 2651
 2652
 2653
 2654
 2655
 2656
 2657
 2658
 2659
 2660
 2661
 2662
 2663
 2664
 2665
 2666
 2667
 2668
 2669
 2670
 2671
 2672
 2673
 2674
 2675
 2676
 2677
 2678
 2679
 2680
 2681
 2682
 2683
 2684
 2685
 2686
 2687
 2688
 2689
 2690
 2691
 2692
 2693
 2694
 2695
 2696
 2697
 2698
 2699
 2700
 2701
 2702
 2703
 2704
 2705
 2706
 2707
 2708
 2709
 2710
 2711
 2712
 2713
 2714
 2715
 2716
 2717
 2718
 2719
 2720
 2721
 2722
 2723
 2724
 2725
 2726
 2727
 2728
 2729
 2730
 2731
 2732
 2733
 2734
 2735
 2736
 2737
 2738
 2739
 2740
 2741
 2742
 2743
 2744
 2745
 2746
 2747
 2748
 2749
 2750
 2751
 2752
 2753
 2754
 2755
 2756
 2757
 2758
 2759
 2760
 2761
 2762
 2763
 2764
 2765
 2766
 2767
 2768
 2769
 2770
 2771
 2772
 2773
 2774
 2775
 2776
 2777
 2778
 2779
 2780
 2781
 2782
 2783
 2784
 2785
 2786
 2787
 2788
 2789
 2790
 2791
 2792
 2793
 2794
 2795
 2796
 2797
 2798
 2799
 2800
 2801
 2802
 2803
 2804
 2805
 2806
 2807
 2808
 2809
 2810
 2811
 2812
 2813
 2814
 2815
 2816
 2817
 2818
 2819
 2820
 2821
 2822
 2823
 2824
 2825
 2826
 2827
 2828
 2829
 2830
 2831
 2832
 2833
 2834
 2835
 2836
 2837
 2838
 2839
 2840
 2841
 2842
 2843
 2844
 2845
 2846
 2847
 2848
 2849
 2850
 2851
 2852
 2853
 2854
 2855
 2856
 2857
 2858
 2859
 2860
 2861
 2862
 2863
 2864
 2865
 2866
 2867
 2868
 2869
 2870
 2871
 2872
 2873
 2874
 2875
 2876
 2877
 2878
 2879
 2880
 2881
 2882
 2883
 2884
 2885
 2886
 2887
 2888
 2889
 2890
 2891
 2892
 2893
 2894
 2895
 2896
 2897
 2898
 2899
 2900
 2901
 2902
 2903
 2904
 2905
 2906
 2907
 2908
 2909
 2910
 2911
 2912
 2913
 2914
 2915
 2916
 2917
 2918
 2919
 2920
 2921
 2922
 2923
 2924
 2925
 2926
 2927
 2928
 2929
 2930
 2931
 2932
 2933
 2934
 2935
 2936
 2937
 2938
 2939
 2940
 2941
 2942
 2943
 2944
 2945
 2946
 2947
 2948
 2949
 2950
 2951
 2952
 2953
 2954
 2955
 2956
 2957
 2958
 2959
 2960
 2961
 2962
 2963
 2964
 2965
 2966
 2967
 2968
 2969
 2970
 2971
 2972
 2973
 2974
 2975
 2976
 2977
 2978
 2979
 2980
 2981
 2982
 2983
 2984
 2985
 2986
 2987
 2988
 2989
 2990
 2991
 2992
 2993
 2994
 2995
 2996
 2997
 2998
 2999
 3000
 3001
 3002
 3003
 3004
 3005
 3006
 3007
 3008
 3009
 3010
 3011
 3012
 3013
 3014
 3015
 3016
 3017
 3018
 3019
 3020
 3021
 3022
 3023
 3024
 3025
 3026
 3027
 3028
 3029
 3030
 3031
 3032
 3033
 3034
 3035
 3036
 3037
 3038
 3039
 3040
 3041
 3042
 3043
 3044
 3045
 3046
 3047
 3048
 3049
 3050
 3051
 3052
 3053
 3054
 3055
 3056
 3057
 3058
 3059
 3060
 3061
 3062
 3063
 3064
 3065
 3066
 3067
 3068
 3069
 3070
 3071
 3072
 3073
 3074
 3075
 3076
 3077
 3078
 3079
 3080
 3081
 3082
 3083
 3084
 3085
 3086
 3087
 3088
 3089
 3090
 3091
 3092
 3093
 3094
 3095
 3096
 3097
 3098
 3099
 3100
 3101
 3102
 3103
 3104
 3105
 3106
 3107
 3108
 3109
 3110
 3111
 3112
 3113
 3114
 3115
 3116
 3117
 3118
 3119
 3120
 3121
 3122
 3123
 3124
 3125
 3126
 3127
 3128
 3129
 3130
 3131
 3132
 3133
 3134
 3135
 3136
 3137
 3138
 3139
 3140
 3141
 3142
 3143
 3144
 3145
 3146
 3147
 3148
 3149
 3150
 3151
 3152
 3153
 3154
 3155
 3156
 3157
 3158
 3159
 3160
 3161
 3162
 3163
 3164
 3165
 3166
 3167
 3168
 3169
 3170
 3171
 3172
 3173
 3174
 3175
 3176
 3177
 3178
 3179
 3180
 3181
 3182
 3183
 3184
 3185
 3186
 3187
 3188
 3189
 3190
 3191
 3192
 3193
 3194
 3195
 3196
 3197
 3198
 3199
 3200
 3201
 3202
 3203
 3204
 3205
 3206
 3207
 3208
 3209
 3210
 3211
 3212
 3213
 3214
 3215
 3216
 3217
 3218
 3219
 3220
 3221
 3222
 3223
 3224
 3225
 3226
 3227
 3228
 3229
 3230
 3231
 3232
 3233
 3234
 3235
 3236
 3237
 3238
 3239
 3240
 3241
 3242
 3243
 3244
 3245
 3246
 3247
 3248
 3249
 3250
 3251
 3252
 3253
 3254
 3255
 3256
 3257
 3258
 3259
 3260
 3261
 3262
 3263
 3264
 3265
 3266
 3267
 3268
 3269
 3270
 3271
 3272
 3273
 3274
 3275
 3276
 3277
 3278
 3279
 3280
 3281
 3282
 3283
 3284
 3285
 3286
 3287
 3288
 3289
 3290
 3291
 3292
 3293
 3294
 3295
 3296
 3297
 3298
 3299
 3300
 3301
 3302
 3303
 3304
 3305
 3306
 3307
 3308
 3309
 3310
 3311
 3312
 3313
 3314
 3315
 3316
 3317
 3318
 3319
 3320
 3321
 3322
 3323
 3324
 3325
 3326
 3327
 3328
 3329
 3330
 3331
 3332
 3333
 3334
 3335
 3336
 3337
 3338
 3339
 3340
 3341
 3342
 3343
 3344
 3345
 3346
 3347
 3348
 3349
 3350
 3351
 3352
 3353
 3354
 3355
 3356
 3357
 3358
 3359
 3360
 3361
 3362
 3363
 3364
 3365
 3366
 3367
 3368
 3369
 3370
 3371
 3372
 3373
 3374
 3375
 3376
 3377
 3378
 3379
 3380
 3381
 3382
 3383
 3384
 3385
 3386
 3387
 3388
 3389
 3390
 3391
 3392
 3393
 3394
 3395
 3396
 3397
 3398
 3399
 3400
 3401
 3402
 3403
 3404
 3405
 3406
 3407
 3408
 3409
 3410
 3411
 3412
 3413
 3414
 3415
 3416
 3417
 3418
 3419
 3420
 3421
 3422
 3423
 3424
 3425
 3426
 3427
 3428
 3429
 3430
 3431
 3432
 3433
 3434
 3435
 3436
 3437
 3438
 3439
 3440
 3441
 3442
 3443
 3444
 3445
 3446
 3447
 3448
 3449
 3450
 3451
 3452
 3453
 3454
 3455
 3456
 3457
 3458
 3459
 3460
 3461
 3462
 3463
 3464
 3465
 3466
 3467
 3468
 3469
 3470
 3471
 3472
 3473
 3474
 3475
 3476
 3477
 3478
 3479
 3480
 3481
 3482
 3483
 3484
 3485
 3486
 3487
 3488
 3489
 3490
 3491
 3492
 3493
 3494
 3495
 3496
 3497
 3498
 3499
 3500
 3501
 3502
 3503
 3504
 3505
 3506
 3507
 3508
 3509
 3510
 3511
 3512
 3513
 3514
 3515
 3516
 3517
 3518
 3519
 3520
 3521
 3522
 3523
 3524
 3525
 3526
 3527
 3528
 3529
 3530
 3531
 3532
 3533
 3534
 3535
 3536
 3537
 3538
 3539
 3540
 3541
 3542
 3543
 3544
 3545
 3546
 3547
 3548
 3549
 3550
 3551
 3552
 3553
 3554
 3555
 3556
 3557
 3558
 3559
 3560
 3561
 3562
 3563
 3564
 3565
 3566
 3567
 3568
 3569
 3570
 3571
 3572
 3573
 3574
 3575
 3576
 3577
 3578
 3579
 3580
 3581
 3582
 3583
 3584
 3585
 3586
 3587
 3588
 3589
 3590
 3591
 3592
 3593
 3594
 3595
 3596
 3597
 3598
 3599
 3600
 3601
 3602
 3603
 3604
 3605
 3606
 3607
 3608
 3609
 3610
 3611
 3612
 3613
 3614
 3615
 3616
 3617
 3618
 3619
 3620
 3621
 3622
 3623
 3624
 3625
 3626
 3627
 3628
 3629
 3630
 3631
 3632
 3633
 3634
 3635
 3636
 3637
 3638
 3639
 3640
 3641
 3642
 3643
 3644
 3645
 3646
 3647
 3648
 3649
 3650
 3651
 3652
 3653
 3654
 3655
 3656
 3657
 3658
 3659
 3660
 3661
 3662
 3663
 3664
 3665
 3666
 3667
 3668
 3669
 3670
 3671
 3672
 3673
 3674
 3675
 3676
 3677
 3678
 3679
 3680
 3681
 3682
 3683
 3684
 3685
 3686
 3687
 3688
 3689
 3690
 3691
 3692
 3693
 3694
 3695
 3696
 3697
 3698
 3699
 3700
 3701
 3702
 3703
 3704
 3705
 3706
 3707
 3708
 3709
 3710
 3711
 3712
 3713
 3714
 3715
 3716
 3717
 3718
 3719
 3720
 3721
 3722
 3723
 3724
 3725
 3726
 3727
 3728
 3729
 3730
 3731
 3732
 3733
 3734
 3735
 3736
 3737
 3738
 3739
 3740
 3741
 3742
 3743
 3744
 3745
 3746
 3747
 3748
 3749
 3750
 3751
 3752
 3753
 3754
 3755
 3756
 3757
 3758
 3759
 3760
 3761
 3762
 3763
 3764
 3765
 3766
 3767
 3768
 3769
 3770
 3771
 3772
 3773
 3774
 3775
 3776
 3777
 3778
 3779
 3780
 3781
 3782
 3783
 3784
 3785
 3786
 3787
 3788
 3789
 3790
 3791
 3792
 3793
 3794
 3795
 3796
 3797
 3798
 3799
 3800
 3801
 3802
 3803
 3804
 3805
 3806
 3807
 3808
 3809
 3810
 3811
 3812
 3813
 3814
 3815
 3816
 3817
 3818
 3819
 3820
 3821
 3822
 3823
 3824
 3825
 3826
 3827
 3828
 3829
 3830
 3831
 3832
 3833
 3834
 3835
 3836
 3837
 3838
 3839
 3840
 3841
 3842
 3843
 3844
 3845
 3846
 3847
 3848
 3849
 3850
 3851
 3852
 3853
 3854
 3855
 3856
 3857
 3858
 3859
 3860
 3861
 3862
 3863
 3864
 3865
 3866
 3867
 3868
 3869
 3870
 3871
 3872
 3873
 3874
 3875
 3876
 3877
 3878
 3879
 3880
 3881
 3882
 3883
 3884
 3885
 3886
 3887
 3888
 3889
 3890
 3891
 3892
 3893
 3894
 3895
 3896
 3897
 3898
 3899
 3900
 3901
 3902
 3903
 3904
 3905
 3906
 3907
 3908
 3909
 3910
 3911
 3912
 3913
 3914
 3915
 3916
 3917
 3918
 3919
 3920
 3921
 3922
 3923
 3924
 3925
 3926
 3927
 3928
 3929
 3930
 3931
 3932
 3933
 3934
 3935
 3936
 3937
 3938
 3939
 3940
 3941
 3942
 3943
 3944
 3945
 3946
 3947
 3948
 3949
 3950
 3951
 3952
 3953
 3954
 3955
 3956
 3957
 3958
 3959
 3960
 3961
 3962
 3963
 3964
 3965
 3966
 3967
 3968
 3969
 3970
 3971
 3972
 3973
 3974
 3975
 3976
 3977
 3978
 3979
 3980
 3981
 3982
 3983
 3984
 3985
 3986
 3987
 3988
 3989
 3990
 3991
 3992
 3993
 3994
 3995
 3996
 3997
 3998
 3999
 4000
 4001
 4002
 4003
 4004
 4005
 4006
 4007
 4008
 4009
 4010
 4011
 4012
 4013
 4014
 4015
 4016
 4017
 4018
 4019
 4020
 4021
 4022
 4023
 4024
 4025
 4026
 4027
 4028
 4029
 4030
 4031
 4032
 4033
 4034
 4035
 4036
 4037
 4038
 4039
 4040
 4041
 4042
 4043
 4044
 4045
 4046
 4047
 4048
 4049
 4050
 4051
 4052
 4053
 4054
 4055
 4056
 4057
 4058
 4059
 4060
 4061
 4062
 4063
 4064
 4065
 4066
 4067
 4068
 4069
 4070
 4071
 4072
 4073
 4074
 4075
 4076
 4077
 4078
 4079
 4080
 4081
 4082
 4083
 4084
 4085
 4086
 4087
 4088
 4089
 4090
 4091
 4092
 4093
 4094
 4095
 4096
 4097
 4098
 4099
 4100
 4101
 4102
 4103
 4104
 4105
 4106
 4107
 4108
 4109
 4110
 4111
 4112
 4113
 4114
 4115
 4116
 4117
 4118
 4119
 4120
 4121
 4122
 4123
 4124
 4125
 4126
 4127
 4128
 4129
 4130
 4131
 4132
 4133
 4134
 4135
 4136
 4137
 4138
 4139
 4140
 4141
 4142
 4143
 4144
 4145
 4146
 4147
 4148
 4149
 4150
 4151
 4152
 4153
 4154
 4155
 4156
 4157
 4158
 4159
 4160
 4161
 4162
 4163
 4164
 4165
 4166
 4167
 4168
 4169
 4170
 4171
 4172
 4173
 4174
 4175
 4176
 4177
 4178
 4179
 4180
 4181
 4182
 4183
 4184
 4185
 4186
 4187
 4188
 4189
 4190
 4191
 4192
 4193
 4194
 4195
 4196
 4197
 4198
 4199
 4200
 4201
 4202
 4203
 4204
 4205
 4206
 4207
 4208
 4209
 4210
 4211
 4212
 4213
 4214
 4215
 4216
 4217
 4218
 4219
 4220
 4221
 4222
 4223
 4224
 4225
 4226
 4227
 4228
 4229
 4230
 4231
 4232
 4233
 4234
 4235
 4236
 4237
 4238
 4239
 4240
 4241
 4242
 4243
 4244
 4245
 4246
 4247
 4248
 4249
 4250
 4251
 4252
 4253
 4254
 4255
 4256
 4257
 4258
 4259
 4260
 4261
 4262
 4263
 4264
 4265
 4266
 4267
 4268
 4269
 4270
 4271
 4272
 4273
 4274
 4275
 4276
 4277
 4278
 4279
 4280
 4281
 4282
 4283
 4284
 4285
 4286
 4287
 4288
 4289
 4290
 4291
 4292
 4293
 4294
 4295
 4296
 4297
 4298
 4299
 4300
 4301
 4302
 4303
 4304
 4305
 4306
 4307
 4308
 4309
 4310
 4311
 4312
 4313
 4314
 4315
 4316
 4317
 4318
 4319
 4320
 4321
 4322
 4323
 4324
 4325
 4326
 4327
 4328
 4329
 4330
 4331
 4332
 4333
 4334
 4335
 4336
 4337
 4338
 4339
 4340
 4341
 4342
 4343
 4344
 4345
 4346
 4347
 4348
 4349
 4350
 4351
 4352
 4353
 4354
 4355
 4356
 4357
 4358
 4359
 4360
 4361
 4362
 4363
 4364
 4365
 4366
 4367
 4368
 4369
 4370
 4371
 4372
 4373
 4374
 4375
 4376
 4377
 4378
 4379
 4380
 4381
 4382
 4383
 4384
 4385
 4386
 4387
 4388
 4389
 4390
 4391
 4392
 4393
 4394
 4395
 4396
 4397
 4398
 4399
 4400
 4401
 4402
 4403
 4404
 4405
 4406
 4407
 4408
 4409
 4410
 4411
 4412
 4413
 4414
 4415
 4416
 4417
 4418
 4419
 4420
 4421
 4422
 4423
 4424
 4425
 4426
 4427
 4428
 4429
 4430
 4431
 4432
 4433
 4434
 4435
 4436
 4437
 4438
 4439
 4440
 4441
 4442
 4443
 4444
 4445
 4446
 4447
 4448
 4449
 4450
 4451
 4452
 4453
 4454
 4455
 4456
 4457
 4458
 4459
 4460
 4461
 4462
 4463
 4464
 4465
 4466
 4467
 4468
 4469
 4470
 4471
 4472
 4473
 4474
 4475
 4476
 4477
 4478
 4479
 4480
 4481
 4482
 4483
 4484
 4485
 4486
 4487
 4488
 4489
 4490
 4491
 4492
 4493
 4494
 4495
 4496
 4497
 4498
 4499
 4500
 4501
 4502
 4503
 4504
 4505
 4506
 4507
 4508
 4509
 4510
 4511
 4512
 4513
 4514
 4515
 4516
 4517
 4518
 4519
 4520
 4521
 4522
 4523
 4524
 4525
 4526
 4527
 4528
 4529
 4530
 4531
 4532
 4533
 4534
 4535
 4536
 4537
 4538
 4539
 4540
 4541
 4542
 4543
 4544
 4545
 4546
 4547
 4548
 4549
 4550
 4551
 4552
 4553
 4554
 4555
 4556
 4557
 4558
 4559
 4560
 4561
 4562
 4563
 4564
 4565
 4566
 4567
 4568
 4569
 4570
 4571
 4572
 4573
 4574
 4575
 4576
 4577
 4578
 4579
 4580
 4581
 4582
 4583
 4584
 4585
 4586
 4587
 4588
 4589
 4590
 4591
 4592
 4593
 4594
 4595
 4596
 4597
 4598
 4599
 4600
 4601
 4602
 4603
 4604
 4605
 4606
 4607
 4608
 4609
 4610
 4611
 4612
 4613
 4614
 4615
 4616
 4617
 4618
 4619
 4620
 4621
 4622
 4623
 4624
 4625
 4626
 4627
 4628
 4629
 4630
 4631
 4632
 4633
 4634
 4635
 4636
 4637
 4638
 4639
 4640
 4641
 4642
 4643
 4644
 4645
 4646
 4647
 4648
 4649
 4650
 4651
 4652
 4653
 4654
 4655
 4656
 4657
 4658
 4659
 4660
 4661
 4662
 4663
 4664
 4665
 4666
 4667
 4668
 4669
 4670
 4671
 4672
 4673
 4674
 4675
 4676
 4677
 4678
 4679
 4680
 4681
 4682
 4683
 4684
 4685
 4686
 4687
 4688
 4689
 4690
 4691
 4692
 4693
 4694
 4695
 4696
 4697
 4698
 4699
 4700
 4701
 4702
 4703
 4704
 4705
 4706
 4707
 4708
 4709
 4710
 4711
 4712
 4713
 4714
 4715
 4716
 4717
 4718
 4719
 4720
 4721
 4722
 4723
 4724
 4725
 4726
 4727
 4728
 4729
 4730
 4731
 4732
 4733
 4734
 4735
 4736
 4737
 4738
 4739
 4740
 4741
 4742
 4743
 4744
 4745
 4746
 4747
 4748
 4749
 4750
 4751
 4752
 4753
 4754
 4755
 4756
 4757
 4758
 4759
 4760
 4761
 4762
 4763
 4764
 4765
 4766
 4767
 4768
 4769
 4770
 4771
 4772
 4773
 4774
 4775
 4776
 4777
 4778
 4779
 4780
 4781
 4782
 4783
 4784
 4785
 4786
 4787
 4788
 4789
 4790
 4791
 4792
 4793
 4794
 4795
 4796
 4797
 4798
 4799
 4800
 4801
 4802
 4803
 4804
 4805
 4806
 4807
 4808
 4809
 4810
 4811
 4812
 4813
 4814
 4815
 4816
 4817
 4818
 4819
 4820
 4821
 4822
 4823
 4824
 4825
 4826
 4827
 4828
 4829
 4830
 4831
 4832
 4833
 4834
 4835
 4836
 4837
 4838
 4839
 4840
 4841
 4842
 4843
 4844
 4845
 4846
 4847
 4848
 4849
 4850
 4851
 4852
 4853
 4854
 4855
 4856
 4857
 4858
 4859
 4860
 4861
 4862
 4863
 4864
 4865
 4866
 4867
 4868
 4869
 4870
 4871
 4872
 4873
 4874
 4875
 4876
 4877
 4878
 4879
 4880
 4881
 4882
 4883
 4884
 4885
 4886
 4887
 4888
 4889
 4890
 4891
 4892
 4893
 4894
 4895
 4896
 4897
 4898
 4899
 4900
 4901
 4902
 4903
 4904
 4905
 4906
 4907
 4908
 4909
 4910
 4911
 4912
 4913
 4914
 4915
 4916
 4917
 4918
 4919
 4920
 4921
 4922
 4923
 4924
 4925
 4926
 4927
 4928
 4929
 4930
 4931
 4932
 4933
 4934
 4935
 4936
 4937
 4938
 4939
 4940
 4941
 4942
 4943
 4944
 4945
 4946
 4947
 4948
 4949
 4950
 4951
 4952
 4953
 4954
 4955
 4956
 4957
 4958
 4959
 4960
 4961
 4962
 4963
 4964
 4965
 4966
 4967
 4968
 4969
 4970
 4971
 4972
 4973
 4974
 4975
 4976
 4977
 4978
 4979
 4980
 4981
 4982
 4983
 4984
 4985
 4986
 4987
 4988
 4989
 4990
 4991
 4992
 4993
 4994
 4995
 4996
 4997
 4998
 4999
 5000
 5001
 5002
 5003
 5004
 5005
 5006
 5007
 5008
 5009
 5010
 5011
 5012
 5013
 5014
 5015
 5016
 5017
 5018
 5019
 5020
 5021
 5022
 5023
 5024
 5025
 5026
 5027
 5028
 5029
 5030
 5031
 5032
 5033
 5034
 5035
 5036
 5037
 5038
 5039
 5040
 5041
 5042
 5043
 5044
 5045
 5046
 5047
 5048
 5049
 5050
 5051
 5052
 5053
 5054
 5055
 5056
 5057
 5058
 5059
 5060
 5061
 5062
 5063
 5064
 5065
 5066
 5067
 5068
 5069
 5070
 5071
 5072
 5073
 5074
 5075
 5076
 5077
 5078
 5079
 5080
 5081
 5082
 5083
 5084
 5085
 5086
 5087
 5088
 5089
 5090
 5091
 5092
 5093
 5094
 5095
 5096
 5097
 5098
 5099
 5100
 5101
 5102
 5103
 5104
 5105
 5106
 5107
 5108
 5109
 5110
 5111
 5112
 5113
 5114
 5115
 5116
 5117
 5118
 5119
 5120
 5121
 5122
 5123
 5124
 5125
 5126
 5127
 5128
 5129
 5130
 5131
 5132
 5133
 5134
 5135
 5136
 5137
 5138
 5139
 5140
 5141
 5142
 5143
 5144
 5145
 5146
 5147
 5148
 5149
 5150
 5151
 5152
 5153
 5154
 5155
 5156
 5157
 5158
 5159
 5160
 5161
 5162
 5163
 5164
 5165
 5166
 5167
 5168
 5169
 5170
 5171
 5172
 5173
 5174
 5175
 5176
 5177
 5178
 5179
 5180
 5181
 5182
 5183
 5184
 5185
 5186
 5187
 5188
 5189
 5190
 5191
 5192
 5193
 5194
 5195
 5196
 5197
 5198
 5199
 5200
 5201
 5202
 5203
 5204
 5205
 5206
 5207
 5208
 5209
 5210
 5211
 5212
 5213
 5214
 5215
 5216
 5217
 5218
 5219
 5220
 5221
 5222
 5223
 5224
 5225
 5226
 5227
 5228
 5229
 5230
 5231
 5232
 5233
 5234
 5235
 5236
 5237
 5238
 5239
 5240
 5241
 5242
 5243
 5244
 5245
 5246
 5247
 5248
 5249
 5250
 5251
 5252
 5253
 5254
 5255
 5256
 5257
 5258
 5259
 5260
 5261
 5262
 5263
 5264
 5265
 5266
 5267
 5268
 5269
 5270
 5271
 5272
 5273
 5274
 5275
 5276
 5277
 5278
 5279
 5280
 5281
 5282
 5283
 5284
 5285
 5286
 5287
 5288
 5289
 5290
 5291
 5292
 5293
 5294
 5295
 5296
 5297
 5298
 5299
 5300
 5301
 5302
 5303
 5304
 5305
 5306
 5307
 5308
 5309
 5310
 5311
 5312
 5313
 5314
 5315
 5316
 5317
 5318
 5319
 5320
 5321
 5322
 5323
 5324
 5325
 5326
 5327
 5328
 5329
 5330
 5331
 5332
 5333
 5334
 5335
 5336
 5337
 5338
 5339
 5340
 5341
 5342
 5343
 5344
 5345
 5346
 5347
 5348
 5349
 5350
 5351
 5352
 5353
 5354
 5355
 5356
 5357
 5358
 5359
 5360
 5361
 5362
 5363
 5364
 5365
 5366
 5367
 5368
 5369
 5370
 5371
 5372
 5373
 5374
 5375
 5376
 5377
 5378
 5379
 5380
 5381
 5382
 5383
 5384
 5385
 5386
 5387
 5388
 5389
 5390
 5391
 5392
 5393
 5394
 5395
 5396
 5397
 5398
 5399
 5400
 5401
 5402
 5403
 5404
 5405
 5406
 5407
 5408
 5409
 5410
 5411
 5412
 5413
 5414
 5415
 5416
 5417
 5418
 5419
 5420
 5421
 5422
 5423
 5424
 5425
 5426
 5427
 5428
 5429
 5430
 5431
 5432
 5433
 5434
 5435
 5436
 5437
 5438
 5439
 5440
 5441
 5442
 5443
 5444
 5445
 5446
 5447
 5448
 5449
 5450
 5451
 5452
 5453
 5454
 5455
 5456
 5457
 5458
 5459
 5460
 5461
 5462
 5463
 5464
 5465
 5466
 5467
 5468
 5469
 5470
 5471
 5472
 5473
 5474
 5475
 5476
 5477
 5478
 5479
 5480
 5481
 5482
 5483
 5484
 5485
 5486
 5487
 5488
 5489
 5490
 5491
 5492
 5493
 5494
 5495
 5496
 5497
 5498
 5499
 5500
 5501
 5502
 5503
 5504
 5505
 5506
 5507
 5508
 5509
 5510
 5511
 5512
 5513
 5514
 5515
 5516
 5517
 5518
 5519
 5520
 5521
 5522
 5523
 5524
 5525
 5526
 5527
 5528
 5529
 5530
 5531
 5532
 5533
 5534
 5535
 5536
 5537
 5538
 5539
 5540
 5541
 5542
 5543
 5544
 5545
 5546
 5547
 5548
 5549
 5550
 5551
 5552
 5553
 5554
 5555
 5556
 5557
 5558
 5559
 5560
 5561
 5562
 5563
 5564
 5565
 5566
 5567
 5568
 5569
 5570
 5571
 5572
 5573
 5574
 5575
 5576
 5577
 5578
 5579
 5580
 5581
 5582
 5583
 5584
 5585
 5586
 5587
 5588
 5589
 5590
 5591
 5592
 5593
 5594
 5595
 5596
 5597
 5598
 5599
 5600
 5601
 5602
 5603
 5604
 5605
 5606
 5607
 5608
 5609
 5610
 5611
 5612
 5613
 5614
 5615
 5616
 5617
 5618
 5619
 5620
 5621
 5622
 5623
 5624
 5625
 5626
 5627
 5628
 5629
 5630
 5631
 5632
 5633
 5634
 5635
 5636
 5637
 5638
 5639
 5640
 5641
 5642
 5643
 5644
 5645
 5646
 5647
 5648
 5649
 5650
 5651
 5652
 5653
 5654
 5655
 5656
 5657
 5658
 5659
 5660
 5661
 5662
 5663
 5664
 5665
 5666
 5667
 5668
 5669
 5670
 5671
 5672
 5673
 5674
 5675
 5676
 5677
 5678
 5679
 5680
 5681
 5682
 5683
 5684
 5685
 5686
 5687
 5688
 5689
 5690
 5691
 5692
 5693
 5694
 5695
 5696
 5697
 5698
 5699
 5700
 5701
 5702
 5703
 5704
 5705
 5706
 5707
 5708
 5709
 5710
 5711
 5712
 5713
 5714
 5715
 5716
 5717
 5718
 5719
 5720
 5721
 5722
 5723
 5724
 5725
 5726
 5727
 5728
 5729
 5730
 5731
 5732
 5733
 5734
 5735
 5736
 5737
 5738
 5739
 5740
 5741
 5742
 5743
 5744
 5745
 5746
 5747
 5748
 5749
 5750
 5751
 5752
 5753
 5754
 5755
 5756
 5757
 5758
 5759
 5760
 5761
 5762
 5763
 5764
 5765
 5766
 5767
 5768
 5769
 5770
 5771
 5772
 5773
 5774
 5775
 5776
 5777
 5778
 5779
 5780
 5781
 5782
 5783
 5784
 5785
 5786
 5787
 5788
 5789
 5790
 5791
 5792
 5793
 5794
 5795
 5796
 5797
 5798
 5799
 5800
 5801
 5802
 5803
 5804
 5805
 5806
 5807
 5808
 5809
 5810
 5811
 5812
 5813
 5814
 5815
 5816
 5817
 5818
 5819
 5820
 5821
 5822
 5823
 5824
 5825
 5826
 5827
 5828
 5829
 5830
 5831
 5832
 5833
 5834
 5835
 5836
 5837
 5838
 5839
 5840
 5841
 5842
 5843
 5844
 5845
 5846
 5847
 5848
 5849
 5850
 5851
 5852
 5853
 5854
 5855
 5856
 5857
 5858
 5859
 5860
 5861
 5862
 5863
 5864
 5865
 5866
 5867
 5868
 5869
 5870
 5871
 5872
 5873
 5874
 5875
 5876
 5877
 5878
 5879
 5880
 5881
 5882
 5883
 5884
 5885
 5886
 5887
 5888
 5889
 5890
 5891
 5892
 5893
 5894
 5895
 5896
 5897
 5898
 5899
 5900
 5901
 5902
 5903
 5904
 5905
 5906
 5907
 5908
 5909
 5910
 5911
 5912
 5913
 5914
 5915
 5916
 5917
 5918
 5919
 5920
 5921
 5922
 5923
 5924
 5925
 5926
 5927
 5928
 5929
 5930
 5931
 5932
 5933
 5934
 5935
 5936
 5937
 5938
 5939
 5940
 5941
 5942
 5943
 5944
 5945
 5946
 5947
 5948
 5949
 5950
 5951
 5952
 5953
 5954
 5955
 5956
 5957
 5958
 5959
 5960
 5961
 5962
 5963
 5964
 5965
 5966
 5967
 5968
 5969
 5970
 5971
 5972
 5973
 5974
 5975
 5976
 5977
 5978
 5979
 5980
 5981
 5982
 5983
 5984
 5985
 5986
 5987
 5988
 5989
 5990
 5991
 5992
 5993
 5994
 5995
 5996
 5997
 5998
 5999
 6000
 6001
 6002
 6003
 6004
 6005
 6006
 6007
 6008
 6009
 6010
 6011
 6012
 6013
 6014
 6015
 6016
 6017
 6018
 6019
 6020
 6021
 6022
 6023
 6024
 6025
 6026
 6027
 6028
 6029
 6030
 6031
 6032
 6033
 6034
 6035
 6036
 6037
 6038
 6039
 6040
 6041
 6042
 6043
 6044
 6045
 6046
 6047
 6048
 6049
 6050
 6051
 6052
 6053
 6054
 6055
 6056
 6057
 6058
 6059
 6060
 6061
 6062
 6063
 6064
 6065
 6066
 6067
 6068
 6069
 6070
 6071
 6072
 6073
 6074
 6075
 6076
 6077
 6078
 6079
 6080
 6081
 6082
 6083
 6084
 6085
 6086
 6087
 6088
 6089
 6090
 6091
 6092
 6093
 6094
 6095
 6096
 6097
 6098
 6099
 6100
 6101
 6102
 6103
 6104
 6105
 6106
 6107
 6108
 6109
 6110
 6111
 6112
 6113
 6114
 6115
 6116
 6117
 6118
 6119
 6120
 6121
 6122
 6123
 6124
 6125
 6126
 6127
 6128
 6129
 6130
 6131
 6132
 6133
 6134
 6135
 6136
 6137
 6138
 6139
 6140
 6141
 6142
 6143
 6144
 6145
 6146
 6147
 6148
 6149
 6150
 6151
 6152
 6153
 6154
 6155
 6156
 6157
 6158
 6159
 6160
 6161
 6162
 6163
 6164
 6165
 6166
 6167
 6168
 6169
 6170
 6171
 6172
 6173
 6174
 6175
 6176
 6177
 6178
 6179
 6180
 6181
 6182
 6183
 6184
 6185
 6186
 6187
 6188
 6189
 6190
 6191
 6192
 6193
 6194
 6195
 6196
 6197
 6198
 6199
 6200
 6201
 6202
 6203
 6204
 6205
 6206
 6207
 6208
 6209
 6210
 6211
 6212
 6213
 6214
 6215
 6216
 6217
 6218
 6219
 6220
 6221
 6222
 6223
 6224
 6225
 6226
 6227
 6228
 6229
 6230
 6231
 6232
 6233
 6234
 6235
 6236
 6237
 6238
 6239
 6240
 6241
 6242
 6243
 6244
 6245
 6246
 6247
 6248
 6249
 6250
 6251
 6252
 6253
 6254
 6255
 6256
 6257
 6258
 6259
 6260
 6261
 6262
 6263
 6264
 6265
 6266
 6267
 6268
 6269
 6270
 6271
 6272
 6273
 6274
 6275
 6276
 6277
 6278
 6279
 6280
 6281
 6282
 6283
 6284
 6285
 6286
 6287
 6288
 6289
 6290
 6291
 6292
 6293
 6294
 6295
 6296
 6297
 6298
 6299
 6300
 6301
 6302
 6303
 6304
 6305
 6306
 6307
 6308
 6309
 6310
 6311
 6312
 6313
 6314
 6315
 6316
 6317
 6318
 6319
 6320
 6321
 6322
 6323
 6324
 6325
 6326
 6327
 6328
 6329
 6330
 6331
 6332
 6333
 6334
 6335
 6336
 6337
 6338
 6339
 6340
 6341
 6342
 6343
 6344
 6345
 6346
 6347
 6348
 6349
 6350
 6351
 6352
 6353
 6354
 6355
 6356
 6357
 6358
 6359
 6360
 6361
 6362
 6363
 6364
 6365
 6366
 6367
 6368
 6369
 6370
 6371
 6372
 6373
 6374
 6375
 6376
 6377
 6378
 6379
 6380
 6381
 6382
 6383
 6384
 6385
 6386
 6387
 6388
 6389
 6390
 6391
 6392
 6393
 6394
 6395
 6396
 6397
 6398
 6399
 6400
 6401
 6402
 6403
 6404
 6405
 6406
 6407
 6408
 6409
 6410
 6411
 6412
 6413
 6414
 6415
 6416
 6417
 6418
 6419
 6420
 6421
 6422
 6423
 6424
 6425
 6426
 6427
 6428
 6429
 6430
 6431
 6432
 6433
 6434
 6435
 6436
 6437
 6438
 6439
 6440
 6441
 6442
 6443
 6444
 6445
 6446
 6447
 6448
 6449
 6450
 6451
 6452
 6453
 6454
 6455
 6456
 6457
 6458
 6459
 6460
 6461
 6462
 6463
 6464
 6465
 6466
 6467
 6468
 6469
 6470
 6471
 6472
 6473
 6474
 6475
 6476
 6477
 6478
 6479
 6480
 6481
 6482
 6483
 6484
 6485
 6486
 6487
 6488
 6489
 6490
 6491
 6492
 6493
 6494
 6495
 6496
 6497
 6498
 6499
 6500
 6501
 6502
 6503
 6504
 6505
 6506
 6507
 6508
 6509
 6510
 6511
 6512
 6513
 6514
 6515
 6516
 6517
 6518
 6519
 6520
 6521
 6522
 6523
 6524
 6525
 6526
 6527
 6528
 6529
 6530
 6531
 6532
 6533
 6534
 6535
 6536
 6537
 6538
 6539
 6540
 6541
 6542
 6543
 6544
 6545
 6546
 6547
 6548
 6549
 6550
 6551
 6552
 6553
 6554
 6555
 6556
 6557
 6558
 6559
 6560
 6561
 6562
 6563
 6564
 6565
 6566
 6567
 6568
 6569
 6570
 6571
 6572
 6573
 6574
 6575
 6576
 6577
 6578
 6579
 6580
 6581
 6582
 6583
 6584
 6585
 6586
 6587
 6588
 6589
 6590
 6591
 6592
 6593
 6594
 6595
 6596
 6597
 6598
 6599
 6600
 6601
 6602
 6603
 6604
 6605
 6606
 6607
 6608
 6609
 6610
 6611
 6612
 6613
 6614
 6615
 6616
 6617
 6618
 6619
 6620
 6621
 6622
 6623
 6624
 6625
 6626
 6627
 6628
 6629
 6630
 6631
 6632
 6633
 6634
 6635
 6636
 6637
 6638
 6639
 6640
 6641
 6642
 6643
 6644
 6645
 6646
 6647
 6648
 6649
 6650
 6651
 6652
 6653
 6654
 6655
 6656
 6657
 6658
 6659
 6660
 6661
 6662
 6663
 6664
 6665
 6666
 6667
 6668
 6669
 6670
 6671
 6672
 6673
 6674
 6675
 6676
 6677
 6678
 6679
 6680
 6681
 6682
 6683
 6684
 6685
 6686
 6687
 6688
 6689
 6690
 6691
 6692
 6693
 6694
 6695
 6696
 6697
 6698
 6699
 6700
 6701
 6702
 6703
 6704
 6705
 6706
 6707
 6708
 6709
 6710
 6711
 6712
 6713
 6714
 6715
 6716
 6717
 6718
 6719
 6720
 6721
 6722
 6723
 6724
 6725
 6726
 6727
 6728
 6729
 6730
 6731
 6732
 6733
 6734
 6735
 6736
 6737
 6738
 6739
 6740
 6741
 6742
 6743
 6744
 6745
 6746
 6747
 6748
 6749
 6750
 6751
 6752
 6753
 6754
 6755
 6756
 6757
 6758
 6759
 6760
 6761
 6762
 6763
 6764
 6765
 6766
 6767
 6768
 6769
 6770
 6771
 6772
 6773
 6774
 6775
 6776
 6777
 6778
 6779
 6780
 6781
 6782
 6783
 6784
 6785
 6786
 6787
 6788
 6789
 6790
 6791
 6792
 6793
 6794
 6795
 6796
 6797
 6798
 6799
 6800
 6801
 6802
 6803
 6804
 6805
 6806
 6807
 6808
 6809
 6810
 6811
 6812
 6813
 6814
 6815
 6816
 6817
 6818
 6819
 6820
 6821
 6822
 6823
 6824
 6825
 6826
 6827
 6828
 6829
 6830
 6831
 6832
 6833
 6834
 6835
 6836
 6837
 6838
 6839
 6840
 6841
 6842
 6843
 6844
 6845
 6846
 6847
 6848
 6849
 6850
 6851
 6852
 6853
 6854
 6855
 6856
 6857
 6858
 6859
 6860
 6861
 6862
 6863
 6864
 6865
 6866
 6867
 6868
 6869
 6870
 6871
 6872
 6873
 6874
 6875
 6876
 6877
 6878
 6879
 6880
 6881
 6882
 6883
 6884
 6885
 6886
 6887
 6888
 6889
 6890
 6891
 6892
 6893
 6894
 6895
 6896
 6897
 6898
 6899
 6900
 6901
 6902
 6903
 6904
 6905
 6906
 6907
 6908
 6909
 6910
 6911
 6912
 6913
 6914
 6915
 6916
 6917
 6918
 6919
 6920
 6921
 6922
 6923
 6924
 6925
 6926
 6927
 6928
 6929
 6930
 6931
 6932
 6933
 6934
 6935
 6936
 6937
 6938
 6939
 6940
 6941
 6942
 6943
 6944
 6945
 6946
 6947
 6948
 6949
 6950
 6951
 6952
 6953
 6954
 6955
 6956
 6957
 6958
 6959
 6960
 6961
 6962
 6963
 6964
 6965
 6966
 6967
 6968
 6969
 6970
 6971
 6972
 6973
 6974
 6975
 6976
 6977
 6978
 6979
 6980
 6981
 6982
 6983
 6984
 6985
 6986
 6987
 6988
 6989
 6990
 6991
 6992
 6993
 6994
 6995
 6996
 6997
 6998
 6999
 7000
 7001
 7002
 7003
 7004
 7005
 7006
 7007
 7008
 7009
 7010
 7011
 7012
 7013
 7014
 7015
 7016
 7017
 7018
 7019
 7020
 7021
 7022
 7023
 7024
 7025
 7026
 7027
 7028
 7029
 7030
 7031
 7032
 7033
 7034
 7035
 7036
 7037
 7038
 7039
 7040
 7041
 7042
 7043
 7044
 7045
 7046
 7047
 7048
 7049
 7050
 7051
 7052
 7053
 7054
 7055
 7056
 7057
 7058
 7059
 7060
 7061
 7062
 7063
 7064
 7065
 7066
 7067
 7068
 7069
 7070
 7071
 7072
 7073
 7074
 7075
 7076
 7077
 7078
 7079
 7080
 7081
 7082
 7083
 7084
 7085
 7086
 7087
 7088
 7089
 7090
 7091
 7092
 7093
 7094
 7095
 7096
 7097
 7098
 7099
 7100
 7101
 7102
 7103
 7104
 7105
 7106
 7107
 7108
 7109
 7110
 7111
 7112
 7113
 7114
 7115
 7116
 7117
 7118
 7119
 7120
 7121
 7122
 7123
 7124
 7125
 7126
 7127
 7128
 7129
 7130
 7131
 7132
 7133
 7134
 7135
 7136
 7137
 7138
 7139
 7140
 7141
 7142
 7143
 7144
 7145
 7146
 7147
 7148
 7149
 7150
 7151
 7152
 7153
 7154
 7155
 7156
 7157
 7158
 7159
 7160
 7161
 7162
 7163
 7164
 7165
 7166
 7167
 7168
 7169
 7170
 7171
 7172
 7173
 7174
 7175
 7176
 7177
 7178
 7179
 7180
 7181
 7182
 7183
 7184
 7185
 7186
 7187
 7188
 7189
 7190
 7191
 7192
 7193
 7194
 7195
 7196
 7197
 7198
 7199
 7200
 7201
 7202
 7203
 7204
 7205
 7206
 7207
 7208
 7209
 7210
 7211
 7212
 7213
 7214
 7215
 7216
 7217
 7218
 7219
 7220
 7221
 7222
 7223
 7224
 7225
 7226
 7227
 7228
 7229
 7230
 7231
 7232
 7233
 7234
 7235
 7236
 7237
 7238
 7239
 7240
 7241
 7242
 7243
 7244
 7245
 7246
 7247
 7248
 7249
 7250
 7251
 7252
 7253
 7254
 7255
 7256
 7257
 7258
 7259
 7260
 7261
 7262
 7263
 7264
 7265
 7266
 7267
 7268
 7269
 7270
 7271
 7272
 7273
 7274
 7275
 7276
 7277
 7278
 7279
 7280
 7281
 7282
 7283
 7284
 7285
 7286
 7287
 7288
 7289
 7290
 7291
 7292
 7293
 7294
 7295
 7296
 7297
 7298
 7299
 7300
 7301
 7302
 7303
 7304
 7305
 7306
 7307
 7308
 7309
 7310
 7311
 7312
 7313
 7314
 7315
 7316
 7317
 7318
 7319
 7320
 7321
 7322
 7323
 7324
 7325
 7326
 7327
 7328
 7329
 7330
 7331
 7332
 7333
 7334
 7335
 7336
 7337
 7338
 7339
 7340
 7341
 7342
 7343
 7344
 7345
 7346
 7347
 7348
 7349
 7350
 7351
 7352
 7353
 7354
 7355
 7356
 7357
 7358
 7359
 7360
 7361
 7362
 7363
 7364
 7365
 7366
 7367
 7368
 7369
 7370
 7371
 7372
 7373
 7374
 7375
 7376
 7377
 7378
 7379
 7380
 7381
 7382
 7383
 7384
 7385
 7386
 7387
 7388
 7389
 7390
 7391
 7392
 7393
 7394
 7395
 7396
 7397
 7398
 7399
 7400
 7401
 7402
 7403
 7404
 7405
 7406
 7407
 7408
 7409
 7410
 7411
 7412
 7413
 7414
 7415
 7416
 7417
 7418
 7419
 7420
 7421
 7422
 7423
 7424
 7425
 7426
 7427
 7428
 7429
 7430
 7431
 7432
 7433
 7434
 7435
 7436
 7437
 7438
 7439
 7440
 7441
 7442
 7443
 7444
 7445
 7446
 7447
 7448
 7449
 7450
 7451
 7452
 7453
 7454
 7455
 7456
 7457
 7458
 7459
 7460
 7461
 7462
 7463
 7464
 7465
 7466
 7467
 7468
 7469
 7470
 7471
 7472
 7473
 7474
 7475
 7476
 7477
 7478
 7479
 7480
 7481
 7482
 7483
 7484
 7485
 7486
 7487
 7488
 7489
 7490
 7491
 7492
 7493
 7494
 7495
 7496
 7497
 7498
 7499
 7500
 7501
 7502
 7503
 7504
 7505
 7506
 7507
 7508
 7509
 7510
 7511
 7512
 7513
 7514
 7515
 7516
 7517
 7518
 7519
 7520
 7521
 7522
 7523
 7524
 7525
 7526
 7527
 7528
 7529
 7530
 7531
 7532
 7533
 7534
 7535
 7536
 7537
 7538
 7539
 7540
 7541
 7542
 7543
 7544
 7545
 7546
 7547
 7548
 7549
 7550
 7551
 7552
 7553
 7554
 7555
 7556
 7557
 7558
 7559
 7560
 7561
 7562
 7563
 7564
 7565
 7566
 7567
 7568
 7569
 7570
 7571
 7572
 7573
 7574
 7575
 7576
 7577
 7578
 7579
 7580
 7581
 7582
 7583
 7584
 7585
 7586
 7587
 7588
 7589
 7590
 7591
 7592
 7593
 7594
 7595
 7596
 7597
 7598
 7599
 7600
 7601
 7602
 7603
 7604
 7605
 7606
 7607
 7608
 7609
 7610
 7611
 7612
 7613
 7614
 7615
 7616
 7617
 7618
 7619
 7620
 7621
 7622
 7623
 7624
 7625
 7626
 7627
 7628
 7629
 7630
 7631
 7632
 7633
 7634
 7635
 7636
 7637
 7638
 7639
 7640
 7641
 7642
 7643
 7644
 7645
 7646
 7647
 7648
 7649
 7650
 7651
 7652
 7653
 7654
 7655
 7656
 7657
 7658
 7659
 7660
 7661
 7662
 7663
 7664
 7665
 7666
 7667
 7668
 7669
 7670
 7671
 7672
 7673
 7674
 7675
 7676
 7677
 7678
 7679
 7680
 7681
 7682
 7683
 7684
 7685
 7686
 7687
 7688
 7689
 7690
 7691
 7692
 7693
 7694
 7695
 7696
 7697
 7698
 7699
 7700
 7701
 7702
 7703
 7704
 7705
 7706
 7707
 7708
 7709
 7710
 7711
 7712
 7713
 7714
 7715
 7716
 7717
 7718
 7719
 7720
 7721
 7722
 7723
 7724
 7725
 7726
 7727
 7728
 7729
 7730
 7731
 7732
 7733
 7734
 7735
 7736
 7737
 7738
 7739
 7740
 7741
 7742
 7743
 7744
 7745
 7746
 7747
 7748
 7749
 7750
 7751
 7752
 7753
 7754
 7755
 7756
 7757
 7758
 7759
 7760
 7761
 7762
 7763
 7764
 7765
 7766
 7767
 7768
 7769
 7770
 7771
 7772
 7773
 7774
 7775
 7776
 7777
 7778
 7779
 7780
 7781
 7782
 7783
 7784
 7785
 7786
 7787
 7788
 7789
 7790
 7791
 7792
 7793
 7794
 7795
 7796
 7797
 7798
 7799
 7800
 7801
 7802
 7803
 7804
 7805
 7806
 7807
 7808
 7809
 7810
 7811
 7812
 7813
 7814
 7815
 7816
 7817
 7818
 7819
 7820
 7821
 7822
 7823
 7824
 7825
 7826
 7827
 7828
 7829
 7830
 7831
 7832
 7833
 7834
 7835
 7836
 7837
 7838
 7839
 7840
 7841
 7842
 7843
 7844
 7845
 7846
 7847
 7848
 7849
 7850
 7851
 7852
 7853
 7854
 7855
 7856
 7857
 7858
 7859
 7860
 7861
 7862
 7863
 7864
 7865
 7866
 7867
 7868
 7869
 7870
 7871
 7872
 7873
 7874
 7875
 7876
 7877
 7878
 7879
 7880
 7881
 7882
 7883
 7884
 7885
 7886
 7887
 7888
 7889
 7890
 7891
 7892
 7893
 7894
 7895
 7896
 7897
 7898
 7899
 7900
 7901
 7902
 7903
 7904
 7905
 7906
 7907
 7908
 7909
 7910
 7911
 7912
 7913
 7914
 7915
 7916
 7917
 7918
 7919
 7920
 7921
 7922
 7923
 7924
 7925
 7926
 7927
 7928
 7929
 7930
 7931
 7932
 7933
 7934
 7935
 7936
 7937
 7938
 7939
 7940
 7941
 7942
 7943
 7944
 7945
 7946
 7947
 7948
 7949
 7950
 7951
 7952
 7953
 7954
 7955
 7956
 7957
 7958
 7959
 7960
 7961
 7962
 7963
 7964
 7965
 7966
 7967
 7968
 7969
 7970
 7971
 7972
 7973
 7974
 7975
 7976
 7977
 7978
 7979
 7980
 7981
 7982
 7983
 7984
 7985
 7986
 7987
 7988
 7989
 7990
 7991
 7992
 7993
 7994
 7995
 7996
 7997
 7998
 7999
 8000
 8001
 8002
 8003
 8004
 8005
 8006
 8007
 8008
 8009
 8010
 8011
 8012
 8013
 8014
 8015
 8016
 8017
 8018
 8019
 8020
 8021
 8022
 8023
 8024
 8025
 8026
 8027
 8028
 8029
 8030
 8031
 8032
 8033
 8034
 8035
 8036
 8037
 8038
 8039
 8040
 8041
 8042
 8043
 8044
 8045
 8046
 8047
 8048
 8049
 8050
 8051
 8052
 8053
 8054
 8055
 8056
 8057
 8058
 8059
 8060
 8061
 8062
 8063
 8064
 8065
 8066
 8067
 8068
 8069
 8070
 8071
 8072
 8073
 8074
 8075
 8076
 8077
 8078
 8079
 8080
 8081
 8082
 8083
 8084
 8085
 8086
 8087
 8088
 8089
 8090
 8091
 8092
 8093
 8094
 8095
 8096
 8097
 8098
 8099
 8100
 8101
 8102
 8103
 8104
 8105
 8106
 8107
 8108
 8109
 8110
 8111
 8112
 8113
 8114
 8115
 8116
 8117
 8118
 8119
 8120
 8121
 8122
 8123
 8124
 8125
 8126
 8127
 8128
 8129
 8130
 8131
 8132
 8133
 8134
 8135
 8136
 8137
 8138
 8139
 8140
 8141
 8142
 8143
 8144
 8145
 8146
 8147
 8148
 8149
 8150
 8151
 8152
 8153
 8154
 8155
 8156
 8157
 8158
 8159
 8160
 8161
 8162
 8163
 8164
 8165
 8166
 8167
 8168
 8169
 8170
 8171
 8172
 8173
 8174
 8175
 8176
 8177
 8178
 8179
 8180
 8181
 8182
 8183
 8184
 8185
 8186
 8187
 8188
 8189
 8190
 8191
 8192
 8193
 8194
 8195
 8196
 8197
 8198
 8199
 8200
 8201
 8202
 8203
 8204
 8205
 8206
 8207
 8208
 8209
 8210
 8211
 8212
 8213
 8214
 8215
 8216
 8217
 8218
 8219
 8220
 8221
 8222
 8223
 8224
 8225
 8226
 8227
 8228
 8229
 8230
 8231
 8232
 8233
 8234
 8235
 8236
 8237
 8238
 8239
 8240
 8241
 8242
 8243
 8244
 8245
 8246
 8247
 8248
 8249
 8250
 8251
 8252
 8253
 8254
 8255
 8256
 8257
 8258
 8259
 8260
 8261
 8262
 8263
 8264
 8265
 8266
 8267
 8268
 8269
 8270
 8271
 8272
 8273
 8274
 8275
 8276
 8277
 8278
 8279
 8280
 8281
 8282
 8283
 8284
 8285
 8286
 8287
 8288
 8289
 8290
 8291
 8292
 8293
 8294
 8295
 8296
 8297
 8298
 8299
 8300
 8301
 8302
 8303
 8304
 8305
 8306
 8307
 8308
 8309
 8310
 8311
 8312
 8313
 8314
 8315
 8316
 8317
 8318
 8319
 8320
 8321
 8322
 8323
 8324
 8325
 8326
 8327
 8328
 8329
 8330
 8331
 8332
 8333
 8334
 8335
 8336
 8337
 8338
 8339
 8340
 8341
 8342
 8343
 8344
 8345
 8346
 8347
 8348
 8349
 8350
 8351
 8352
 8353
 8354
 8355
 8356
 8357
 8358
 8359
 8360
 8361
 8362
 8363
 8364
 8365
 8366
 8367
 8368
 8369
 8370
 8371
 8372
 8373
 8374
 8375
 8376
 8377
 8378
 8379
 8380
 8381
 8382
 8383
 8384
 8385
 8386
 8387
 8388
 8389
 8390
 8391
 8392
 8393
 8394
 8395
 8396
 8397
 8398
 8399
 8400
 8401
 8402
 8403
 8404
 8405
 8406
 8407
 8408
 8409
 8410
 8411
 8412
 8413
 8414
 8415
 8416
 8417
 8418
 8419
 8420
 8421
 8422
 8423
 8424
 8425
 8426
 8427
 8428
 8429
 8430
 8431
 8432
 8433
 8434
 8435
 8436
 8437
 8438
 8439
 8440
 8441
 8442
 8443
 8444
 8445
 8446
 8447
 8448
 8449
 8450
 8451
 8452
 8453
 8454
 8455
 8456
 8457
 8458
 8459
 8460
 8461
 8462
 8463
 8464
 8465
 8466
 8467
 8468
 8469
 8470
 8471
 8472
 8473
 8474
 8475
 8476
 8477
 8478
 8479
 8480
 8481
 8482
 8483
 8484
 8485
 8486
 8487
 8488
 8489
 8490
 8491
 8492
 8493
 8494
 8495
 8496
 8497
 8498
 8499
 8500
 8501
 8502
 8503
 8504
 8505
 8506
 8507
 8508
 8509
 8510
 8511
 8512
 8513
 8514
 8515
 8516
 8517
 8518
 8519
 8520
 8521
 8522
 8523
 8524
 8525
 8526
 8527
 8528
 8529
 8530
 8531
 8532
 8533
 8534
 8535
 8536
 8537
 8538
 8539
 8540
 8541
 8542
 8543
 8544
 8545
 8546
 8547
 8548
 8549
 8550
 8551
 8552
 8553
 8554
 8555
 8556
 8557
 8558
 8559
 8560
 8561
 8562
 8563
 8564
 8565
 8566
 8567
 8568
 8569
 8570
 8571
 8572
 8573
 8574
 8575
 8576
 8577
 8578
 8579
 8580
 8581
 8582
 8583
 8584
 8585
 8586
 8587
 8588
 8589
 8590
 8591
 8592
 8593
 8594
 8595
 8596
 8597
 8598
 8599
 8600
 8601
 8602
 8603
 8604
 8605
 8606
 8607
 8608
 8609
 8610
 8611
 8612
 8613
 8614
 8615
 8616
 8617
 8618
 8619
 8620
 8621
 8622
 8623
 8624
 8625
 8626
 8627
 8628
 8629
 8630
 8631
 8632
 8633
 8634
 8635
 8636
 8637
 8638
 8639
 8640
 8641
 8642
 8643
 8644
 8645
 8646
 8647
 8648
 8649
 8650
 8651
 8652
 8653
 8654
 8655
 8656
 8657
 8658
 8659
 8660
 8661
 8662
 8663
 8664
 8665
 8666
 8667
 8668
 8669
 8670
 8671
 8672
 8673
 8674
 8675
 8676
 8677
 8678
 8679
 8680
 8681
 8682
 8683
 8684
 8685
 8686
 8687
 8688
 8689
 8690
 8691
 8692
 8693
 8694
 8695
 8696
 8697
 8698
 8699
 8700
 8701
 8702
 8703
 8704
 8705
 8706
 8707
 8708
 8709
 8710
 8711
 8712
 8713
 8714
 8715
 8716
 8717
 8718
 8719
 8720
 8721
 8722
 8723
 8724
 8725
 8726
 8727
 8728
 8729
 8730
 8731
 8732
 8733
 8734
 8735
 8736
 8737
 8738
 8739
 8740
 8741
 8742
 8743
 8744
 8745
 8746
 8747
 8748
 8749
 8750
 8751
 8752
 8753
 8754
 8755
 8756
 8757
 8758
 8759
 8760
 8761
 8762
 8763
 8764
 8765
 8766
 8767
 8768
 8769
 8770
 8771
 8772
 8773
 8774
 8775
 8776
 8777
 8778
 8779
 8780
 8781
 8782
 8783
 8784
 8785
 8786
 8787
 8788
 8789
 8790
 8791
 8792
 8793
 8794
 8795
 8796
 8797
 8798
 8799
 8800
 8801
 8802
 8803
 8804
 8805
 8806
 8807
 8808
 8809
 8810
 8811
 8812
 8813
 8814
 8815
 8816
 8817
 8818
 8819
 8820
 8821
 8822
 8823
 8824
 8825
 8826
 8827
 8828
 8829
 8830
 8831
 8832
 8833
 8834
 8835
 8836
 8837
 8838
 8839
 8840
 8841
 8842
 8843
 8844
 8845
 8846
 8847
 8848
 8849
 8850
 8851
 8852
 8853
 8854
 8855
 8856
 8857
 8858
 8859
 8860
 8861
 8862
 8863
 8864
 8865
 8866
 8867
 8868
 8869
 8870
 8871
 8872
 8873
 8874
 8875
 8876
 8877
 8878
 8879
 8880
 8881
 8882
 8883
 8884
 8885
 8886
 8887
 8888
 8889
 8890
 8891
 8892
 8893
 8894
 8895
 8896
 8897
 8898
 8899
 8900
 8901
 8902
 8903
 8904
 8905
 8906
 8907
 8908
 8909
 8910
 8911
 8912
 8913
 8914
 8915
 8916
 8917
 8918
 8919
 8920
 8921
 8922
 8923
 8924
 8925
 8926
 8927
 8928
 8929
 8930
 8931
 8932
 8933
 8934
 8935
 8936
 8937
 8938
 8939
 8940
 8941
 8942
 8943
 8944
 8945
 8946
 8947
 8948
 8949
 8950
 8951
 8952
 8953
 8954
 8955
 8956
 8957
 8958
 8959
 8960
 8961
 8962
 8963
 8964
 8965
 8966
 8967
 8968
 8969
 8970
 8971
 8972
 8973
 8974
 8975
 8976
 8977
 8978
 8979
 8980
 8981
 8982
 8983
 8984
 8985
 8986
 8987
 8988
 8989
 8990
 8991
 8992
 8993
 8994
 8995
 8996
 8997
 8998
 8999
 9000
 9001
 9002
 9003
 9004
 9005
 9006
 9007
 9008
 9009
 9010
 9011
 9012
 9013
 9014
 9015
 9016
 9017
 9018
 9019
 9020
 9021
 9022
 9023
 9024
 9025
 9026
 9027
 9028
 9029
 9030
 9031
 9032
 9033
 9034
 9035
 9036
 9037
 9038
 9039
 9040
 9041
 9042
 9043
 9044
 9045
 9046
 9047
 9048
 9049
 9050
 9051
 9052
 9053
 9054
 9055
 9056
 9057
 9058
 9059
 9060
 9061
 9062
 9063
 9064
 9065
 9066
 9067
 9068
 9069
 9070
 9071
 9072
 9073
 9074
 9075
 9076
 9077
 9078
 9079
 9080
 9081
 9082
 9083
 9084
 9085
 9086
 9087
 9088
 9089
 9090
 9091
 9092
 9093
 9094
 9095
 9096
 9097
 9098
 9099
 9100
 9101
 9102
 9103
 9104
 9105
 9106
 9107
 9108
 9109
 9110
 9111
 9112
 9113
 9114
 9115
 9116
 9117
 9118
 9119
 9120
 9121
 9122
 9123
 9124
 9125
 9126
 9127
 9128
 9129
 9130
 9131
 9132
 9133
 9134
 9135
 9136
 9137
 9138
 9139
 9140
 9141
 9142
 9143
 9144
 9145
 9146
 9147
 9148
 9149
 9150
 9151
 9152
 9153
 9154
 9155
 9156
 9157
 9158
 9159
 9160
 9161
 9162
 9163
 9164
 9165
 9166
 9167
 9168
 9169
 9170
 9171
 9172
 9173
 9174
 9175
 9176
 9177
 9178
 9179
 9180
 9181
 9182
 9183
 9184
 9185
 9186
 9187
 9188
 9189
 9190
 9191
 9192
 9193
 9194
 9195
 9196
 9197
 9198
 9199
 9200
 9201
 9202
 9203
 9204
 9205
 9206
 9207
 9208
 9209
 9210
 9211
 9212
 9213
 9214
 9215
 9216
 9217
 9218
 9219
 9220
 9221
 9222
 9223
 9224
 9225
 9226
 9227
 9228
 9229
 9230
 9231
 9232
 9233
 9234
 9235
 9236
 9237
 9238
 9239
 9240
 9241
 9242
 9243
 9244
 9245
 9246
 9247
 9248
 9249
 9250
 9251
 9252
 9253
 9254
 9255
 9256
 9257
 9258
 9259
 9260
 9261
 9262
 9263
 9264
 9265
 9266
 9267
 9268
 9269
 9270
 9271
 9272
 9273
 9274
 9275
 9276
 9277
 9278
 9279
 9280
 9281
 9282
 9283
 9284
 9285
 9286
 9287
 9288
 9289
 9290
 9291
 9292
 9293
 9294
 9295
 9296
 9297
 9298
 9299
 9300
 9301
 9302
 9303
 9304
 9305
 9306
 9307
 9308
 9309
 9310
 9311
 9312
 9313
 9314
 9315
 9316
 9317
 9318
 9319
 9320
 9321
 9322
 9323
 9324
 9325
 9326
 9327
 9328
 9329
 9330
 9331
 9332
 9333
 9334
 9335
 9336
 9337
 9338
 9339
 9340
 9341
 9342
 9343
 9344
 9345
 9346
 9347
 9348
 9349
 9350
 9351
 9352
 9353
 9354
 9355
 9356
 9357
 9358
 9359
 9360
 9361
 9362
 9363
 9364
 9365
 9366
 9367
 9368
 9369
 9370
 9371
 9372
 9373
 9374
 9375
 9376
 9377
 9378
 9379
 9380
 9381
 9382
 9383
 9384
 9385
 9386
 9387
 9388
 9389
 9390
 9391
 9392
 9393
 9394
 9395
 9396
 9397
 9398
 9399
 9400
 9401
 9402
 9403
 9404
 9405
 9406
 9407
 9408
 9409
 9410
 9411
 9412
 9413
 9414
 9415
 9416
 9417
 9418
 9419
 9420
 9421
 9422
 9423
 9424
 9425
 9426
 9427
 9428
 9429
 9430
 9431
 9432
 9433
 9434
 9435
 9436
 9437
 9438
 9439
 9440
 9441
 9442
 9443
 9444
 9445
 9446
 9447
 9448
 9449
 9450
 9451
 9452
 9453
 9454
 9455
 9456
 9457
 9458
 9459
 9460
 9461
 9462
 9463
 9464
 9465
 9466
 9467
 9468
 9469
 9470
 9471
 9472
 9473
 9474
 9475
 9476
 9477
 9478
 9479
 9480
 9481
 9482
 9483
 9484
 9485
 9486
 9487
 9488
 9489
 9490
 9491
 9492
 9493
 9494
 9495
 9496
 9497
 9498
 9499
 9500
 9501
 9502
 9503
 9504
 9505
 9506
 9507
 9508
 9509
 9510
 9511
 9512
 9513
 9514
 9515
 9516
 9517
 9518
 9519
 9520
 9521
 9522
 9523
 9524
 9525
 9526
 9527
 9528
 9529
 9530
 9531
 9532
 9533
 9534
 9535
 9536
 9537
 9538
 9539
 9540
 9541
 9542
 9543
 9544
 9545
 9546
 9547
 9548
 9549
 9550
 9551
 9552
 9553
 9554
 9555
 9556
 9557
 9558
 9559
 9560
 9561
 9562
 9563
 9564
 9565
 9566
 9567
 9568
 9569
 9570
 9571
 9572
 9573
 9574
 9575
 9576
 9577
 9578
 9579
 9580
 9581
 9582
 9583
 9584
 9585
 9586
 9587
 9588
 9589
 9590
 9591
 9592
 9593
 9594
 9595
 9596
 9597
 9598
 9599
 9600
 9601
 9602
 9603
 9604
 9605
 9606
 9607
 9608
 9609
 9610
 9611
 9612
 9613
 9614
 9615
 9616
 9617
 9618
 9619
 9620
 9621
 9622
 9623
 9624
 9625
 9626
 9627
 9628
 9629
 9630
 9631
 9632
 9633
 9634
 9635
 9636
 9637
 9638
 9639
 9640
 9641
 9642
 9643
 9644
 9645
 9646
 9647
 9648
 9649
 9650
 9651
 9652
 9653
 9654
 9655
 9656
 9657
 9658
 9659
 9660
 9661
 9662
 9663
 9664
 9665
 9666
 9667
 9668
 9669
 9670
 9671
 9672
 9673
 9674
 9675
 9676
 9677
 9678
 9679
 9680
 9681
 9682
 9683
 9684
 9685
 9686
 9687
 9688
 9689
 9690
 9691
 9692
 9693
 9694
 9695
 9696
 9697
 9698
 9699
 9700
 9701
 9702
 9703
 9704
 9705
 9706
 9707
 9708
 9709
 9710
 9711
 9712
 9713
 9714
 9715
 9716
 9717
 9718
 9719
 9720
 9721
 9722
 9723
 9724
 9725
 9726
 9727
 9728
 9729
 9730
 9731
 9732
 9733
 9734
 9735
 9736
 9737
 9738
 9739
 9740
 9741
 9742
 9743
 9744
 9745
 9746
 9747
 9748
 9749
 9750
 9751
 9752
 9753
 9754
 9755
 9756
 9757
 9758
 9759
 9760
 9761
 9762
 9763
 9764
 9765
 9766
 9767
 9768
 9769
 9770
 9771
 9772
 9773
 9774
 9775
 9776
 9777
 9778
 9779
 9780
 9781
 9782
 9783
 9784
 9785
 9786
 9787
 9788
 9789
 9790
 9791
 9792
 9793
 9794
 9795
 9796
 9797
 9798
 9799
 9800
 9801
 9802
 9803
 9804
 9805
 9806
 9807
 9808
 9809
 9810
 9811
 9812
 9813
 9814
 9815
 9816
 9817
 9818
 9819
 9820
 9821
 9822
 9823
 9824
 9825
 9826
 9827
 9828
 9829
 9830
 9831
 9832
 9833
 9834
 9835
 9836
 9837
 9838
 9839
 9840
 9841
 9842
 9843
 9844
 9845
 9846
 9847
 9848
 9849
 9850
 9851
 9852
 9853
 9854
 9855
 9856
 9857
 9858
 9859
 9860
 9861
 9862
 9863
 9864
 9865
 9866
 9867
 9868
 9869
 9870
 9871
 9872
 9873
 9874
 9875
 9876
 9877
 9878
 9879
 9880
 9881
 9882
 9883
 9884
 9885
 9886
 9887
 9888
 9889
 9890
 9891
 9892
 9893
 9894
 9895
 9896
 9897
 9898
 9899
 9900
 9901
 9902
 9903
 9904
 9905
 9906
 9907
 9908
 9909
 9910
 9911
 9912
 9913
 9914
 9915
 9916
 9917
 9918
 9919
 9920
 9921
 9922
 9923
 9924
 9925
 9926
 9927
 9928
 9929
 9930
 9931
 9932
 9933
 9934
 9935
 9936
 9937
 9938
 9939
 9940
 9941
 9942
 9943
 9944
 9945
 9946
 9947
 9948
 9949
 9950
 9951
 9952
 9953
 9954
 9955
 9956
 9957
 9958
 9959
 9960
 9961
 9962
 9963
 9964
 9965
 9966
 9967
 9968
 9969
 9970
 9971
 9972
 9973
 9974
 9975
 9976
 9977
 9978
 9979
 9980
 9981
 9982
 9983
 9984
 9985
 9986
 9987
 9988
 9989
 9990
 9991
 9992
 9993
 9994
 9995
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
/*
 * Copyright (c) 2018-2020 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 "ClientRequests.h"

#include "DNSCommon.h"
#include "uDNS.h"

#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
#include "QuerierSupport.h"
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
#include "D2D.h"
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, REACHABILITY_TRIGGER)
#include "mDNSMacOSX.h"
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, UNREADY_INTERFACES)
#include <dispatch/dispatch.h>
#include <net/if.h>
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
#include <WebFilterDNS/WebFilterDNS.h>

int WCFIsServerRunning(WCFConnection *conn) __attribute__((weak_import));
int WCFNameResolvesToAddr(WCFConnection *conn, char* domainName, struct sockaddr* address, uid_t userid) __attribute__((weak_import));
int WCFNameResolvesToName(WCFConnection *conn, char* fromName, char* toName, uid_t userid) __attribute__((weak_import));
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
#include "dnssec_v2.h"
#endif

#define RecordTypeIsAddress(TYPE)   (((TYPE) == kDNSType_A) || ((TYPE) == kDNSType_AAAA))

extern mDNS mDNSStorage;
#if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DOTLOCAL)
extern domainname ActiveDirectoryPrimaryDomain;
#endif

// Normally we append search domains only for queries with a single label that are not fully qualified. This can be
// overridden to apply search domains for queries (that are not fully qualified) with any number of labels e.g., moon,
// moon.cs, moon.cs.be, etc. - Mohan
mDNSBool AlwaysAppendSearchDomains = mDNSfalse;

// Control enabling optimistic DNS - Phil
mDNSBool EnableAllowExpired = mDNStrue;


typedef struct
{
    mDNSu32                 requestID;
    const domainname *      qname;
    mDNSu16                 qtype;
    mDNSu16                 qclass;
    mDNSInterfaceID         interfaceID;
    mDNSs32                 serviceID;
    mDNSu32                 flags;
    mDNSBool                appendSearchDomains;
    mDNSs32                 effectivePID;
    const mDNSu8 *          effectiveUUID;
    mDNSu32                 peerUID;
    mDNSBool                isInAppBrowserRequest;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    const mDNSu8 *          resolverUUID;
	mdns_dns_service_id_t	customID;
    mDNSBool                needEncryption;
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    const audit_token_t *   peerAuditToken;
    const audit_token_t *   delegatorAuditToken;
#endif

}   QueryRecordOpParams;

mDNSlocal void QueryRecordOpParamsInit(QueryRecordOpParams *inParams)
{
	mDNSPlatformMemZero(inParams, (mDNSu32)sizeof(*inParams));
    inParams->serviceID = -1;
}

mDNSlocal mStatus QueryRecordOpCreate(QueryRecordOp **outOp);
mDNSlocal void QueryRecordOpFree(QueryRecordOp *operation);
mDNSlocal mStatus QueryRecordOpStart(QueryRecordOp *inOp, const QueryRecordOpParams *inParams,
    QueryRecordResultHandler inResultHandler, void *inResultContext);
mDNSlocal void QueryRecordOpStop(QueryRecordOp *op);
mDNSlocal mDNSBool QueryRecordOpIsMulticast(const QueryRecordOp *op);
mDNSlocal void QueryRecordOpCallback(mDNS *m, DNSQuestion *inQuestion, const ResourceRecord *inAnswer,
    QC_result inAddRecord);
mDNSlocal void QueryRecordOpResetHandler(DNSQuestion *inQuestion);
mDNSlocal mStatus QueryRecordOpStartQuestion(QueryRecordOp *inOp, DNSQuestion *inQuestion);
mDNSlocal mStatus QueryRecordOpStopQuestion(DNSQuestion *inQuestion);
mDNSlocal mStatus QueryRecordOpRestartUnicastQuestion(QueryRecordOp *inOp, DNSQuestion *inQuestion,
    const domainname *inSearchDomain);
mDNSlocal mStatus InterfaceIndexToInterfaceID(mDNSu32 inInterfaceIndex, mDNSInterfaceID *outInterfaceID);
mDNSlocal mDNSBool DomainNameIsSingleLabel(const domainname *inName);
mDNSlocal mDNSBool StringEndsWithDot(const char *inString);
mDNSlocal const domainname * NextSearchDomain(QueryRecordOp *inOp);
#if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DOTLOCAL)
mDNSlocal mDNSBool DomainNameIsInSearchList(const domainname *domain, mDNSBool inExcludeLocal);
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
mDNSlocal void NotifyWebContentFilter(const ResourceRecord *inAnswer, uid_t inUID);
#endif

mDNSexport void GetAddrInfoClientRequestParamsInit(GetAddrInfoClientRequestParams *inParams)
{
	mDNSPlatformMemZero(inParams, (mDNSu32)sizeof(*inParams));
}

mDNSexport mStatus GetAddrInfoClientRequestStart(GetAddrInfoClientRequest *inRequest,
    const GetAddrInfoClientRequestParams *inParams, QueryRecordResultHandler inResultHandler, void *inResultContext)
{
    mStatus             err;
    domainname          hostname;
    mDNSBool            appendSearchDomains;
    mDNSInterfaceID     interfaceID;
    DNSServiceFlags     flags;
    mDNSs32             serviceID;
    QueryRecordOpParams opParams;

    if (!MakeDomainNameFromDNSNameString(&hostname, inParams->hostnameStr))
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%u] ERROR: bad hostname '" PRI_S "'", inParams->requestID, inParams->hostnameStr);
        err = mStatus_BadParamErr;
        goto exit;
    }

    if (inParams->protocols & ~(kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6))
    {
        err = mStatus_BadParamErr;
        goto exit;
    }

    flags = inParams->flags;
    if (inParams->protocols == 0)
    {
        flags |= kDNSServiceFlagsSuppressUnusable;
        inRequest->protocols = kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6;
    }
    else
    {
        inRequest->protocols = inParams->protocols;
    }

    if (flags & kDNSServiceFlagsServiceIndex)
    {
        // NOTE: kDNSServiceFlagsServiceIndex flag can only be set for DNSServiceGetAddrInfo()
        LogInfo("GetAddrInfoClientRequestStart: kDNSServiceFlagsServiceIndex is SET by the client");

        // If kDNSServiceFlagsServiceIndex is SET, interpret the interfaceID as the serviceId and set the interfaceID to 0.
        serviceID   = (mDNSs32)inParams->interfaceIndex;
        interfaceID = mDNSNULL;
    }
    else
    {
        serviceID = -1;
        err = InterfaceIndexToInterfaceID(inParams->interfaceIndex, &interfaceID);
        if (err) goto exit;
    }
    inRequest->interfaceID = interfaceID;

    if (!StringEndsWithDot(inParams->hostnameStr) && (AlwaysAppendSearchDomains || DomainNameIsSingleLabel(&hostname)))
    {
        appendSearchDomains = mDNStrue;
    }
    else
    {
        appendSearchDomains = mDNSfalse;
    }
    QueryRecordOpParamsInit(&opParams);
    opParams.requestID              = inParams->requestID;
    opParams.qname                  = &hostname;
    opParams.qclass                 = kDNSClass_IN;
    opParams.interfaceID            = inRequest->interfaceID;
    opParams.serviceID              = serviceID;
    opParams.flags                  = flags;
    opParams.appendSearchDomains    = appendSearchDomains;
    opParams.effectivePID           = inParams->effectivePID;
    opParams.effectiveUUID          = inParams->effectiveUUID;
    opParams.peerUID                = inParams->peerUID;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    opParams.resolverUUID           = inParams->resolverUUID;
    opParams.customID               = inParams->customID;
    opParams.needEncryption         = inParams->needEncryption;
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    opParams.peerAuditToken         = inParams->peerAuditToken;
    opParams.delegatorAuditToken    = inParams->delegatorAuditToken;
    opParams.isInAppBrowserRequest  = inParams->isInAppBrowserRequest;
#endif
    if (inRequest->protocols & kDNSServiceProtocol_IPv6)
    {
        err = QueryRecordOpCreate(&inRequest->op6);
        if (err) goto exit;

        opParams.qtype = kDNSType_AAAA;
        err = QueryRecordOpStart(inRequest->op6, &opParams, inResultHandler, inResultContext);
        if (err) goto exit;
    }
    if (inRequest->protocols & kDNSServiceProtocol_IPv4)
    {
        err = QueryRecordOpCreate(&inRequest->op4);
        if (err) goto exit;

        opParams.qtype = kDNSType_A;
        err = QueryRecordOpStart(inRequest->op4, &opParams, inResultHandler, inResultContext);
        if (err) goto exit;
    }
    err = mStatus_NoError;

exit:
    if (err) GetAddrInfoClientRequestStop(inRequest);
    return err;
}

mDNSexport void GetAddrInfoClientRequestStop(GetAddrInfoClientRequest *inRequest)
{
    if (inRequest->op4) QueryRecordOpStop(inRequest->op4);
    if (inRequest->op6) QueryRecordOpStop(inRequest->op6);

#if MDNSRESPONDER_SUPPORTS(APPLE, REACHABILITY_TRIGGER)
    {
        const QueryRecordOp * const     op4 = inRequest->op4;
        const QueryRecordOp * const     op6 = inRequest->op6;
        const DNSQuestion *             q4  = mDNSNULL;
        const DNSQuestion *             q6  = mDNSNULL;

        if (op4)
        {
            if (op4->answered)
            {
                // If we have a v4 answer and if we timed out prematurely before, provide a trigger to the upper layer so
                // that it can retry questions if needed. - Mohan
                q4 = &op4->q;
            }
            else if (op4->q.TimeoutQuestion)
            {
                // If we are not delivering answers, we may be timing out prematurely. Note down the current state so that
                // we know to retry when we see a valid response again. - Mohan
                mDNSPlatformUpdateDNSStatus(&op4->q);
            }
        }
        if (op6)
        {
            if (op6->answered)
            {
                q6 = &op6->q;
            }
            else if (op6->q.TimeoutQuestion)
            {
                mDNSPlatformUpdateDNSStatus(&op6->q);
            }
        }
        mDNSPlatformTriggerDNSRetry(q4, q6);
    }
#endif

    if (inRequest->op4)
    {
        QueryRecordOpFree(inRequest->op4);
        inRequest->op4 = mDNSNULL;
    }
    if (inRequest->op6)
    {
        QueryRecordOpFree(inRequest->op6);
        inRequest->op6 = mDNSNULL;
    }
}

mDNSexport const domainname * GetAddrInfoClientRequestGetQName(const GetAddrInfoClientRequest *inRequest)
{
    if (inRequest->op4) return &inRequest->op4->q.qname;
    if (inRequest->op6) return &inRequest->op6->q.qname;
    return (const domainname *)"";
}

mDNSexport mDNSBool GetAddrInfoClientRequestIsMulticast(const GetAddrInfoClientRequest *inRequest)
{
    if ((inRequest->op4 && QueryRecordOpIsMulticast(inRequest->op4)) ||
        (inRequest->op6 && QueryRecordOpIsMulticast(inRequest->op6)))
    {
        return mDNStrue;
    }
    return mDNSfalse;
}

mDNSexport void QueryRecordClientRequestParamsInit(QueryRecordClientRequestParams *inParams)
{
	mDNSPlatformMemZero(inParams, (mDNSu32)sizeof(*inParams));
}

mDNSexport mStatus QueryRecordClientRequestStart(QueryRecordClientRequest *inRequest,
    const QueryRecordClientRequestParams *inParams, QueryRecordResultHandler inResultHandler, void *inResultContext)
{
    mStatus             err;
    domainname          qname;
    mDNSInterfaceID     interfaceID;
    mDNSBool            appendSearchDomains;
    QueryRecordOpParams opParams;
#if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
    dnssec_context_t *  dnssecContext = mDNSNULL;
#endif

    err = InterfaceIndexToInterfaceID(inParams->interfaceIndex, &interfaceID);
    if (err) goto exit;

    if (!MakeDomainNameFromDNSNameString(&qname, inParams->qnameStr))
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%u] ERROR: bad domain name '" PRI_S "'", inParams->requestID, inParams->qnameStr);
        err = mStatus_BadParamErr;
        goto exit;
    }

    if (RecordTypeIsAddress(inParams->qtype) && !StringEndsWithDot(inParams->qnameStr) &&
        (AlwaysAppendSearchDomains || DomainNameIsSingleLabel(&qname)))
    {
        appendSearchDomains = mDNStrue;
    }
    else
    {
        appendSearchDomains = mDNSfalse;
    }
    QueryRecordOpParamsInit(&opParams);
    opParams.requestID              = inParams->requestID;
    opParams.qname                  = &qname;
    opParams.qtype                  = inParams->qtype;
    opParams.qclass                 = inParams->qclass;
    opParams.interfaceID            = interfaceID;
    opParams.appendSearchDomains    = appendSearchDomains;
    opParams.effectivePID           = inParams->effectivePID;
    opParams.effectiveUUID          = inParams->effectiveUUID;
    opParams.peerUID                = inParams->peerUID;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    opParams.resolverUUID           = inParams->resolverUUID;
    opParams.customID               = inParams->customID;
    opParams.needEncryption         = inParams->needEncryption;
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    opParams.peerAuditToken         = inParams->peerAuditToken;
    opParams.delegatorAuditToken    = inParams->delegatorAuditToken;
    opParams.isInAppBrowserRequest  = inParams->isInAppBrowserRequest;
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
    // Query ends with ".local." and query for RRSIG or ANY type cannot be validated by DNSSEC even if the user sets the
    // kDNSServiceFlagsEnableDNSSEC flag.
    if (FLAGS_CONTAIN_DNSOK_BIT(inParams->flags) && is_eligible_for_dnssec(&qname, inParams->qtype))
    {
        opParams.flags = inParams->flags | kDNSServiceFlagsReturnIntermediates; // to handle CNAME reference
        err = create_dnssec_context_t(inRequest, inParams->requestID, &qname, inParams->qtype, inParams->qclass,
            interfaceID, -1, inParams->flags, appendSearchDomains, inParams->effectivePID, inParams->effectiveUUID,
            inParams->peerUID,
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
            inParams->peerAuditToken, inParams->delegatorAuditToken,
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
            mDNSNULL, inParams->needEncryption, inParams->customID,
#endif
            inResultHandler, inResultContext, mDNSNULL, &dnssecContext);
        require_action(err == mStatus_NoError, exit, log_debug("create_dnssec_context_t failed; error_description='%s'",
            mStatusDescription(err)));

        err = QueryRecordOpStart(&inRequest->op, &opParams, query_record_result_reply_with_dnssec, dnssecContext);
    } else
#endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
    {
        opParams.flags = inParams->flags;
        err = QueryRecordOpStart(&inRequest->op, &opParams, inResultHandler, inResultContext);
    }

exit:
    if (err) QueryRecordClientRequestStop(inRequest);
    return err;
}

mDNSexport void QueryRecordClientRequestStop(QueryRecordClientRequest *inRequest)
{
    QueryRecordOpStop(&inRequest->op);

#if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
    stop_dnssec_if_enable_dnssec(inRequest);
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, REACHABILITY_TRIGGER)
    if (inRequest->op.answered)
    {
        DNSQuestion *v4q, *v6q;
        // If we are receiving positive answers, provide the hint to the upper layer. - Mohan
        v4q = (inRequest->op.q.qtype == kDNSType_A)    ? &inRequest->op.q : mDNSNULL;
        v6q = (inRequest->op.q.qtype == kDNSType_AAAA) ? &inRequest->op.q : mDNSNULL;
        mDNSPlatformTriggerDNSRetry(v4q, v6q);
    }
#endif
}

mDNSexport const domainname * QueryRecordClientRequestGetQName(const QueryRecordClientRequest *inRequest)
{
    return &inRequest->op.q.qname;
}

mDNSexport mDNSu16 QueryRecordClientRequestGetType(const QueryRecordClientRequest *inRequest)
{
    return inRequest->op.q.qtype;
}

mDNSexport mDNSBool QueryRecordClientRequestIsMulticast(QueryRecordClientRequest *inRequest)
{
    return (QueryRecordOpIsMulticast(&inRequest->op) ? mDNStrue : mDNSfalse);
}
#if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
mDNSexport mStatus QueryRecordOpStartForClientRequest(
    QueryRecordOp *             inOp,
    mDNSu32                     inReqID,
    const domainname *          inQName,
    mDNSu16                     inQType,
    mDNSu16                     inQClass,
    mDNSInterfaceID             inInterfaceID,
    mDNSs32                     inServiceID,
    mDNSu32                     inFlags,
    mDNSBool                    inAppendSearchDomains,
    mDNSs32                     inPID,
    const mDNSu8                inUUID[UUID_SIZE],
    mDNSu32                     inUID,
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    const audit_token_t *       inPeerAuditTokenPtr,
    const audit_token_t *       inDelegateAuditTokenPtr,
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    const mDNSu8                inResolverUUID[UUID_SIZE],
    mDNSBool                    inNeedEncryption,
    const mdns_dns_service_id_t inCustomID,
#endif
    QueryRecordResultHandler    inResultHandler,
    void *                      inResultContext) {
    QueryRecordOpParams opParams;
    QueryRecordOpParamsInit(&opParams);
    opParams.requestID           = inReqID;
    opParams.qname               = inQName;
    opParams.qtype               = inQType;
    opParams.qclass              = inQClass;
    opParams.interfaceID         = inInterfaceID;
    opParams.serviceID           = inServiceID;
    opParams.flags               = inFlags;
    opParams.appendSearchDomains = inAppendSearchDomains;
    opParams.effectivePID        = inPID;
    opParams.effectiveUUID       = inUUID;
    opParams.peerUID             = inUID;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    opParams.resolverUUID        = inResolverUUID;
    opParams.customID            = inCustomID;
    opParams.needEncryption      = inNeedEncryption;
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    opParams.peerAuditToken      = inPeerAuditTokenPtr;
    opParams.delegatorAuditToken = inDelegateAuditTokenPtr;
#endif
    return QueryRecordOpStart(inOp, &opParams, inResultHandler, inResultContext);
}

mDNSexport void QueryRecordOpStopForClientRequest(QueryRecordOp *op) {
    QueryRecordOpStop(op);
}

#endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)

mDNSlocal mStatus QueryRecordOpCreate(QueryRecordOp **outOp)
{
    mStatus err;
    QueryRecordOp *op;

    op = (QueryRecordOp *) mDNSPlatformMemAllocateClear(sizeof(*op));
    if (!op)
    {
        err = mStatus_NoMemoryErr;
        goto exit;
    }
    *outOp = op;
    err = mStatus_NoError;

exit:
    return err;
}

mDNSlocal void QueryRecordOpFree(QueryRecordOp *operation)
{
    mDNSPlatformMemFree(operation);
}

#define VALID_MSAD_SRV_TRANSPORT(T) \
    (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
#define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))

mDNSlocal mStatus QueryRecordOpStart(QueryRecordOp *inOp, const QueryRecordOpParams *inParams,
    QueryRecordResultHandler inResultHandler, void *inResultContext)
{
    mStatus                 err;
    DNSQuestion * const     q = &inOp->q;
    mDNSu32                 len;

    // Save the original qname.

    len = DomainNameLength(inParams->qname);
    inOp->qname = (domainname *) mDNSPlatformMemAllocate(len);
    if (!inOp->qname)
    {
        err = mStatus_NoMemoryErr;
        goto exit;
    }
    mDNSPlatformMemCopy(inOp->qname, inParams->qname, len);

    inOp->interfaceID   = inParams->interfaceID;
    inOp->reqID         = inParams->requestID;
    inOp->resultHandler = inResultHandler;
    inOp->resultContext = inResultContext;

    // Set up DNSQuestion.

    if (EnableAllowExpired && (inParams->flags & kDNSServiceFlagsAllowExpiredAnswers))
    {
        q->allowExpired = AllowExpired_AllowExpiredAnswers;
    }
    else
    {
        q->allowExpired = AllowExpired_None;
    }
    q->ServiceID = inParams->serviceID;
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    q->inAppBrowserRequest = inParams->isInAppBrowserRequest;
    if (inParams->peerAuditToken)
    {
        q->peerAuditToken = *inParams->peerAuditToken;
    }
    if (inParams->delegatorAuditToken)
    {
        q->delegateAuditToken = *inParams->delegatorAuditToken;
    }
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    if (inParams->resolverUUID)
    {
        mDNSPlatformMemCopy(q->ResolverUUID, inParams->resolverUUID, UUID_SIZE);
    }
#endif
    q->InterfaceID          = inParams->interfaceID;
    q->flags                = inParams->flags;
    AssignDomainName(&q->qname, inParams->qname);
    q->qtype                = inParams->qtype;
    q->qclass               = inParams->qclass;
    q->LongLived            = (inParams->flags & kDNSServiceFlagsLongLivedQuery)            ? mDNStrue : mDNSfalse;
    q->ForceMCast           = (inParams->flags & kDNSServiceFlagsForceMulticast)            ? mDNStrue : mDNSfalse;
    q->ReturnIntermed       = (inParams->flags & kDNSServiceFlagsReturnIntermediates)       ? mDNStrue : mDNSfalse;
    q->SuppressUnusable     = (inParams->flags & kDNSServiceFlagsSuppressUnusable)          ? mDNStrue : mDNSfalse;
    q->TimeoutQuestion      = (inParams->flags & kDNSServiceFlagsTimeout)                   ? mDNStrue : mDNSfalse;
    q->UseBackgroundTraffic = (inParams->flags & kDNSServiceFlagsBackgroundTrafficClass)    ? mDNStrue : mDNSfalse;
    q->AppendSearchDomains  = inParams->appendSearchDomains;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    q->RequireEncryption    = inParams->needEncryption;
    q->CustomID             = inParams->customID;
#endif
    q->InitialCacheMiss     = mDNSfalse;

#if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
    err = initialize_dnssec_status_t(&q->DNSSECStatus, inParams->qname, inParams->qtype, inParams->flags, inResultContext);
    require_action(err == mStatus_NoError, exit, log_debug("initialize_dnssec_status failed; error_description='%s'", mStatusDescription(err)));
#endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)

    q->pid              = inParams->effectivePID;
    if (inParams->effectiveUUID)
    {
        mDNSPlatformMemCopy(q->uuid, inParams->effectiveUUID, UUID_SIZE);
    }
    q->euid             = inParams->peerUID;
    q->request_id       = inParams->requestID;
    q->QuestionCallback = QueryRecordOpCallback;
    q->ResetHandler     = QueryRecordOpResetHandler;

    // For single label queries that are not fully qualified, look at /etc/hosts, cache and try search domains before trying
    // them on the wire as a single label query. - Mohan

    if (q->AppendSearchDomains && DomainNameIsSingleLabel(inOp->qname)) q->InterfaceID = mDNSInterface_LocalOnly;
    err = QueryRecordOpStartQuestion(inOp, q);
    if (err) goto exit;

#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
    if (callExternalHelpers(q->InterfaceID, &q->qname, q->flags))
    {
        external_start_browsing_for_service(q->InterfaceID, &q->qname, q->qtype, q->flags, q->pid);
    }
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DOTLOCAL)
    if ((RecordTypeIsAddress(q->qtype) || VALID_MSAD_SRV(&inOp->q)) && !q->ForceMCast &&
        SameDomainLabel(LastLabel(&q->qname), (const mDNSu8 *)&localdomain))
    {
        DNSQuestion *       q2;

        q2 = (DNSQuestion *) mDNSPlatformMemAllocate((mDNSu32)sizeof(*inOp->q2));
        if (!q2)
        {
            err = mStatus_NoMemoryErr;
            goto exit;
        }
        inOp->q2 = q2;

        *q2 = *q;
        q2->IsUnicastDotLocal = mDNStrue;

        if ((CountLabels(&q2->qname) == 2) && !SameDomainName(&q2->qname, &ActiveDirectoryPrimaryDomain)
            && !DomainNameIsInSearchList(&q2->qname, mDNSfalse))
        {
            inOp->q2Type                = q2->qtype;
            inOp->q2LongLived           = q2->LongLived;
            inOp->q2ReturnIntermed      = q2->ReturnIntermed;
            inOp->q2TimeoutQuestion     = q2->TimeoutQuestion;
            inOp->q2AppendSearchDomains = q2->AppendSearchDomains;

            AssignDomainName(&q2->qname, &localdomain);
            q2->qtype                   = kDNSType_SOA;
            q2->LongLived               = mDNSfalse;
            q2->ReturnIntermed          = mDNStrue;
            q2->TimeoutQuestion         = mDNSfalse;
            q2->AppendSearchDomains     = mDNSfalse;
        }

        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
               "[R%u] QueryRecordOpStart: starting parallel unicast query for " PRI_DM_NAME " " PUB_S,
               inOp->reqID, DM_NAME_PARAM(&q2->qname), DNSTypeName(q2->qtype));

        err = QueryRecordOpStartQuestion(inOp, q2);
        if (err) goto exit;
    }
#endif
    err = mStatus_NoError;

exit:
    if (err) QueryRecordOpStop(inOp);
    return err;
}

mDNSlocal void QueryRecordOpStop(QueryRecordOp *op)
{
    if (op->q.QuestionContext)
    {
        QueryRecordOpStopQuestion(&op->q);
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
        if (callExternalHelpers(op->q.InterfaceID, op->qname, op->q.flags))
        {
            external_stop_browsing_for_service(op->q.InterfaceID, &op->q.qname, op->q.qtype, op->q.flags, op->q.pid);
        }
#endif
    }
    if (op->qname)
    {
        mDNSPlatformMemFree(op->qname);
        op->qname = mDNSNULL;
    }
#if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DOTLOCAL)
    if (op->q2)
    {
        if (op->q2->QuestionContext) QueryRecordOpStopQuestion(op->q2);
        mDNSPlatformMemFree(op->q2);
        op->q2 = mDNSNULL;
    }
#endif
}

mDNSlocal mDNSBool QueryRecordOpIsMulticast(const QueryRecordOp *op)
{
    return ((mDNSOpaque16IsZero(op->q.TargetQID) && (op->q.ThisQInterval > 0)) ? mDNStrue : mDNSfalse);
}

// GetTimeNow is a callback-safe alternative to mDNS_TimeNow(), which expects to be called with m->mDNS_busy == 0.
mDNSlocal mDNSs32 GetTimeNow(mDNS *m)
{
    mDNSs32 time;
    mDNS_Lock(m);
    time = m->timenow;
    mDNS_Unlock(m);
    return time;
}

mDNSlocal void QueryRecordOpCallback(mDNS *m, DNSQuestion *inQuestion, const ResourceRecord *inAnswer, QC_result inAddRecord)
{
    mStatus                     resultErr;
    QueryRecordOp *const        op = (QueryRecordOp *)inQuestion->QuestionContext;
    const domainname *          domain;

#if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DOTLOCAL)
    if ((inQuestion == op->q2) && (inQuestion->qtype == kDNSType_SOA))
    {
        DNSQuestion * const     q2 = op->q2;

        if (inAnswer->rrtype != kDNSType_SOA) goto exit;
        QueryRecordOpStopQuestion(q2);

        // Restore DNSQuestion variables that were modified for the SOA query.

        q2->qtype               = op->q2Type;
        q2->LongLived           = op->q2LongLived;
        q2->ReturnIntermed      = op->q2ReturnIntermed;
        q2->TimeoutQuestion     = op->q2TimeoutQuestion;
        q2->AppendSearchDomains = op->q2AppendSearchDomains;

        if (inAnswer->RecordType != kDNSRecordTypePacketNegative)
        {
            QueryRecordOpRestartUnicastQuestion(op, q2, mDNSNULL);
        }
        else if (q2->AppendSearchDomains)
        {
            domain = NextSearchDomain(op);
            if (domain) QueryRecordOpRestartUnicastQuestion(op, q2, domain);
        }
        goto exit;
    }
#endif

    if (inAddRecord == QC_suppressed)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
               "[R%u] QueryRecordOpCallback: Suppressed question " PRI_DM_NAME " (" PUB_S ")",
               op->reqID, DM_NAME_PARAM(&inQuestion->qname), DNSTypeName(inQuestion->qtype));

        resultErr = kDNSServiceErr_NoSuchRecord;
    }
    else if (inAnswer->RecordType == kDNSRecordTypePacketNegative)
    {
        if (inQuestion->TimeoutQuestion && ((GetTimeNow(m) - inQuestion->StopTime) >= 0))
        {
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
                   "[R%u] QueryRecordOpCallback: Question " PRI_DM_NAME " (" PUB_S ") timing out, InterfaceID %p",
                   op->reqID, DM_NAME_PARAM(&inQuestion->qname), DNSTypeName(inQuestion->qtype),
                   inQuestion->InterfaceID);
            resultErr = kDNSServiceErr_Timeout;
        }
        else
        {
            if (inQuestion->AppendSearchDomains && (op->searchListIndex >= 0) && inAddRecord)
            {
                domain = NextSearchDomain(op);
                if (domain || DomainNameIsSingleLabel(op->qname))
                {
                    QueryRecordOpStopQuestion(inQuestion);
                    QueryRecordOpRestartUnicastQuestion(op, inQuestion, domain);
                    goto exit;
                }
            }
#if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DOTLOCAL)
            if (!inAnswer->InterfaceID && IsLocalDomain(inAnswer->name))
            {
                if ((RecordTypeIsAddress(inQuestion->qtype) &&
                    (inAnswer->negativeRecordType == kNegativeRecordType_NoData)) ||
                    DomainNameIsInSearchList(&inQuestion->qname, mDNStrue))
                {
                    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
                           "[R%u] QueryRecordOpCallback: Question " PRI_DM_NAME " (" PUB_S ") answering local with negative unicast response",
                           op->reqID, DM_NAME_PARAM(&inQuestion->qname), DNSTypeName(inQuestion->qtype));
                }
                else
                {
                    goto exit;
                }
            }
#endif
            resultErr = kDNSServiceErr_NoSuchRecord;
        }
    }
    else
    {
        resultErr = kDNSServiceErr_NoError;
    }

#if MDNSRESPONDER_SUPPORTS(APPLE, REACHABILITY_TRIGGER)
    if ((resultErr != kDNSServiceErr_Timeout) && (inAddRecord == QC_add))
    {
        op->answered = mDNStrue;
    }
#endif

    if (op->resultHandler) op->resultHandler(m, inQuestion, inAnswer, inAddRecord, resultErr, op->resultContext);
    if (resultErr == kDNSServiceErr_Timeout) QueryRecordOpStopQuestion(inQuestion);

#if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
    NotifyWebContentFilter(inAnswer, inQuestion->euid);
#endif

exit:
    return;
}

mDNSlocal void QueryRecordOpResetHandler(DNSQuestion *inQuestion)
{
    QueryRecordOp *const        op = (QueryRecordOp *)inQuestion->QuestionContext;

    AssignDomainName(&inQuestion->qname, op->qname);
    if (inQuestion->AppendSearchDomains && DomainNameIsSingleLabel(op->qname))
    {
        inQuestion->InterfaceID = mDNSInterface_LocalOnly;
    }
    else
    {
        inQuestion->InterfaceID = op->interfaceID;
    }
    op->searchListIndex = 0;
}

mDNSlocal mStatus QueryRecordOpStartQuestion(QueryRecordOp *inOp, DNSQuestion *inQuestion)
{
    mStatus     err;

    inQuestion->QuestionContext = inOp;
    err = mDNS_StartQuery(&mDNSStorage, inQuestion);
    if (err)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%u] ERROR: QueryRecordOpStartQuestion mDNS_StartQuery for " PRI_DM_NAME " " PUB_S " failed with error %d",
               inOp->reqID, DM_NAME_PARAM(&inQuestion->qname), DNSTypeName(inQuestion->qtype), err);
        inQuestion->QuestionContext = mDNSNULL;
    }
    return err;
}

mDNSlocal mStatus QueryRecordOpStopQuestion(DNSQuestion *inQuestion)
{
    mStatus     err;

    err = mDNS_StopQuery(&mDNSStorage, inQuestion);
    inQuestion->QuestionContext = mDNSNULL;
    return err;
}

mDNSlocal mStatus QueryRecordOpRestartUnicastQuestion(QueryRecordOp *inOp, DNSQuestion *inQuestion,
    const domainname *inSearchDomain)
{
    mStatus     err;

    inQuestion->InterfaceID = inOp->interfaceID;
    AssignDomainName(&inQuestion->qname, inOp->qname);
    if (inSearchDomain) AppendDomainName(&inQuestion->qname, inSearchDomain);
    if (SameDomainLabel(LastLabel(&inQuestion->qname), (const mDNSu8 *)&localdomain))
    {
        inQuestion->IsUnicastDotLocal = mDNStrue;
    }
    else
    {
        inQuestion->IsUnicastDotLocal = mDNSfalse;
    }
    err = QueryRecordOpStartQuestion(inOp, inQuestion);
    return err;
}

mDNSlocal mStatus InterfaceIndexToInterfaceID(mDNSu32 inInterfaceIndex, mDNSInterfaceID *outInterfaceID)
{
    mStatus             err;
    mDNSInterfaceID     interfaceID;

    interfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, inInterfaceIndex);

#if MDNSRESPONDER_SUPPORTS(APPLE, UNREADY_INTERFACES)
    // The request is scoped to a specific interface index, but the interface is not currently in our list.
    if ((inInterfaceIndex != kDNSServiceInterfaceIndexAny) && (interfaceID == mDNSInterface_Any))
    {
        static dispatch_once_t      getLoopbackIndexOnce = 0;
        static mDNSu32              loopbackIndex = 0;

        dispatch_once(&getLoopbackIndexOnce,
        ^{
            loopbackIndex = if_nametoindex("lo0");
        });

        // If it's one of the specially defined inteface index values, just return an error. Also, caller should return an
        // error immediately if lo0 is not configured into the current active interfaces. See <rdar://problem/21967160>.
        if ((inInterfaceIndex == kDNSServiceInterfaceIndexLocalOnly) ||
            (inInterfaceIndex == kDNSServiceInterfaceIndexUnicast)   ||
            (inInterfaceIndex == kDNSServiceInterfaceIndexP2P)       ||
            (inInterfaceIndex == kDNSServiceInterfaceIndexBLE)       ||
            (inInterfaceIndex == loopbackIndex))
        {
            LogInfo("ERROR: bad interfaceIndex %d", inInterfaceIndex);
            err = mStatus_BadParamErr;
            goto exit;
        }

        // Otherwise, use the specified interface index value and the request will be applied to that interface when it
        // comes up.
        interfaceID = (mDNSInterfaceID)(uintptr_t)inInterfaceIndex;
        LogInfo("Query pending for interface index %d", inInterfaceIndex);
    }
#endif

    *outInterfaceID = interfaceID;
    err = mStatus_NoError;

#if MDNSRESPONDER_SUPPORTS(APPLE, UNREADY_INTERFACES)
exit:
#endif
    return err;
}

mDNSlocal mDNSBool DomainNameIsSingleLabel(const domainname *inName)
{
    const mDNSu8 *const     label = inName->c;
    return (((label[0] != 0) && (label[1 + label[0]] == 0)) ? mDNStrue : mDNSfalse);
}

mDNSlocal mDNSBool StringEndsWithDot(const char *inString)
{
    const char *        ptr;
    mDNSu32             escapeCount;
    mDNSBool            result;

    // Loop invariant: escapeCount is the number of consecutive escape characters that immediately precede *ptr.
    // - If escapeCount is even, then *ptr is immediately preceded by escapeCount / 2 consecutive literal backslash
    //   characters, so *ptr is not escaped.
    // - If escapeCount is odd, then *ptr is immediately preceded by (escapeCount - 1) / 2 consecutive literal backslash
    //   characters followed by an escape character, so *ptr is escaped.
    escapeCount = 0;
    result = mDNSfalse;
    for (ptr = inString; *ptr != '\0'; ptr++)
    {
        if (*ptr == '\\')
        {
            escapeCount++;
        }
        else
        {
            if ((*ptr == '.') && (ptr[1] == '\0'))
            {
                if ((escapeCount % 2) == 0) result = mDNStrue;
                break;
            }
            escapeCount = 0;
        }
    }
    return result;
}

mDNSlocal const domainname * NextSearchDomain(QueryRecordOp *inOp)
{
    const domainname *      domain;

    while ((domain = uDNS_GetNextSearchDomain(inOp->interfaceID, &inOp->searchListIndex, mDNSfalse)) != mDNSNULL)
    {
        if ((DomainNameLength(inOp->qname) - 1 + DomainNameLength(domain)) <= MAX_DOMAIN_NAME) break;
    }
    if (!domain) inOp->searchListIndex = -1;
    return domain;
}

#if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DOTLOCAL)
mDNSlocal mDNSBool DomainNameIsInSearchList(const domainname *inName, mDNSBool inExcludeLocal)
{
    const SearchListElem *      item;
    int                         labelCount, domainLabelCount;

    labelCount = CountLabels(inName);
    for (item = SearchList; item; item = item->next)
    {
        if (inExcludeLocal && SameDomainName(&item->domain, &localdomain)) continue;
        domainLabelCount = CountLabels(&item->domain);
        if (labelCount >= domainLabelCount)
        {
            if (SameDomainName(&item->domain, SkipLeadingLabels(inName, (labelCount - domainLabelCount))))
            {
                return mDNStrue;
            }
        }
    }
    return mDNSfalse;
}
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
mDNSlocal void NotifyWebContentFilter(const ResourceRecord *inAnswer, uid_t inUID)
{
    if (WCFIsServerRunning)
    {
		const mDNS *const m = &mDNSStorage;

        if (WCFIsServerRunning(m->WCF) && inAnswer->rdlength != 0)
        {
			struct sockaddr_storage addr;
			addr.ss_len = 0;
			if (inAnswer->rrtype == kDNSType_A || inAnswer->rrtype == kDNSType_AAAA)
			{
				if (inAnswer->rrtype == kDNSType_A)
				{
					struct sockaddr_in *const sin = (struct sockaddr_in *)&addr;
					sin->sin_port = 0;
					// Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
					// sin->sin_addr.s_addr = inAnswer->rdata->u.ipv4.NotAnInteger;
					if (!putRData(mDNSNULL, (mDNSu8 *)&sin->sin_addr, (mDNSu8 *)(&sin->sin_addr + sizeof(mDNSv4Addr)), inAnswer))
						LogMsg("NotifyWebContentFilter: WCF AF_INET putRData failed");
					else
					{
						addr.ss_len = sizeof (struct sockaddr_in);
						addr.ss_family = AF_INET;
					}
				}
				else if (inAnswer->rrtype == kDNSType_AAAA)
				{
					struct sockaddr_in6 *const sin6 = (struct sockaddr_in6 *)&addr;
					sin6->sin6_port = 0;
					// Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
					// sin6->sin6_addr.__u6_addr.__u6_addr32[0] = inAnswer->rdata->u.ipv6.l[0];
					// sin6->sin6_addr.__u6_addr.__u6_addr32[1] = inAnswer->rdata->u.ipv6.l[1];
					// sin6->sin6_addr.__u6_addr.__u6_addr32[2] = inAnswer->rdata->u.ipv6.l[2];
					// sin6->sin6_addr.__u6_addr.__u6_addr32[3] = inAnswer->rdata->u.ipv6.l[3];
					if (!putRData(mDNSNULL, (mDNSu8 *)&sin6->sin6_addr, (mDNSu8 *)(&sin6->sin6_addr + sizeof(mDNSv6Addr)), inAnswer))
						LogMsg("NotifyWebContentFilter: WCF AF_INET6 putRData failed");
					else
					{
						addr.ss_len = sizeof (struct sockaddr_in6);
						addr.ss_family = AF_INET6;
					}
				}
				if (addr.ss_len)
				{
        			char name[MAX_ESCAPED_DOMAIN_NAME];
        			ConvertDomainNameToCString(inAnswer->name, name);

					debugf("NotifyWebContentFilter: Name %s, uid %u, addr length %d", name, inUID, addr.ss_len);
					if (WCFNameResolvesToAddr)
					{
						WCFNameResolvesToAddr(m->WCF, name, (struct sockaddr *)&addr, inUID);
					}
				}
			}
			else if (inAnswer->rrtype == kDNSType_CNAME)
			{
				domainname cname;
        		char name[MAX_ESCAPED_DOMAIN_NAME];
				char cname_cstr[MAX_ESCAPED_DOMAIN_NAME];

				if (!putRData(mDNSNULL, cname.c, (mDNSu8 *)(cname.c + MAX_DOMAIN_NAME), inAnswer))
					LogMsg("NotifyWebContentFilter: WCF CNAME putRData failed");
				else
				{
        			ConvertDomainNameToCString(inAnswer->name, name);
					ConvertDomainNameToCString(&cname, cname_cstr);
					if (WCFNameResolvesToAddr)
					{
						WCFNameResolvesToName(m->WCF, name, cname_cstr, inUID);
					}
				}
			}
        }
    }
}
#endif
/*
 * Copyright (c) 2018-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.
 */

#ifndef __ClientRequests_h
#define __ClientRequests_h

#include "mDNSEmbeddedAPI.h"
#include "dns_sd_internal.h"

typedef void (*QueryRecordResultHandler)(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord,
    DNSServiceErrorType error, void *context);

typedef struct
{
    DNSQuestion                 q;                      // DNSQuestion for record query.
    domainname *                qname;                  // Name of the original record.
    mDNSInterfaceID             interfaceID;            // Interface over which to perform query.
    QueryRecordResultHandler    resultHandler;          // Handler for query record operation results.
    void *                      resultContext;          // Context to pass to result handler.
    mDNSu32                     reqID;                  // 
    int                         searchListIndex;        // Index that indicates the next search domain to try.
#if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DOTLOCAL)
    DNSQuestion *               q2;                     // DNSQuestion for unicast version of a record with a dot-local name.
    mDNSu16                     q2Type;                 // q2's original qtype value.
    mDNSBool                    q2LongLived;            // q2's original LongLived value.
    mDNSBool                    q2ReturnIntermed;       // q2's original ReturnIntermed value.
    mDNSBool                    q2TimeoutQuestion;      // q2's original TimeoutQuestion value.
    mDNSBool                    q2AppendSearchDomains;  // q2's original AppendSearchDomains value.
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, REACHABILITY_TRIGGER)
    mDNSBool                    answered;               // True if the query was answered.
#endif

}   QueryRecordOp;

typedef struct
{
    mDNSInterfaceID     interfaceID;    // InterfaceID being used for query record operations.
    mDNSu32             protocols;      // Protocols (IPv4, IPv6) specified by client.
    QueryRecordOp *     op4;            // Query record operation object for A record.
    QueryRecordOp *     op6;            // Query record operation object for AAAA record.

}   GetAddrInfoClientRequest;

typedef struct
{
    QueryRecordOp       op; // Query record operation object.

}   QueryRecordClientRequest;

typedef struct
{
    mDNSu32                 requestID;
    const char *            hostnameStr;
    mDNSu32                 interfaceIndex;
    DNSServiceFlags         flags;
    mDNSu32                 protocols;
    mDNSs32                 effectivePID;
    const mDNSu8 *          effectiveUUID;
    mDNSu32                 peerUID;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    mDNSBool                needEncryption;
    const mDNSu8 *          resolverUUID;
    mdns_dns_service_id_t   customID;
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    const audit_token_t *   peerAuditToken;
    const audit_token_t *   delegatorAuditToken;
    mDNSBool                isInAppBrowserRequest;
#endif

}   GetAddrInfoClientRequestParams;

typedef struct
{
    mDNSu32                 requestID;
    const char *            qnameStr;
    mDNSu32                 interfaceIndex;
    DNSServiceFlags         flags;
    mDNSu16                 qtype;
    mDNSu16                 qclass;
    mDNSs32                 effectivePID;
    const mDNSu8 *          effectiveUUID;
    mDNSu32                 peerUID;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    mDNSBool                needEncryption;
    const mDNSu8 *          resolverUUID;
	mdns_dns_service_id_t	customID;
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    const audit_token_t *   peerAuditToken;
    const audit_token_t *   delegatorAuditToken;
    mDNSBool                isInAppBrowserRequest;
#endif

}   QueryRecordClientRequestParams;

#ifdef __cplusplus
extern "C" {
#endif

mDNSexport void GetAddrInfoClientRequestParamsInit(GetAddrInfoClientRequestParams *inParams);
mDNSexport mStatus GetAddrInfoClientRequestStart(GetAddrInfoClientRequest *inRequest,
    const GetAddrInfoClientRequestParams *inParams, QueryRecordResultHandler inResultHandler, void *inResultContext);
mDNSexport void GetAddrInfoClientRequestStop(GetAddrInfoClientRequest *inRequest);
mDNSexport const domainname * GetAddrInfoClientRequestGetQName(const GetAddrInfoClientRequest *inRequest);
mDNSexport mDNSBool GetAddrInfoClientRequestIsMulticast(const GetAddrInfoClientRequest *inRequest);

mDNSexport void QueryRecordClientRequestParamsInit(QueryRecordClientRequestParams *inParams);
mDNSexport mStatus QueryRecordClientRequestStart(QueryRecordClientRequest *inRequest,
    const QueryRecordClientRequestParams *inParams, QueryRecordResultHandler inResultHandler, void *inResultContext);
mDNSexport void QueryRecordClientRequestStop(QueryRecordClientRequest *inRequest);
mDNSexport const domainname * QueryRecordClientRequestGetQName(const QueryRecordClientRequest *inRequest);
mDNSexport mDNSu16 QueryRecordClientRequestGetType(const QueryRecordClientRequest *inRequest);
mDNSexport mDNSBool QueryRecordClientRequestIsMulticast(QueryRecordClientRequest *inRequest);

#if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
// This is a "mDNSexport" wrapper around the "static" QueryRecordOpStart that cannot be called by outside, which can be
// called by the outside(dnssec related function).
mDNSexport mStatus QueryRecordOpStartForClientRequest(
    QueryRecordOp *             inOp,
    mDNSu32                     inReqID,
    const domainname *          inQName,
    mDNSu16                     inQType,
    mDNSu16                     inQClass,
    mDNSInterfaceID             inInterfaceID,
    mDNSs32                     inServiceID,
    mDNSu32                     inFlags,
    mDNSBool                    inAppendSearchDomains,
    mDNSs32                     inPID,
    const mDNSu8                inUUID[UUID_SIZE],
    mDNSu32                     inUID,
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    const audit_token_t *       inPeerAuditTokenPtr,
    const audit_token_t *       inDelegateAuditTokenPtr,
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    const mDNSu8                inResolverUUID[UUID_SIZE],
    mDNSBool                    inNeedEncryption,
    const mdns_dns_service_id_t inCustomID,
#endif
    QueryRecordResultHandler    inResultHandler,
    void *                      inResultContext);

mDNSexport void QueryRecordOpStopForClientRequest(QueryRecordOp *op);
#endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)

#ifdef __cplusplus
}
#endif

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

#include "GenLinkedList.h"


// Return the link pointer contained within element e at offset o.
#define     GETLINK( e, o)          ( *(void**)((char*) (e) + (o)) )

// Assign the link pointer l to element e at offset o.
#define     ASSIGNLINK( e, l, o)    ( *((void**)((char*) (e) + (o))) = (l))


//		GenLinkedList		/////////////////////////////////////////////////////////////

void        InitLinkedList( GenLinkedList *pList, size_t linkOffset)
/* Initialize the block of memory pointed to by pList as a linked list. */
{
    pList->Head = NULL;
    pList->Tail = NULL;
    pList->LinkOffset = linkOffset;
}


void        AddToTail( GenLinkedList *pList, void *elem)
/* Add a linked list element to the tail of the list. */
{
    if ( pList->Tail) {
        ASSIGNLINK( pList->Tail, elem, pList->LinkOffset);
    } else
        pList->Head = elem;
    ASSIGNLINK( elem, NULL, pList->LinkOffset);

    pList->Tail = elem;
}


void        AddToHead( GenLinkedList *pList, void *elem)
/* Add a linked list element to the head of the list. */
{
    ASSIGNLINK( elem, pList->Head, pList->LinkOffset);
    if ( pList->Tail == NULL)
        pList->Tail = elem;

    pList->Head = elem;
}


int     RemoveFromList( GenLinkedList *pList, void *elem)
/* Remove a linked list element from the list. Return 0 if it was not found. */
/* If the element is removed, its link will be set to NULL. */
{
    void    *iElem, *lastElem;

    for ( iElem = pList->Head, lastElem = NULL; iElem; iElem = GETLINK( iElem, pList->LinkOffset)) {
        if ( iElem == elem) {
            if ( lastElem) {        // somewhere past the head
                ASSIGNLINK( lastElem, GETLINK( elem, pList->LinkOffset), pList->LinkOffset);
            } else {                // at the head
                pList->Head = GETLINK( elem, pList->LinkOffset);
            }
            if ( pList->Tail == elem)
                pList->Tail = lastElem ? lastElem : NULL;
            ASSIGNLINK( elem, NULL, pList->LinkOffset);         // maybe catch a stale reference bug.
            return 1;
        }
        lastElem = iElem;
    }

    return 0;
}


int         ReplaceElem( GenLinkedList *pList, void *elemInList, void *newElem)
/* Replace an element in the list with a new element, in the same position. */
{
    void    *iElem, *lastElem;

    if ( elemInList == NULL || newElem == NULL)
        return 0;

    for ( iElem = pList->Head, lastElem = NULL; iElem; iElem = GETLINK( iElem, pList->LinkOffset))
    {
        if ( iElem == elemInList)
        {
            ASSIGNLINK( newElem, GETLINK( elemInList, pList->LinkOffset), pList->LinkOffset);
            if ( lastElem)      // somewhere past the head
            {
                ASSIGNLINK( lastElem, newElem, pList->LinkOffset);
            }
            else                // at the head
            {
                pList->Head = newElem;
            }
            if ( pList->Tail == elemInList)
                pList->Tail = newElem;
            return 1;
        }
        lastElem = iElem;
    }

    return 0;
}


//		GenDoubleLinkedList		/////////////////////////////////////////////////////////

void        InitDoubleLinkedList( GenDoubleLinkedList *pList, size_t fwdLinkOffset,
                                  size_t backLinkOffset)
/* Initialize the block of memory pointed to by pList as a double linked list. */
{
    pList->Head = NULL;
    pList->Tail = NULL;
    pList->FwdLinkOffset = fwdLinkOffset;
    pList->BackLinkOffset = backLinkOffset;
}


void            DLLAddToHead( GenDoubleLinkedList *pList, void *elem)
/* Add a linked list element to the head of the list. */
{
    void        *pNext;

    pNext = pList->Head;

    // fix up the forward links
    ASSIGNLINK( elem, pList->Head, pList->FwdLinkOffset);
    pList->Head = elem;

    // fix up the backward links
    if ( pNext) {
        ASSIGNLINK( pNext, elem, pList->BackLinkOffset);
    } else
        pList->Tail = elem;
    ASSIGNLINK( elem, NULL, pList->BackLinkOffset);
}


void            DLLRemoveFromList( GenDoubleLinkedList *pList, void *elem)
/* Remove a linked list element from the list. */
/* When the element is removed, its link will be set to NULL. */
{
    void        *pNext, *pPrev;

    pNext = GETLINK( elem, pList->FwdLinkOffset);
    pPrev = GETLINK( elem, pList->BackLinkOffset);

    // fix up the forward links
    if ( pPrev)
        ASSIGNLINK( pPrev, pNext, pList->FwdLinkOffset);
    else
        pList->Head = pNext;

    // fix up the backward links
    if ( pNext)
        ASSIGNLINK( pNext, pPrev, pList->BackLinkOffset);
    else
        pList->Tail = pPrev;

    ASSIGNLINK( elem, NULL, pList->FwdLinkOffset);
    ASSIGNLINK( elem, NULL, pList->BackLinkOffset);
}


//		GenLinkedOffsetList		/////////////////////////////////////////////////////

// Extract the Next offset from element
#define     GETOFFSET( e, o)    ( *(size_t*)((char*) (e) + (o)) )

static void     AssignOffsetLink( void *elem, void *link, size_t linkOffset);


static void AssignOffsetLink( void *elem, void *link, size_t linkOffset)
// Assign link to elem as an offset from elem. Assign 0 to elem if link is NULL.
{
    GETOFFSET( elem, linkOffset) = link ? (size_t) link - (size_t) elem : 0;
}


void        *GetHeadPtr( GenLinkedOffsetList *pList)
/* Return a pointer to the head element of a list, or NULL if none. */
{
    return pList->Head ? ( (char*) (pList) + pList->Head) : NULL;
}


void        *GetTailPtr( GenLinkedOffsetList *pList)
/* Return a pointer to the tail element of a list, or NULL if none. */
{
    return pList->Tail ? ( (char*) (pList) + pList->Tail) : NULL;
}


void        *GetOffsetLink( GenLinkedOffsetList *pList, void *elem)
/* Return the link pointer contained within element e for pList, or NULL if it is 0. */
{
    size_t nextOffset;

    nextOffset = GETOFFSET( elem, pList->LinkOffset);

    return nextOffset ? (char*) elem + nextOffset : NULL;
}


void        InitLinkedOffsetList( GenLinkedOffsetList *pList, size_t linkOffset)
/* Initialize the block of memory pointed to by pList as a linked list. */
{
    pList->Head = 0;
    pList->Tail = 0;
    pList->LinkOffset = linkOffset;
}


void        OffsetAddToTail( GenLinkedOffsetList *pList, void *elem)
/* Add a linked list element to the tail of the list. */
{
    if ( pList->Tail) {
        AssignOffsetLink( GetTailPtr( pList), elem, pList->LinkOffset);
    } else
        pList->Head = (size_t) elem - (size_t) pList;
    AssignOffsetLink( elem, NULL, pList->LinkOffset);

    pList->Tail = (size_t) elem - (size_t) pList;
}


void        OffsetAddToHead( GenLinkedOffsetList *pList, void *elem)
/* Add a linked list element to the head of the list. */
{
    AssignOffsetLink( elem, GetHeadPtr( pList), pList->LinkOffset);
    if ( pList->Tail == 0)
        pList->Tail = (size_t) elem - (size_t) pList;

    pList->Head = (size_t) elem - (size_t) pList;
}


int     OffsetRemoveFromList( GenLinkedOffsetList *pList, void *elem)
/* Remove a linked list element from the list. Return 0 if it was not found. */
/* If the element is removed, its link will be set to NULL. */
{
    void    *iElem, *lastElem;

    if (elem == NULL) {
        return 0;
    }
    for ( iElem = GetHeadPtr( pList), lastElem = NULL; iElem;
          iElem = GetOffsetLink( pList, iElem))
    {
        if ( iElem == elem) {
            if ( lastElem) {        // somewhere past the head
                AssignOffsetLink( lastElem, GetOffsetLink( pList, elem), pList->LinkOffset);
            } else {                // at the head
                iElem = GetOffsetLink( pList, elem);
                pList->Head = iElem ? (size_t) iElem - (size_t) pList : 0;
            }
            if ( GetTailPtr( pList) == elem)
                pList->Tail = lastElem ? (size_t) lastElem - (size_t) pList : 0;
            AssignOffsetLink( elem, NULL, pList->LinkOffset);   // maybe catch a stale reference bug.
            return 1;
        }
        lastElem = iElem;
    }

    return 0;
}


int         OffsetReplaceElem( GenLinkedOffsetList *pList, void *elemInList, void *newElem)
/* Replace an element in the list with a new element, in the same position. */
{
    void    *iElem, *lastElem;

    if ( elemInList == NULL || newElem == NULL)
        return 0;

    for ( iElem = GetHeadPtr( pList), lastElem = NULL; iElem;
          iElem = GetOffsetLink( pList, iElem))
    {
        if ( iElem == elemInList)
        {
            AssignOffsetLink( newElem, GetOffsetLink( pList, elemInList), pList->LinkOffset);
            if ( lastElem)      // somewhere past the head
            {
                AssignOffsetLink( lastElem, newElem, pList->LinkOffset);
            }
            else                // at the head
            {
                pList->Head = (size_t) newElem - (size_t) pList;
            }
            if ( GetTailPtr( pList) == elemInList)
                pList->Tail = (size_t) newElem - (size_t) pList;
            return 1;
        }
        lastElem = iElem;
    }

    return 0;
}


/* -*- Mode: C; tab-width: 4 -*-
 *
 * Copyright (c) 2003 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 __GenLinkedList__
#define __GenLinkedList__


#include <stddef.h>


struct  GenLinkedList
{
    void        *Head,
    *Tail;
    size_t LinkOffset;
};
typedef struct GenLinkedList GenLinkedList;


void        InitLinkedList( GenLinkedList *pList, size_t linkOffset);

void        AddToHead( GenLinkedList *pList, void *elem);
void        AddToTail( GenLinkedList *pList, void *elem);

int     RemoveFromList( GenLinkedList *pList, void *elem);

int     ReplaceElem( GenLinkedList *pList, void *elemInList, void *newElem);



struct  GenDoubleLinkedList
{
    void        *Head,
    *Tail;
    size_t FwdLinkOffset,
           BackLinkOffset;
};
typedef struct GenDoubleLinkedList GenDoubleLinkedList;


void        InitDoubleLinkedList( GenDoubleLinkedList *pList, size_t fwdLinkOffset,
                                  size_t backLinkOffset);

void        DLLAddToHead( GenDoubleLinkedList *pList, void *elem);

void        DLLRemoveFromList( GenDoubleLinkedList *pList, void *elem);



/* A GenLinkedOffsetList is like a GenLinkedList that stores the *Next field as a signed */
/* offset from the address of the beginning of the element, rather than as a pointer. */

struct  GenLinkedOffsetList
{
    size_t Head,
           Tail;
    size_t LinkOffset;
};
typedef struct GenLinkedOffsetList GenLinkedOffsetList;


void        InitLinkedOffsetList( GenLinkedOffsetList *pList, size_t linkOffset);

void        *GetHeadPtr( GenLinkedOffsetList *pList);
void        *GetTailPtr( GenLinkedOffsetList *pList);
void        *GetOffsetLink( GenLinkedOffsetList *pList, void *elem);

void        OffsetAddToHead( GenLinkedOffsetList *pList, void *elem);
void        OffsetAddToTail( GenLinkedOffsetList *pList, void *elem);

int     OffsetRemoveFromList( GenLinkedOffsetList *pList, void *elem);

int     OffsetReplaceElem( GenLinkedOffsetList *pList, void *elemInList, void *newElem);


#endif //	__GenLinkedList__
/* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*-
 *
 * Copyright (c) 2004-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.
 *
 * This file defines functions that are common to platforms with Posix APIs.
 * Current examples are mDNSMacOSX and mDNSPosix.
 */

#include <stdio.h>              // Needed for fopen() etc.
#include <unistd.h>             // Needed for close()
#include <stdlib.h>             // Needed for malloc()
#include <string.h>             // Needed for strlen() etc.
#include <errno.h>              // Needed for errno etc.
#include <sys/socket.h>         // Needed for socket() etc.
#include <netinet/in.h>         // Needed for sockaddr_in
#include <syslog.h>
#include <sys/fcntl.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <assert.h>

#if APPLE_OSX_mDNSResponder
#include <os/log.h>
#endif

#include "mDNSEmbeddedAPI.h"    // Defines the interface provided to the client layer above
#include "DNSCommon.h"
#include "PlatformCommon.h"

#ifdef NOT_HAVE_SOCKLEN_T
typedef unsigned int socklen_t;
#endif

#if MDNS_MALLOC_DEBUGGING
// We ONLY want this for malloc debugging--on a running production system we want to deal with
// malloc failures, not just die.   There is a small performance penalty for enabling these options
// as well, so they are all only appropriate for debugging.   The flags mean:
//
// A = warnings are errors
// X = abort on failure
// Z = sets J & R
// J = allocated memory is initialized to a pattern
// R causes realloc to always reallocate even if not needed

char _malloc_options[] = "AXZ";

mDNSlocal mDNSListValidator *listValidators;

mDNSexport void mDNSPlatformAddListValidator(mDNSListValidator *lv, mDNSListValidationFunction *lvf,
                                             const char *lvfName, void *context)
{
    mDNSPlatformMemZero(lv, sizeof *lv);
    lv->validator = lvf;
    lv->validationFunctionName = lvfName;
    lv->context = context;
    lv->next = listValidators;
    listValidators = lv;
}

mDNSlocal void validateLists(void)
{
    mDNSListValidator *vfp;
    // Check Unix Domain Socket client lists (uds_daemon.c)
    for (vfp = listValidators; vfp; vfp = vfp->next)
    {
        vfp->validator(vfp->context);
    }

    mDNSPlatformValidateLists();
}

#define kAllocMagic     0xDEAD1234
#define kGuardMagic     0xDEAD1234
#define kFreeMagic      0xDEADDEAD
#define kAllocLargeSize 32768

mDNSexport void *mallocL(const char *msg, mDNSu32 size)
{
    // Allocate space for two words of sanity checking data before the requested block and two words after.
    // Adjust the length for alignment.
    mDNSu32 *mem = malloc(sizeof(mDNSu32) * 4 + size);
    mDNSu32 guard[2];
    if (!mem)
    { LogMsg("malloc( %s : %u ) failed", msg, size); return(NULL); }
    else
    {
        mDNSu32 *after = (mDNSu32 *)((mDNSu8 *)(mem + 2) + size);
        if      (size > kAllocLargeSize)      LogMsg("malloc( %s : %lu ) @ %p suspiciously large", msg, size, &mem[2]);
        else if (MDNS_MALLOC_DEBUGGING >= 2)  LogMsg("malloc( %s : %lu ) @ %p",                    msg, size, &mem[2]);
        mem[  0] = kAllocMagic;
        guard[0] = kGuardMagic;
        mem[  1] = size;
        guard[1] = size;
        memcpy(after, &guard, sizeof guard);
        memset(&mem[2], 0xFF, size);
        validateLists();
        return(&mem[2]);
    }
}

mDNSexport void *callocL(const char *msg, mDNSu32 size)
{
    mDNSu32 guard[2];
    const mDNSu32 headerSize = 4 * sizeof(mDNSu32);
    
    // Allocate space for two words of sanity checking data before the requested block and two words after.
    // Adjust the length for alignment.
    mDNSu32 *mem = (mDNSu32 *)calloc(1, headerSize + size);
    if (!mem)
    { LogMsg("calloc( %s : %u ) failed", msg, size); return(NULL); }
    else
    {
        mDNSu32 *after = (mDNSu32 *)((mDNSu8 *)(mem + 2) + size);
        if      (size > kAllocLargeSize)     LogMsg("calloc( %s : %lu ) @ %p suspiciously large", msg, size, &mem[2]);
        else if (MDNS_MALLOC_DEBUGGING >= 2) LogMsg("calloc( %s : %lu ) @ %p",                    msg, size, &mem[2]);
        mem[  0] = kAllocMagic;
        guard[0] = kGuardMagic;
        mem[  1] = size;
        guard[1] = size;
        memcpy(after, guard, sizeof guard);
        validateLists();
        return(&mem[2]);
    }
}

mDNSexport void freeL(const char *msg, void *x)
{
    if (!x)
        LogMsg("free( %s @ NULL )!", msg);
    else
    {
        mDNSu32 *mem = ((mDNSu32 *)x) - 2;
        if      (mem[0] == kFreeMagic)  { LogMemCorruption("free( %s : %lu @ %p ) !!!! ALREADY DISPOSED !!!!", msg, mem[1], &mem[2]); return; }
        if      (mem[0] != kAllocMagic) { LogMemCorruption("free( %s : %lu @ %p ) !!!! NEVER ALLOCATED !!!!",  msg, mem[1], &mem[2]); return; }
        if      (mem[1] > kAllocLargeSize)          LogMsg("free( %s : %lu @ %p) suspiciously large",          msg, mem[1], &mem[2]);
        else if (MDNS_MALLOC_DEBUGGING >= 2)        LogMsg("free( %s : %ld @ %p)",                             msg, mem[1], &mem[2]);
        mDNSu32 *after = (mDNSu32 *)((mDNSu8 *)x + mem[1]);
        mDNSu32 guard[2];

        memcpy(guard, after, sizeof guard);
        if (guard[0] != kGuardMagic)    { LogMemCorruption("free( %s : %lu @ %p ) !!!! END GUARD OVERWRITE !!!!",
                                                           msg, mem[1], &mem[2]); return; }
        if (guard[1] != mem[1])         { LogMemCorruption("free( %s : %lu @ %p ) !!!! LENGTH MISMATCH !!!!",
                                                           msg, mem[1], &mem[2]); return; }
        mem[0] = kFreeMagic;
        memset(mem + 2, 0xFF, mem[1] + 2 * sizeof(mDNSu32));
        validateLists();
        free(mem);
    }
}

#endif

// Bind a UDP socket to find the source address to a destination
mDNSexport void mDNSPlatformSourceAddrForDest(mDNSAddr *const src, const mDNSAddr *const dst)
{
    union { struct sockaddr s; struct sockaddr_in a4; struct sockaddr_in6 a6; } addr;
    socklen_t len = sizeof(addr);
    socklen_t inner_len = 0;
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    src->type = mDNSAddrType_None;
    if (sock == -1) return;
    if (dst->type == mDNSAddrType_IPv4)
    {
        inner_len = sizeof(addr.a4);
        #ifndef NOT_HAVE_SA_LEN
        addr.a4.sin_len         = inner_len;
        #endif
        addr.a4.sin_family      = AF_INET;
        addr.a4.sin_port        = 1;    // Not important, any port will do
        addr.a4.sin_addr.s_addr = dst->ip.v4.NotAnInteger;
    }
    else if (dst->type == mDNSAddrType_IPv6)
    {
        inner_len = sizeof(addr.a6);
        #ifndef NOT_HAVE_SA_LEN
        addr.a6.sin6_len      = inner_len;
        #endif
        addr.a6.sin6_family   = AF_INET6;
        addr.a6.sin6_flowinfo = 0;
        addr.a6.sin6_port     = 1;  // Not important, any port will do
        addr.a6.sin6_addr     = *(struct in6_addr*)&dst->ip.v6;
        addr.a6.sin6_scope_id = 0;
    }
    else return;

    if ((connect(sock, &addr.s, inner_len)) < 0) {
	if (errno != ENETUNREACH)
		LogMsg("mDNSPlatformSourceAddrForDest: connect %#a failed errno %d (%s)", dst, errno,
		    strerror(errno));
	goto exit;
    }

    if ((getsockname(sock, &addr.s, &len)) < 0)
    { LogMsg("mDNSPlatformSourceAddrForDest: getsockname failed errno %d (%s)", errno, strerror(errno)); goto exit; }

    src->type = dst->type;
    if (dst->type == mDNSAddrType_IPv4) src->ip.v4.NotAnInteger = addr.a4.sin_addr.s_addr;
    else src->ip.v6 = *(mDNSv6Addr*)&addr.a6.sin6_addr;
exit:
    close(sock);
}

// dst must be at least MAX_ESCAPED_DOMAIN_NAME bytes, and option must be less than 32 bytes in length
mDNSlocal mDNSBool GetConfigOption(char *dst, const char *option, FILE *f)
{
    char buf[32+1+MAX_ESCAPED_DOMAIN_NAME]; // Option name, one space, option value
    size_t len = strlen(option);
    if (len + 1 + MAX_ESCAPED_DOMAIN_NAME > sizeof(buf)-1) { LogMsg("GetConfigOption: option %s too long", option); return mDNSfalse; }
    fseek(f, 0, SEEK_SET);  // set position to beginning of stream
    while (fgets(buf, sizeof(buf), f))      // Read at most sizeof(buf)-1 bytes from file, and append '\0' C-string terminator
    {
        if (!strncmp(buf, option, len))
        {
            strncpy(dst, buf + len + 1, MAX_ESCAPED_DOMAIN_NAME-1);
            if (dst[MAX_ESCAPED_DOMAIN_NAME-1]) dst[MAX_ESCAPED_DOMAIN_NAME-1] = '\0';
            len = strlen(dst);
            if (len && dst[len-1] == '\n') dst[len-1] = '\0';  // chop newline
            return mDNStrue;
        }
    }
    debugf("Option %s not set", option);
    return mDNSfalse;
}

mDNSexport void ReadDDNSSettingsFromConfFile(mDNS *const m, const char *const filename, domainname *const hostname, domainname *const domain, mDNSBool *DomainDiscoveryDisabled)
{
    char buf[MAX_ESCAPED_DOMAIN_NAME] = "";
    mStatus err;
    FILE *f = fopen(filename, "r");

    if (hostname) hostname->c[0] = 0;
    if (domain) domain->c[0] = 0;
    if (DomainDiscoveryDisabled) *DomainDiscoveryDisabled = mDNSfalse;

    if (f)
    {
        if (DomainDiscoveryDisabled && GetConfigOption(buf, "DomainDiscoveryDisabled", f) && !strcasecmp(buf, "true")) *DomainDiscoveryDisabled = mDNStrue;
        if (hostname && GetConfigOption(buf, "hostname", f) && !MakeDomainNameFromDNSNameString(hostname, buf)) goto badf;
        if (domain && GetConfigOption(buf, "zone", f) && !MakeDomainNameFromDNSNameString(domain, buf)) goto badf;
        buf[0] = 0;
        GetConfigOption(buf, "secret-64", f);  // failure means no authentication
        fclose(f);
        f = NULL;
    }
    else
    {
        if (errno != ENOENT) LogMsg("ERROR: Config file exists, but cannot be opened.");
        return;
    }

    if (domain && domain->c[0] && buf[0])
    {
        DomainAuthInfo *info = (DomainAuthInfo*) mDNSPlatformMemAllocateClear(sizeof(*info));
        // for now we assume keyname = service reg domain and we use same key for service and hostname registration
        err = mDNS_SetSecretForDomain(m, info, domain, domain, buf, NULL, 0);
        if (err) LogMsg("ERROR: mDNS_SetSecretForDomain returned %d for domain %##s", err, domain->c);
    }

    return;

badf:
    LogMsg("ERROR: malformatted config file");
    if (f) fclose(f);
}

#if MDNS_DEBUGMSGS
mDNSexport void mDNSPlatformWriteDebugMsg(const char *msg)
{
    fprintf(stderr,"%s\n", msg);
    fflush(stderr);
}
#endif

#if !MDNSRESPONDER_SUPPORTS(APPLE, OS_LOG)
mDNSexport void mDNSPlatformWriteLogMsg(const char *ident, const char *buffer, mDNSLogLevel_t loglevel)
{
#if APPLE_OSX_mDNSResponder && LogTimeStamps
    extern mDNS mDNSStorage;
    extern mDNSu32 mDNSPlatformClockDivisor;
    mDNSs32 t = mDNSStorage.timenow ? mDNSStorage.timenow : mDNSPlatformClockDivisor ? mDNS_TimeNow_NoLock(&mDNSStorage) : 0;
    int ms = ((t < 0) ? -t : t) % 1000;
#endif

    if (mDNS_DebugMode) // In debug mode we write to stderr
    {
#if APPLE_OSX_mDNSResponder && LogTimeStamps
        if (ident && ident[0] && mDNSPlatformClockDivisor)
            fprintf(stderr,"%8d.%03d: %s\n", (int)(t/1000), ms, buffer);
        else
#endif
        fprintf(stderr,"%s\n", buffer);
        fflush(stderr);
    }
    else                // else, in production mode, we write to syslog
    {
        static int log_inited = 0;

        int syslog_level;
        switch (loglevel)
        {
            case MDNS_LOG_FAULT:     syslog_level = LOG_ERR;     break;
            case MDNS_LOG_ERROR:     syslog_level = LOG_ERR;     break;
            case MDNS_LOG_WARNING:   syslog_level = LOG_WARNING; break;
            case MDNS_LOG_DEFAULT:   syslog_level = LOG_NOTICE;  break;
            case MDNS_LOG_INFO:      syslog_level = LOG_INFO;    break;
            case MDNS_LOG_DEBUG:     syslog_level = LOG_DEBUG;   break;
            default:                 syslog_level = LOG_NOTICE;  break;
        }

        if (!log_inited) { openlog(ident, LOG_CONS, LOG_DAEMON); log_inited++; }

#if APPLE_OSX_mDNSResponder && LogTimeStamps
        if (ident && ident[0] && mDNSPlatformClockDivisor)
            syslog(syslog_level, "%8d.%03d: %s", (int)(t/1000), ms, buffer);
        else
#endif
        {
            syslog(syslog_level, "%s", buffer);
        }
    }
}
#endif // !MDNSRESPONDER_SUPPORTS(APPLE, OS_LOG)

mDNSexport mDNSBool mDNSPosixTCPSocketSetup(int *fd, mDNSAddr_Type addrType, mDNSIPPort *port, mDNSIPPort *outTcpPort)
{
    int sa_family = (addrType == mDNSAddrType_IPv4) ? AF_INET : AF_INET6;
    int err;
    int sock;
    mDNSu32 lowWater = 15384;

    sock = socket(sa_family, SOCK_STREAM, IPPROTO_TCP);
    if (sock < 3)
    {
        if (errno != EAFNOSUPPORT)
        {
            LogMsg("mDNSPosixTCPSocketSetup: socket error %d errno %d (%s)", sock, errno, strerror(errno));
        }
        return mDNStrue;
    }
    *fd = sock;

    union
    {
        struct sockaddr sa;
        struct sockaddr_in sin;
        struct sockaddr_in6 sin6;
    } addr;
    // If port is not NULL, bind to it.
    if (port != NULL)
    {
        socklen_t len = (sa_family == AF_INET) ? sizeof (struct sockaddr_in) : sizeof (struct sockaddr_in6);
        mDNSPlatformMemZero(&addr, sizeof addr);

        addr.sa.sa_family = sa_family;
#ifndef NOT_HAVE_SA_LEN
	addr.sa.sa_len = len;
#endif
        if (sa_family == AF_INET6)
        {
            addr.sin6.sin6_port = port->NotAnInteger;
        }
        else
        {
            addr.sin.sin_port = port->NotAnInteger;
        }
        err = bind(sock, &addr.sa, len);
        if (err < 0)
        {
            LogMsg("mDNSPosixTCPSocketSetup getsockname: %s", strerror(errno));
            return mDNSfalse;
        }
    }

    socklen_t addrlen = sizeof addr;
    err = getsockname(sock, (struct sockaddr *)&addr, &addrlen);
    if (err < 0)
    {
        LogMsg("mDNSPosixTCPSocketSetup getsockname: %s", strerror(errno));
        return mDNSfalse;
    }
    if (sa_family == AF_INET6)
    {
        outTcpPort->NotAnInteger = addr.sin6.sin6_port;

    } else
    {
        outTcpPort->NotAnInteger = addr.sin.sin_port;
    }
    if (port)
        port->NotAnInteger = outTcpPort->NotAnInteger;

#ifdef TCP_NOTSENT_LOWAT
    err = setsockopt(sock, IPPROTO_TCP, TCP_NOTSENT_LOWAT, &lowWater, sizeof lowWater);
    if (err < 0)
    {
        LogMsg("mDNSPosixTCPSocketSetup: TCP_NOTSENT_LOWAT failed: %s", strerror(errno));
        return mDNSfalse;
    }
#endif

    return mDNStrue;
}

mDNSexport TCPSocket *mDNSPosixDoTCPListenCallback(int fd, mDNSAddr_Type addressType, TCPSocketFlags socketFlags,
                                             TCPAcceptedCallback callback, void *context)
{
    union
    {
        struct sockaddr_in6 sin6;
        struct sockaddr_in sin;
        struct sockaddr sa;
    } address;

    socklen_t slen = sizeof address;
    int remoteSock;
    mDNSAddr addr;
    mDNSIPPort port;
    TCPSocket *sock = mDNSNULL;
    int failed;
    char *nbp;
    int i;
    mDNSu32 lowWater = 16384;
    // When we remember our connection, we remember a name that we can print for logging.   But
    // since we are the listener in this case, we don't /have/ a name for it.   This buffer
    // is used to print the IP address into a human readable string which will serve that purpose
    // for this case.
    char namebuf[INET6_ADDRSTRLEN + 1 + 5 + 1];

    remoteSock = accept(fd, &address.sa, &slen);
    if (remoteSock < 0)
    {
        LogMsg("mDNSPosixDoTCPListenCallback: accept returned %d", remoteSock);
        goto out;
    }

    failed = fcntl(remoteSock, F_SETFL, O_NONBLOCK);
    if (failed < 0)
    {
        close(remoteSock);
        LogMsg("mDNSPosixDoTCPListenCallback: fcntl returned %d", errno);
        goto out;
    }

#ifdef TCP_NOTSENT_LOWAT
    failed = setsockopt(remoteSock, IPPROTO_TCP, TCP_NOTSENT_LOWAT,
                        &lowWater, sizeof lowWater);
    if (failed < 0)
    {
        close(remoteSock);
        LogMsg("mDNSPosixDoTCPListenCallback: TCP_NOTSENT_LOWAT returned %d", errno);
        goto out;
    }
#endif
    
    if (address.sa.sa_family == AF_INET6)
    {
        // If we are listening on an IPv4/IPv6 socket, the incoming address might be an IPv4-in-IPv6 address
        for (i = 0; i < 10; i++)
        {
            if (address.sin6.sin6_addr.s6_addr[i] != 0)
            {
                addr.type = mDNSAddrType_IPv6;
                goto nope;
            }
        }

        // a legit IPv4 address would be ::ffff:a.b.c.d; if there's no ::ffff bit, then it's an IPv6
        // address with a really weird prefix.
        if (address.sin6.sin6_addr.s6_addr[10] != 0xFF || address.sin6.sin6_addr.s6_addr[11] != 0xFF)
        {
            addr.type = mDNSAddrType_IPv6;
        } else if (addressType != mDNSAddrType_None)
        {
            if (inet_ntop(AF_INET, &address.sin6.sin6_addr.s6_addr[12], namebuf, INET6_ADDRSTRLEN + 1) == NULL)
            {
                strcpy(namebuf, ":unknown:");
            }
            LogMsg("mDNSPosixDoTCPListenCallback received an IPv4 connection from %s on an IPv6-only socket.",
                   namebuf);
            close(remoteSock);
            goto out;
        }
        else
        {
            addr.type = mDNSAddrType_IPv4;
        }
    nope:
        if (addr.type == mDNSAddrType_IPv6)
        {
            if (inet_ntop(address.sin6.sin6_family, &address.sin6.sin6_addr, namebuf, INET6_ADDRSTRLEN + 1) == NULL)
            {
                strcpy(namebuf, ":unknown:");
            }
            memcpy(&addr.ip.v6, &address.sin6.sin6_addr, sizeof addr.ip.v6);
        }
        else
        {
            if (inet_ntop(AF_INET, &address.sin6.sin6_addr.s6_addr[12], namebuf, INET6_ADDRSTRLEN + 1) == NULL)
            {
                strcpy(namebuf, ":unknown:");
            }
            memcpy(&addr.ip.v4, &address.sin6.sin6_addr.s6_addr[12], sizeof addr.ip.v4);
        }
        port.NotAnInteger = address.sin6.sin6_port;
    }
    else if (address.sa.sa_family == AF_INET)
    {
        addr.type = mDNSAddrType_IPv4;
        memcpy(&addr.ip.v4, &address.sin.sin_addr, sizeof addr.ip.v4);
        port.NotAnInteger = address.sin.sin_port;
        if (inet_ntop(AF_INET, &address.sin.sin_addr, namebuf, INET6_ADDRSTRLEN + 1) == NULL)
        {
            strcpy(namebuf, ":unknown:");
        }
    } else {
        LogMsg("mDNSPosixDoTCPListenCallback: connection from unknown address family %d", address.sa.sa_family);
        close(remoteSock);
        goto out;
    }
    nbp = namebuf + strlen(namebuf);
    *nbp++ = '%';
    snprintf(nbp, 6, "%u", ntohs(port.NotAnInteger));
             
    sock = mDNSPlatformTCPAccept(socketFlags, remoteSock);
    if (sock == NULL)
    {
        LogMsg("mDNSPosixDoTCPListenCallback: mDNSPlatformTCPAccept returned NULL; dropping connection from %s",
               namebuf);
        close(remoteSock);
        goto out;
    }
    callback(sock, &addr, &port, namebuf, context);
out:
    return sock;
}

mDNSexport mDNSBool mDNSPosixTCPListen(int *fd, mDNSAddr_Type addrtype, mDNSIPPort *port, mDNSAddr *addr,
                                       mDNSBool reuseAddr, int queueLength)

{
    union
    {
        struct sockaddr_in6 sin6;
        struct sockaddr_in sin;
        struct sockaddr sa;
    } address;

    int failed;
    int sock;
    int one = 1;
    socklen_t sock_len;

    // We require an addrtype parameter because addr is allowed to be null, but they have to agree.
    if (addr != mDNSNULL && addr->type != addrtype)
    {
        LogMsg("mDNSPlatformTCPListen: address type conflict: %d:%d", addr->type, addrtype);
        return mDNSfalse;
    }
    if (port == mDNSNULL)
    {
        LogMsg("mDNSPlatformTCPListen: port must not be NULL");
        return mDNSfalse;
    }

    mDNSPlatformMemZero(&address, sizeof address);
    if (addrtype == mDNSAddrType_None || addrtype == mDNSAddrType_IPv6)
    {
        // Set up DNS listener socket
        if (addr != mDNSNULL)
        {
            memcpy(&address.sin6.sin6_addr.s6_addr, &addr->ip, sizeof address.sin6.sin6_addr.s6_addr);
        }
        address.sin6.sin6_port = port->NotAnInteger;

        sock_len = sizeof address.sin6;
        address.sin6.sin6_family = AF_INET6;
    }
    else if (addrtype == mDNSAddrType_IPv4)
    {
        if (addr != mDNSNULL)
        {
            memcpy(&address.sin.sin_addr.s_addr, &addr->ip, sizeof address.sin.sin_addr.s_addr);
        }
        address.sin.sin_port = port->NotAnInteger;
        sock_len = sizeof address.sin;
        address.sin.sin_family = AF_INET;
    }
    else
    {
        LogMsg("mDNSPlatformTCPListen: invalid address type: %d", addrtype);
        return mDNSfalse;
    }
#ifndef NOT_HAVE_SA_LEN
    address.sa.sa_len = sock_len;
#endif
    sock = socket(address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);

    if (sock < 0)
    {
        LogMsg("mDNSPlatformTCPListen: socket call failed: %s", strerror(errno));
        return mDNSfalse;
    }
    *fd = sock;

    // The reuseAddr flag is used to indicate that we want to listen on this port even if
    // there are still lingering sockets.   We will still fail if there is another listener.
    // Note that this requires SO_REUSEADDR, not SO_REUSEPORT, which does not have special
    // handling for lingering sockets.
    if (reuseAddr)
    {
        failed = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
        if (failed < 0)
        {
            LogMsg("mDNSPlatformTCPListen: SO_REUSEADDR failed %s", strerror(errno));
            return mDNSfalse;
        }
    }

    // Bind to the port and (if provided) address
    failed = bind(sock, &address.sa, sock_len);
    if (failed < 0)
    {
        LogMsg("mDNSPlatformTCPListen: bind failed %s", strerror(errno));
        return mDNSfalse;
    }

    // If there was no specified listen port, we need to know what port we got.
    if (port->NotAnInteger == 0)
    {
        mDNSPlatformMemZero(&address, sizeof address);
        failed = getsockname(sock, &address.sa, &sock_len);
        if (failed < 0)
        {
            LogMsg("mDNSRelay: getsockname failed: %s", strerror(errno));
            return mDNSfalse;
        }
        if (address.sa.sa_family == AF_INET)
        {
            port->NotAnInteger = address.sin.sin_port;
        }
        else
        {
            port->NotAnInteger = address.sin6.sin6_port;
        }
    }

    failed = listen(sock, queueLength);
    if (failed < 0)
    {
        LogMsg("mDNSPlatformTCPListen: listen failed: %s", strerror(errno));
        return mDNSfalse;
    }
    return mDNStrue;
}

mDNSexport long mDNSPosixReadTCP(int fd, void *buf, unsigned long buflen, mDNSBool *closed)
{
    static int CLOSEDcount = 0;
    static int EAGAINcount = 0;
    ssize_t nread = recv(fd, buf, buflen, 0);

    if (nread > 0)
    {
        CLOSEDcount = 0; 
        EAGAINcount = 0; 
    } // On success, clear our error counters
    else if (nread == 0)
    {
        *closed = mDNStrue;
        if ((++CLOSEDcount % 20) == 0)
        {
            LogMsg("ERROR: mDNSPosixReadFromSocket - recv %d got CLOSED %d times", fd, CLOSEDcount); 
            assert(CLOSEDcount < 1000);
            // Recovery Mechanism to bail mDNSResponder out of trouble: Instead of logging the same error
            // msg multiple times, crash mDNSResponder using assert() and restart fresh. See advantages
            // below:
            // 1.Better User Experience 
            // 2.CrashLogs frequency can be monitored 
            // 3.StackTrace can be used for more info
        }
    }
    // else nread is negative -- see what kind of error we got
    else if (errno == ECONNRESET)
    {
        nread = 0; *closed = mDNStrue;
    }
    else if (errno != EAGAIN)
    {
        LogMsg("ERROR: mDNSPosixReadFromSocket - recv: %d (%s)", errno, strerror(errno));
        nread = -1;
    }
    else
    { // errno is EAGAIN (EWOULDBLOCK) -- no data available
        nread = 0;
        if ((++EAGAINcount % 1000) == 0)
        {
            LogMsg("ERROR: mDNSPosixReadFromSocket - recv %d got EAGAIN %d times", fd, EAGAINcount);
            sleep(1);
        }
    }
    return nread;
}

mDNSexport long mDNSPosixWriteTCP(int fd, const char *msg, unsigned long len)
{
    ssize_t result;
    long nsent;

    result = write(fd, msg, len);
    if (result < 0)
    {
        if (errno == EAGAIN)
        {
            nsent = 0;
        }
        else
        {
            LogMsg("ERROR: mDNSPosixWriteTCP - send %s", strerror(errno)); nsent = -1;
        }
    }
    else
    {
        nsent = (long)result;
    }
    return nsent;
}
/* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*-
 *
 * Copyright (c) 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 __PLATFORM_COMMON_H
#define __PLATFORM_COMMON_H
extern void ReadDDNSSettingsFromConfFile(mDNS *const m, const char *const filename,
										 domainname *const hostname, domainname *const domain,
										 mDNSBool *DomainDiscoveryDisabled);
extern mDNSBool mDNSPosixTCPSocketSetup(int *fd, mDNSAddr_Type addrType, mDNSIPPort *port, mDNSIPPort *outTcpPort);
extern TCPSocket *mDNSPosixDoTCPListenCallback(int fd, mDNSAddr_Type addressType, TCPSocketFlags socketFlags,
                     TCPAcceptedCallback callback, void *context);
extern mDNSBool mDNSPosixTCPListen(int *fd, mDNSAddr_Type addrtype, mDNSIPPort *port, mDNSAddr *addr,
                   mDNSBool reuseAddr, int queueLength);
extern long mDNSPosixReadTCP(int fd, void *buf, unsigned long buflen, mDNSBool *closed);
extern long mDNSPosixWriteTCP(int fd, const char *msg, unsigned long len);
#endif
/* -*- Mode: C; tab-width: 4 -*-
 *
 * Copyright (c) 2003-2018 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Inc. ("Apple") nor the names of its
 *     contributors may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


/*! @header     DNS Service Discovery
 *
 * @discussion  This section describes the functions, callbacks, and data structures
 *              that make up the DNS Service Discovery API.
 *
 *              The DNS Service Discovery API is part of Bonjour, Apple's implementation
 *              of zero-configuration networking (ZEROCONF).
 *
 *              Bonjour allows you to register a network service, such as a
 *              printer or file server, so that it can be found by name or browsed
 *              for by service type and domain. Using Bonjour, applications can
 *              discover what services are available on the network, along with
 *              all the information -- such as name, IP address, and port --
 *              necessary to access a particular service.
 *
 *              In effect, Bonjour combines the functions of a local DNS server and
 *              AppleTalk. Bonjour allows applications to provide user-friendly printer
 *              and server browsing, among other things, over standard IP networks.
 *              This behavior is a result of combining protocols such as multicast and
 *              DNS to add new functionality to the network (such as multicast DNS).
 *
 *              Bonjour gives applications easy access to services over local IP
 *              networks without requiring the service or the application to support
 *              an AppleTalk or a Netbeui stack, and without requiring a DNS server
 *              for the local network.
 */

/* _DNS_SD_H contains the API version number for this header file
 * The API version defined in this header file symbol allows for compile-time
 * checking, so that C code building with earlier versions of the header file
 * can avoid compile errors trying to use functions that aren't even defined
 * in those earlier versions. Similar checks may also be performed at run-time:
 *  => weak linking -- to avoid link failures if run with an earlier
 *     version of the library that's missing some desired symbol, or
 *  => DNSServiceGetProperty(DaemonVersion) -- to verify whether the running daemon
 *     ("system service" on Windows) meets some required minimum functionality level.
 */

#ifndef _DNS_SD_H
#define _DNS_SD_H 13108001

#ifdef  __cplusplus
extern "C" {
#endif

/* Set to 1 if libdispatch is supported
 * Note: May also be set by project and/or Makefile
 */
#if defined(__APPLE__)
#define _DNS_SD_LIBDISPATCH 1
#else
#define _DNS_SD_LIBDISPATCH 0
#endif

/* standard calling convention under Win32 is __stdcall */
/* Note: When compiling Intel EFI (Extensible Firmware Interface) under MS Visual Studio, the */
/* _WIN32 symbol is defined by the compiler even though it's NOT compiling code for Windows32 */
#if defined(_WIN32) && !defined(EFI32) && !defined(EFI64)
#define DNSSD_API __stdcall
#else
#define DNSSD_API
#endif

#if (defined(__GNUC__) && (__GNUC__ >= 4))
#define DNSSD_EXPORT __attribute__((visibility("default")))
#else
#define DNSSD_EXPORT
#endif

#if defined(_WIN32)
#include <winsock2.h>
typedef SOCKET dnssd_sock_t;
#else
typedef int dnssd_sock_t;
#endif

/* stdint.h does not exist on FreeBSD 4.x; its types are defined in sys/types.h instead */
#if defined(__FreeBSD__) && (__FreeBSD__ < 5)
#include <sys/types.h>

/* Likewise, on Sun, standard integer types are in sys/types.h */
#elif defined(__sun__)
#include <sys/types.h>

/* EFI does not have stdint.h, or anything else equivalent */
#elif defined(EFI32) || defined(EFI64) || defined(EFIX64)
#include "Tiano.h"
#if !defined(_STDINT_H_)
typedef UINT8 uint8_t;
typedef INT8 int8_t;
typedef UINT16 uint16_t;
typedef INT16 int16_t;
typedef UINT32 uint32_t;
typedef INT32 int32_t;
#endif
/* Windows has its own differences */
#elif defined(_WIN32)
#include <windows.h>
#define _UNUSED
#ifndef _MSL_STDINT_H
typedef UINT8 uint8_t;
typedef INT8 int8_t;
typedef UINT16 uint16_t;
typedef INT16 int16_t;
typedef UINT32 uint32_t;
typedef INT32 int32_t;
#endif

/* All other Posix platforms use stdint.h */
#else
#include <stdint.h>
#endif

#if _DNS_SD_LIBDISPATCH
#include <dispatch/dispatch.h>
#endif

/* DNSServiceRef, DNSRecordRef
 *
 * Opaque internal data types.
 * Note: client is responsible for serializing access to these structures if
 * they are shared between concurrent threads.
 */

typedef struct _DNSServiceRef_t *DNSServiceRef;
typedef struct _DNSRecordRef_t *DNSRecordRef;

struct sockaddr;

/*! @enum General flags
 * Most DNS-SD API functions and callbacks include a DNSServiceFlags parameter.
 * As a general rule, any given bit in the 32-bit flags field has a specific fixed meaning,
 * regardless of the function or callback being used. For any given function or callback,
 * typically only a subset of the possible flags are meaningful, and all others should be zero.
 * The discussion section for each API call describes which flags are valid for that call
 * and callback. In some cases, for a particular call, it may be that no flags are currently
 * defined, in which case the DNSServiceFlags parameter exists purely to allow future expansion.
 * In all cases, developers should expect that in future releases, it is possible that new flag
 * values will be defined, and write code with this in mind. For example, code that tests
 *     if (flags == kDNSServiceFlagsAdd) ...
 * will fail if, in a future release, another bit in the 32-bit flags field is also set.
 * The reliable way to test whether a particular bit is set is not with an equality test,
 * but with a bitwise mask:
 *     if (flags & kDNSServiceFlagsAdd) ...
 * With the exception of kDNSServiceFlagsValidate, each flag can be valid(be set)
 * EITHER only as an input to one of the DNSService*() APIs OR only as an output
 * (provide status) through any of the callbacks used. For example, kDNSServiceFlagsAdd
 * can be set only as an output in the callback, whereas the kDNSServiceFlagsIncludeP2P
 * can be set only as an input to the DNSService*() APIs. See comments on kDNSServiceFlagsValidate
 * defined in enum below.
 */
enum
{
    kDNSServiceFlagsMoreComing          = 0x1,
    /* MoreComing indicates to a callback that at least one more result is
     * queued and will be delivered following immediately after this one.
     * When the MoreComing flag is set, applications should not immediately
     * update their UI, because this can result in a great deal of ugly flickering
     * on the screen, and can waste a great deal of CPU time repeatedly updating
     * the screen with content that is then immediately erased, over and over.
     * Applications should wait until MoreComing is not set, and then
     * update their UI when no more changes are imminent.
     * When MoreComing is not set, that doesn't mean there will be no more
     * answers EVER, just that there are no more answers immediately
     * available right now at this instant. If more answers become available
     * in the future they will be delivered as usual.
     */

    kDNSServiceFlagsAutoTrigger        = 0x1,
    /* Valid for browses using kDNSServiceInterfaceIndexAny.
     * Will auto trigger the browse over AWDL as well once the service is discovered
     * over BLE.
     * This flag is an input value to DNSServiceBrowse(), which is why we can
     * use the same value as kDNSServiceFlagsMoreComing, which is an output flag
     * for various client callbacks.
    */

    kDNSServiceFlagsAdd                 = 0x2,
    kDNSServiceFlagsDefault             = 0x4,
    /* Flags for domain enumeration and browse/query reply callbacks.
     * "Default" applies only to enumeration and is only valid in
     * conjunction with "Add". An enumeration callback with the "Add"
     * flag NOT set indicates a "Remove", i.e. the domain is no longer
     * valid.
     */

    kDNSServiceFlagsNoAutoRename        = 0x8,
    /* Flag for specifying renaming behavior on name conflict when registering
     * non-shared records. By default, name conflicts are automatically handled
     * by renaming the service. NoAutoRename overrides this behavior - with this
     * flag set, name conflicts will result in a callback. The NoAutorename flag
     * is only valid if a name is explicitly specified when registering a service
     * (i.e. the default name is not used.)
     */

    kDNSServiceFlagsShared              = 0x10,
    kDNSServiceFlagsUnique              = 0x20,
    /* Flag for registering individual records on a connected
     * DNSServiceRef. Shared indicates that there may be multiple records
     * with this name on the network (e.g. PTR records). Unique indicates that the
     * record's name is to be unique on the network (e.g. SRV records).
     */

    kDNSServiceFlagsBrowseDomains       = 0x40,
    kDNSServiceFlagsRegistrationDomains = 0x80,
    /* Flags for specifying domain enumeration type in DNSServiceEnumerateDomains.
     * BrowseDomains enumerates domains recommended for browsing, RegistrationDomains
     * enumerates domains recommended for registration.
     */

    kDNSServiceFlagsLongLivedQuery      = 0x100,
    /* Flag for creating a long-lived unicast query for the DNSServiceQueryRecord call. */

    kDNSServiceFlagsAllowRemoteQuery    = 0x200,
    /* Flag for creating a record for which we will answer remote queries
     * (queries from hosts more than one hop away; hosts not directly connected to the local link).
     */

    kDNSServiceFlagsForceMulticast      = 0x400,
    /* Flag for signifying that a query or registration should be performed exclusively via multicast
     * DNS, even for a name in a domain (e.g. foo.apple.com.) that would normally imply unicast DNS.
     */

    kDNSServiceFlagsForce               = 0x800,    // This flag is deprecated.

    kDNSServiceFlagsKnownUnique         = 0x800,
    /*
     * Client guarantees that record names are unique, so we can skip sending out initial
     * probe messages.  Standard name conflict resolution is still done if a conflict is discovered.
     */

    kDNSServiceFlagsReturnIntermediates = 0x1000,
    /* Flag for returning intermediate results.
     * For example, if a query results in an authoritative NXDomain (name does not exist)
     * then that result is returned to the client. However the query is not implicitly
     * cancelled -- it remains active and if the answer subsequently changes
     * (e.g. because a VPN tunnel is subsequently established) then that positive
     * result will still be returned to the client.
     * Similarly, if a query results in a CNAME record, then in addition to following
     * the CNAME referral, the intermediate CNAME result is also returned to the client.
     * When this flag is not set, NXDomain errors are not returned, and CNAME records
     * are followed silently without informing the client of the intermediate steps.
     * (In earlier builds this flag was briefly calledkDNSServiceFlagsReturnCNAME)
     */

    kDNSServiceFlagsShareConnection     = 0x4000,
    /* For efficiency, clients that perform many concurrent operations may want to use a
     * single Unix Domain Socket connection with the background daemon, instead of having a
     * separate connection for each independent operation. To use this mode, clients first
     * call DNSServiceCreateConnection(&SharedRef) to initialize the main DNSServiceRef.
     * For each subsequent operation that is to share that same connection, the client copies
     * the SharedRef, and then passes the address of that copy, setting the ShareConnection flag
     * to tell the library that this DNSServiceRef is not a typical uninitialized DNSServiceRef;
     * it's a copy of an existing DNSServiceRef whose connection information should be reused.
     *
     * For example:
     *
     * DNSServiceErrorType error;
     * DNSServiceRef SharedRef;
     * error = DNSServiceCreateConnection(&SharedRef);
     * if (error) ...
     * DNSServiceRef BrowseRef = SharedRef;  // Important: COPY the primary DNSServiceRef first...
     * error = DNSServiceBrowse(&BrowseRef, kDNSServiceFlagsShareConnection, ...); // then use the copy
     * if (error) ...
     * ...
     * DNSServiceRefDeallocate(BrowseRef); // Terminate the browse operation
     * DNSServiceRefDeallocate(SharedRef); // Terminate the shared connection
     *
     * Notes:
     *
     * 1. Collective kDNSServiceFlagsMoreComing flag
     * When callbacks are invoked using a shared DNSServiceRef, the
     * kDNSServiceFlagsMoreComing flag applies collectively to *all* active
     * operations sharing the same parent DNSServiceRef. If the MoreComing flag is
     * set it means that there are more results queued on this parent DNSServiceRef,
     * but not necessarily more results for this particular callback function.
     * The implication of this for client programmers is that when a callback
     * is invoked with the MoreComing flag set, the code should update its
     * internal data structures with the new result, and set a variable indicating
     * that its UI needs to be updated. Then, later when a callback is eventually
     * invoked with the MoreComing flag not set, the code should update *all*
     * stale UI elements related to that shared parent DNSServiceRef that need
     * updating, not just the UI elements related to the particular callback
     * that happened to be the last one to be invoked.
     *
     * 2. Canceling operations and kDNSServiceFlagsMoreComing
     * Whenever you cancel any operation for which you had deferred UI updates
     * waiting because of a kDNSServiceFlagsMoreComing flag, you should perform
     * those deferred UI updates. This is because, after cancelling the operation,
     * you can no longer wait for a callback *without* MoreComing set, to tell
     * you do perform your deferred UI updates (the operation has been canceled,
     * so there will be no more callbacks). An implication of the collective
     * kDNSServiceFlagsMoreComing flag for shared connections is that this
     * guideline applies more broadly -- any time you cancel an operation on
     * a shared connection, you should perform all deferred UI updates for all
     * operations sharing that connection. This is because the MoreComing flag
     * might have been referring to events coming for the operation you canceled,
     * which will now not be coming because the operation has been canceled.
     *
     * 3. Only share DNSServiceRef's created with DNSServiceCreateConnection
     * Calling DNSServiceCreateConnection(&ref) creates a special shareable DNSServiceRef.
     * DNSServiceRef's created by other calls like DNSServiceBrowse() or DNSServiceResolve()
     * cannot be shared by copying them and using kDNSServiceFlagsShareConnection.
     *
     * 4. Don't Double-Deallocate
     * Calling DNSServiceRefDeallocate(OpRef) for a particular operation's DNSServiceRef terminates
     * just that operation. Calling DNSServiceRefDeallocate(SharedRef) for the main shared DNSServiceRef
     * (the parent DNSServiceRef, originally created by DNSServiceCreateConnection(&SharedRef))
     * automatically terminates the shared connection *and* all operations that were still using it.
     * After doing this, DO NOT then attempt to deallocate any remaining subordinate DNSServiceRef's.
     * The memory used by those subordinate DNSServiceRef's has already been freed, so any attempt
     * to do a DNSServiceRefDeallocate (or any other operation) on them will result in accesses
     * to freed memory, leading to crashes or other equally undesirable results.
     * You can deallocate individual operations first and then deallocate the parent DNSServiceRef last,
     * but if you deallocate the parent DNSServiceRef first, then all of the subordinate DNSServiceRef's
     * are implicitly deallocated, and explicitly deallocating them a second time will lead to crashes.
     *
     * 5. Thread Safety
     * The dns_sd.h API does not presuppose any particular threading model, and consequently
     * does no locking internally (which would require linking with a specific threading library).
     * If the client concurrently, from multiple threads (or contexts), calls API routines using
     * the same DNSServiceRef, it is the client's responsibility to provide mutual exclusion for
     * that DNSServiceRef.
     *
     * For example, use of DNSServiceRefDeallocate requires caution. A common mistake is as follows:
     * Thread B calls DNSServiceRefDeallocate to deallocate sdRef while Thread A is processing events
     * using sdRef. Doing this will lead to intermittent crashes on thread A if the sdRef is used after
     * it was deallocated.
     *
     * A telltale sign of this crash type is to see DNSServiceProcessResult on the stack preceding the
     * actual crash location.
     *
     * To state this more explicitly, mDNSResponder does not queue DNSServiceRefDeallocate so
     * that it occurs discretely before or after an event is handled.
     */

    kDNSServiceFlagsSuppressUnusable    = 0x8000,
    /*
     * This flag is meaningful only in DNSServiceQueryRecord which suppresses unusable queries on the
     * wire. If "hostname" is a wide-area unicast DNS hostname (i.e. not a ".local." name)
     * but this host has no routable IPv6 address, then the call will not try to look up IPv6 addresses
     * for "hostname", since any addresses it found would be unlikely to be of any use anyway. Similarly,
     * if this host has no routable IPv4 address, the call will not try to look up IPv4 addresses for
     * "hostname".
     */

    kDNSServiceFlagsTimeout            = 0x10000,
    /*
     * When kDNServiceFlagsTimeout is passed to DNSServiceQueryRecord or DNSServiceGetAddrInfo, the query is
     * stopped after a certain number of seconds have elapsed. The time at which the query will be stopped
     * is determined by the system and cannot be configured by the user. The query will be stopped irrespective
     * of whether a response was given earlier or not. When the query is stopped, the callback will be called
     * with an error code of kDNSServiceErr_Timeout and a NULL sockaddr will be returned for DNSServiceGetAddrInfo
     * and zero length rdata will be returned for DNSServiceQueryRecord.
     */

    kDNSServiceFlagsIncludeP2P          = 0x20000,
    /*
     * Include P2P interfaces when kDNSServiceInterfaceIndexAny is specified.
     * By default, specifying kDNSServiceInterfaceIndexAny does not include P2P interfaces.
     */

    kDNSServiceFlagsWakeOnResolve      = 0x40000,
    /*
    * This flag is meaningful only in DNSServiceResolve. When set, it tries to send a magic packet
    * to wake up the client.
    */

    kDNSServiceFlagsBackgroundTrafficClass  = 0x80000,
    /*
    * This flag is meaningful for Unicast DNS queries. When set, it uses the background traffic
    * class for packets that service the request.
    */

    kDNSServiceFlagsIncludeAWDL      = 0x100000,
   /*
    * Include AWDL interface when kDNSServiceInterfaceIndexAny is specified.
    */

    kDNSServiceFlagsEnableDNSSEC           = 0x200000,
    /*
     * Perform DNSSEC validation on the client request when kDNSServiceFlagsEnableDNSSEC is specified
     * Since the client API has not been finalized, we will use it as a temporary flag to turn on the DNSSEC validation.
     */

    kDNSServiceFlagsValidate               = 0x200000,
   /*
    * This flag is meaningful in DNSServiceGetAddrInfo and DNSServiceQueryRecord. This is the ONLY flag to be valid
    * as an input to the APIs and also an output through the callbacks in the APIs.
    *
    * When this flag is passed to DNSServiceQueryRecord and DNSServiceGetAddrInfo to resolve unicast names,
    * the response  will be validated using DNSSEC. The validation results are delivered using the flags field in
    * the callback and kDNSServiceFlagsValidate is marked in the flags to indicate that DNSSEC status is also available.
    * When the callback is called to deliver the query results, the validation results may or may not be available.
    * If it is not delivered along with the results, the validation status is delivered when the validation completes.
    *
    * When the validation results are delivered in the callback, it is indicated by marking the flags with
    * kDNSServiceFlagsValidate and kDNSServiceFlagsAdd along with the DNSSEC status flags (described below) and a NULL
    * sockaddr will be returned for DNSServiceGetAddrInfo and zero length rdata will be returned for DNSServiceQueryRecord.
    * DNSSEC validation results are for the whole RRSet and not just individual records delivered in the callback. When
    * kDNSServiceFlagsAdd is not set in the flags, applications should implicitly assume that the DNSSEC status of the
    * RRSet that has been delivered up until that point is not valid anymore, till another callback is called with
    * kDNSServiceFlagsAdd and kDNSServiceFlagsValidate.
    *
    * The following four flags indicate the status of the DNSSEC validation and marked in the flags field of the callback.
    * When any of the four flags is set, kDNSServiceFlagsValidate will also be set. To check the validation status, the 
    * other applicable output flags should be masked.
    */

    kDNSServiceFlagsSecure                 = 0x200010,
   /*
    * The response has been validated by verifying all the signatures in the response and was able to
    * build a successful authentication chain starting from a known trust anchor.
    */

    kDNSServiceFlagsInsecure               = 0x200020,
   /*
    * A chain of trust cannot be built starting from a known trust anchor to the response.
    */

    kDNSServiceFlagsBogus                  = 0x200040,
   /*
    * If the response cannot be verified to be secure due to expired signatures, missing signatures etc.,
    * then the results are considered to be bogus.
    */

    kDNSServiceFlagsIndeterminate          = 0x200080,
   /*
    * There is no valid trust anchor that can be used to determine whether a response is secure or not.
    */

    kDNSServiceFlagsUnicastResponse        = 0x400000,
   /*
    * Request unicast response to query.
    */
    kDNSServiceFlagsValidateOptional       = 0x800000,

    /*
     * This flag is identical to kDNSServiceFlagsValidate except for the case where the response
     * cannot be validated. If this flag is set in DNSServiceQueryRecord or DNSServiceGetAddrInfo,
     * the DNSSEC records will be requested for validation. If they cannot be received for some reason
     * during the validation (e.g., zone is not signed, zone is signed but cannot be traced back to
     * root, recursive server does not understand DNSSEC etc.), then this will fallback to the default
     * behavior where the validation will not be performed and no DNSSEC results will be provided.
     *
     * If the zone is signed and there is a valid path to a known trust anchor configured in the system
     * and the application requires DNSSEC validation irrespective of the DNSSEC awareness in the current
     * network, then this option MUST not be used. This is only intended to be used during the transition
     * period where the different nodes participating in the DNS resolution may not understand DNSSEC or
     * managed properly (e.g. missing DS record) but still want to be able to resolve DNS successfully.
     */

    kDNSServiceFlagsWakeOnlyService        = 0x1000000,
    /*
     * This flag is meaningful only in DNSServiceRegister. When set, the service will not be registered
     * with sleep proxy server during sleep.
     */

    kDNSServiceFlagsThresholdOne           = 0x2000000,
    kDNSServiceFlagsThresholdFinder        = 0x4000000,
    kDNSServiceFlagsThresholdReached       = kDNSServiceFlagsThresholdOne,
    /*
     * kDNSServiceFlagsThresholdOne is meaningful only in DNSServiceBrowse. When set,
     * the system will stop issuing browse queries on the network once the number
     * of answers returned is one or more.  It will issue queries on the network
     * again if the number of answers drops to zero.
     * This flag is for Apple internal use only. Third party developers
     * should not rely on this behavior being supported in any given software release.
     *
     * kDNSServiceFlagsThresholdFinder is meaningful only in DNSServiceBrowse. When set,
     * the system will stop issuing browse queries on the network once the number
     * of answers has reached the threshold set for Finder.
     * It will issue queries on the network again if the number of answers drops below
     * this threshold.
     * This flag is for Apple internal use only. Third party developers
     * should not rely on this behavior being supported in any given software release.
     *
     * When kDNSServiceFlagsThresholdReached is set in the client callback add or remove event,
     * it indicates that the browse answer threshold has been reached and no
     * browse requests will be generated on the network until the number of answers falls
     * below the threshold value.  Add and remove events can still occur based
     * on incoming Bonjour traffic observed by the system.
     * The set of services return to the client is not guaranteed to represent the
     * entire set of services present on the network once the threshold has been reached.
     *
     * Note, while kDNSServiceFlagsThresholdReached and kDNSServiceFlagsThresholdOne
     * have the same value, there  isn't a conflict because kDNSServiceFlagsThresholdReached
     * is only set in the callbacks and kDNSServiceFlagsThresholdOne is only set on
     * input to a DNSServiceBrowse call.
     */
     kDNSServiceFlagsPrivateOne          = 0x2000,
    /*
     * This flag is private and should not be used.
     */

     kDNSServiceFlagsPrivateTwo           = 0x8000000,
    /*
     * This flag is private and should not be used.
     */

     kDNSServiceFlagsPrivateThree         = 0x10000000,
    /*
     * This flag is private and should not be used.
     */

     kDNSServiceFlagsPrivateFour          = 0x20000000,
    /*
     * This flag is private and should not be used.
     */

    kDNSServiceFlagsPrivateFive          = 0x40000000,
    /*
     * This flag is private and should not be used.
     */


    kDNSServiceFlagAnsweredFromCache     = 0x40000000,
    /*
     * When kDNSServiceFlagAnsweredFromCache is passed back in the flags parameter of DNSServiceQueryRecordReply or DNSServiceGetAddrInfoReply,
     * an answer will have this flag set if it was answered from the cache.
     */

    kDNSServiceFlagsAllowExpiredAnswers   = 0x80000000,
    /*
     * When kDNSServiceFlagsAllowExpiredAnswers is passed to DNSServiceQueryRecord or DNSServiceGetAddrInfo,
     * if there are matching expired records still in the cache, then they are immediately returned to the
     * client, and in parallel a network query for that name is issued. All returned records from the query will
     * remain in the cache after expiration.
     */
    
    kDNSServiceFlagsExpiredAnswer         = 0x80000000
    /*
     * When kDNSServiceFlagsAllowExpiredAnswers is passed to DNSServiceQueryRecord or DNSServiceGetAddrInfo,
     * an expired answer will have this flag set.
     */

};

/* Possible protocol values */
enum
{
    /* for DNSServiceGetAddrInfo() */
    kDNSServiceProtocol_IPv4 = 0x01,
    kDNSServiceProtocol_IPv6 = 0x02,
    /* 0x04 and 0x08 reserved for future internetwork protocols */

    /* for DNSServiceNATPortMappingCreate() */
    kDNSServiceProtocol_UDP  = 0x10,
    kDNSServiceProtocol_TCP  = 0x20
                               /* 0x40 and 0x80 reserved for future transport protocols, e.g. SCTP [RFC 2960]
                                * or DCCP [RFC 4340]. If future NAT gateways are created that support port
                                * mappings for these protocols, new constants will be defined here.
                                */
};

/*
 * The values for DNS Classes and Types are listed in RFC 1035, and are available
 * on every OS in its DNS header file. Unfortunately every OS does not have the
 * same header file containing DNS Class and Type constants, and the names of
 * the constants are not consistent. For example, BIND 8 uses "T_A",
 * BIND 9 uses "ns_t_a", Windows uses "DNS_TYPE_A", etc.
 * For this reason, these constants are also listed here, so that code using
 * the DNS-SD programming APIs can use these constants, so that the same code
 * can compile on all our supported platforms.
 */

enum
{
    kDNSServiceClass_IN       = 1       /* Internet */
};

enum
{
    kDNSServiceType_A          = 1,      /* Host address. */
    kDNSServiceType_NS         = 2,      /* Authoritative server. */
    kDNSServiceType_MD         = 3,      /* Mail destination. */
    kDNSServiceType_MF         = 4,      /* Mail forwarder. */
    kDNSServiceType_CNAME      = 5,      /* Canonical name. */
    kDNSServiceType_SOA        = 6,      /* Start of authority zone. */
    kDNSServiceType_MB         = 7,      /* Mailbox domain name. */
    kDNSServiceType_MG         = 8,      /* Mail group member. */
    kDNSServiceType_MR         = 9,      /* Mail rename name. */
    kDNSServiceType_NULL       = 10,     /* Null resource record. */
    kDNSServiceType_WKS        = 11,     /* Well known service. */
    kDNSServiceType_PTR        = 12,     /* Domain name pointer. */
    kDNSServiceType_HINFO      = 13,     /* Host information. */
    kDNSServiceType_MINFO      = 14,     /* Mailbox information. */
    kDNSServiceType_MX         = 15,     /* Mail routing information. */
    kDNSServiceType_TXT        = 16,     /* One or more text strings (NOT "zero or more..."). */
    kDNSServiceType_RP         = 17,     /* Responsible person. */
    kDNSServiceType_AFSDB      = 18,     /* AFS cell database. */
    kDNSServiceType_X25        = 19,     /* X_25 calling address. */
    kDNSServiceType_ISDN       = 20,     /* ISDN calling address. */
    kDNSServiceType_RT         = 21,     /* Router. */
    kDNSServiceType_NSAP       = 22,     /* NSAP address. */
    kDNSServiceType_NSAP_PTR   = 23,     /* Reverse NSAP lookup (deprecated). */
    kDNSServiceType_SIG        = 24,     /* Security signature. */
    kDNSServiceType_KEY        = 25,     /* Security key. */
    kDNSServiceType_PX         = 26,     /* X.400 mail mapping. */
    kDNSServiceType_GPOS       = 27,     /* Geographical position (withdrawn). */
    kDNSServiceType_AAAA       = 28,     /* IPv6 Address. */
    kDNSServiceType_LOC        = 29,     /* Location Information. */
    kDNSServiceType_NXT        = 30,     /* Next domain (security). */
    kDNSServiceType_EID        = 31,     /* Endpoint identifier. */
    kDNSServiceType_NIMLOC     = 32,     /* Nimrod Locator. */
    kDNSServiceType_SRV        = 33,     /* Server Selection. */
    kDNSServiceType_ATMA       = 34,     /* ATM Address */
    kDNSServiceType_NAPTR      = 35,     /* Naming Authority PoinTeR */
    kDNSServiceType_KX         = 36,     /* Key Exchange */
    kDNSServiceType_CERT       = 37,     /* Certification record */
    kDNSServiceType_A6         = 38,     /* IPv6 Address (deprecated) */
    kDNSServiceType_DNAME      = 39,     /* Non-terminal DNAME (for IPv6) */
    kDNSServiceType_SINK       = 40,     /* Kitchen sink (experimental) */
    kDNSServiceType_OPT        = 41,     /* EDNS0 option (meta-RR) */
    kDNSServiceType_APL        = 42,     /* Address Prefix List */
    kDNSServiceType_DS         = 43,     /* Delegation Signer */
    kDNSServiceType_SSHFP      = 44,     /* SSH Key Fingerprint */
    kDNSServiceType_IPSECKEY   = 45,     /* IPSECKEY */
    kDNSServiceType_RRSIG      = 46,     /* RRSIG */
    kDNSServiceType_NSEC       = 47,     /* Denial of Existence */
    kDNSServiceType_DNSKEY     = 48,     /* DNSKEY */
    kDNSServiceType_DHCID      = 49,     /* DHCP Client Identifier */
    kDNSServiceType_NSEC3      = 50,     /* Hashed Authenticated Denial of Existence */
    kDNSServiceType_NSEC3PARAM = 51,     /* Hashed Authenticated Denial of Existence */

    kDNSServiceType_HIP        = 55,     /* Host Identity Protocol */

    kDNSServiceType_SVCB       = 64,     /* Service Binding. */
    kDNSServiceType_HTTPS      = 65,      /* HTTPS Service Binding. */

    kDNSServiceType_SPF        = 99,     /* Sender Policy Framework for E-Mail */
    kDNSServiceType_UINFO      = 100,    /* IANA-Reserved */
    kDNSServiceType_UID        = 101,    /* IANA-Reserved */
    kDNSServiceType_GID        = 102,    /* IANA-Reserved */
    kDNSServiceType_UNSPEC     = 103,    /* IANA-Reserved */

    kDNSServiceType_TKEY       = 249,    /* Transaction key */
    kDNSServiceType_TSIG       = 250,    /* Transaction signature. */
    kDNSServiceType_IXFR       = 251,    /* Incremental zone transfer. */
    kDNSServiceType_AXFR       = 252,    /* Transfer zone of authority. */
    kDNSServiceType_MAILB      = 253,    /* Transfer mailbox records. */
    kDNSServiceType_MAILA      = 254,    /* Transfer mail agent records. */
    kDNSServiceType_ANY        = 255    /* Wildcard match. */
};

/* possible error code values */
enum
{
    kDNSServiceErr_NoError                   = 0,
    kDNSServiceErr_Unknown                   = -65537,  /* 0xFFFE FFFF */
    kDNSServiceErr_NoSuchName                = -65538,
    kDNSServiceErr_NoMemory                  = -65539,
    kDNSServiceErr_BadParam                  = -65540,
    kDNSServiceErr_BadReference              = -65541,
    kDNSServiceErr_BadState                  = -65542,
    kDNSServiceErr_BadFlags                  = -65543,
    kDNSServiceErr_Unsupported               = -65544,
    kDNSServiceErr_NotInitialized            = -65545,
    kDNSServiceErr_AlreadyRegistered         = -65547,
    kDNSServiceErr_NameConflict              = -65548,
    kDNSServiceErr_Invalid                   = -65549,
    kDNSServiceErr_Firewall                  = -65550,
    kDNSServiceErr_Incompatible              = -65551,  /* client library incompatible with daemon */
    kDNSServiceErr_BadInterfaceIndex         = -65552,
    kDNSServiceErr_Refused                   = -65553,
    kDNSServiceErr_NoSuchRecord              = -65554,
    kDNSServiceErr_NoAuth                    = -65555,
    kDNSServiceErr_NoSuchKey                 = -65556,
    kDNSServiceErr_NATTraversal              = -65557,
    kDNSServiceErr_DoubleNAT                 = -65558,
    kDNSServiceErr_BadTime                   = -65559,  /* Codes up to here existed in Tiger */
    kDNSServiceErr_BadSig                    = -65560,
    kDNSServiceErr_BadKey                    = -65561,
    kDNSServiceErr_Transient                 = -65562,
    kDNSServiceErr_ServiceNotRunning         = -65563,  /* Background daemon not running */
    kDNSServiceErr_NATPortMappingUnsupported = -65564,  /* NAT doesn't support PCP, NAT-PMP or UPnP */
    kDNSServiceErr_NATPortMappingDisabled    = -65565,  /* NAT supports PCP, NAT-PMP or UPnP, but it's disabled by the administrator */
    kDNSServiceErr_NoRouter                  = -65566,  /* No router currently configured (probably no network connectivity) */
    kDNSServiceErr_PollingMode               = -65567,
    kDNSServiceErr_Timeout                   = -65568,
    kDNSServiceErr_DefunctConnection         = -65569,  /* Connection to daemon returned a SO_ISDEFUNCT error result */
    kDNSServiceErr_PolicyDenied              = -65570

                                               /* mDNS Error codes are in the range
                                                * FFFE FF00 (-65792) to FFFE FFFF (-65537) */
};

/* Maximum length, in bytes, of a service name represented as a */
/* literal C-String, including the terminating NULL at the end. */

#define kDNSServiceMaxServiceName 64

/* Maximum length, in bytes, of a domain name represented as an *escaped* C-String */
/* including the final trailing dot, and the C-String terminating NULL at the end. */

#define kDNSServiceMaxDomainName 1009

/*
 * Notes on DNS Name Escaping
 *   -- or --
 * "Why is kDNSServiceMaxDomainName 1009, when the maximum legal domain name is 256 bytes?"
 *
 * All strings used in the DNS-SD APIs are UTF-8 strings.
 * Apart from the exceptions noted below, the APIs expect the strings to be properly escaped, using the
 * conventional DNS escaping rules, as used by the traditional DNS res_query() API, as described below:
 *
 * Generally all UTF-8 characters (which includes all US ASCII characters) represent themselves,
 * with three exceptions:
 * the dot ('.') character, which is the DNS label separator,
 * the backslash ('\') character, which is the DNS escape character, and
 * the ASCII NUL (0) byte value, which is the C-string terminator character.
 * The escape character ('\') is interpreted as described below:
 *
 *   '\ddd', where ddd is a three-digit decimal value from 000 to 255,
 *        represents a single literal byte with that value. Any byte value may be
 *        represented in '\ddd' format, even characters that don't strictly need to be escaped.
 *        For example, the ASCII code for 'w' is 119, and therefore '\119' is equivalent to 'w'.
 *        Thus the command "ping '\119\119\119.apple.com'" is the equivalent to the command "ping 'www.apple.com'".
 *        Nonprinting ASCII characters in the range 0-31 are often represented this way.
 *        In particular, the ASCII NUL character (0) cannot appear in a C-string because C uses it as the
 *        string terminator character, so ASCII NUL in a domain name has to be represented in a C-string as '\000'.
 *        Other characters like space (ASCII code 32) are sometimes represented as '\032'
 *        in contexts where having an actual space character in a C-string would be inconvenient.
 *        
 *   Otherwise, for all cases where a '\' is followed by anything other than a three-digit decimal value
 *        from 000 to 255, the character sequence '\x' represents a single literal occurrence of character 'x'.
 *        This is legal for any character, so, for example, '\w' is equivalent to 'w'.
 *        Thus the command "ping '\w\w\w.apple.com'" is the equivalent to the command "ping 'www.apple.com'".
 *        However, this encoding is most useful when representing the characters '.' and '\',
 *        which otherwise would have special meaning in DNS name strings.
 *        This means that the following encodings are particularly common:
 *        '\\' represents a single literal '\' in the name
 *        '\.' represents a single literal '.' in the name
 *
 *   A lone escape character ('\') appearing at the end of a string is not allowed, since it is
 *        followed by neither a three-digit decimal value from 000 to 255 nor a single character.
 *        If a lone escape character ('\') does appear as the last character of a string, it is silently ignored.
 *
 * The worse-case length for an escaped domain name is calculated as follows:
 * The longest legal domain name is 256 bytes in wire format (see RFC 6762, Appendix C, DNS Name Length).
 * For our calculation of the longest *escaped* domain name, we use
 * the longest legal domain name, with the most characters escaped.
 *
 * We consider a domain name of the form: "label63.label63.label63.label62."
 * where "label63" is a 63-byte label and "label62" is a 62-byte label.
 * Counting four label-length bytes, 251 bytes of label data, and the terminating zero,
 * this makes a total of 256 bytes in wire format, the longest legal domain name.
 *
 * If each one of the 251 bytes of label data is represented using '\ddd',
 * then it takes 251 * 4 = 1004 bytes to represent these in a C-string.
 * Adding four '.' characters as shown above, plus the C-string terminating
 * zero at the end, results in a maximum storage requirement of 1009 bytes.
 *
 * The exceptions, that do not use escaping, are the routines where the full
 * DNS name of a resource is broken, for convenience, into servicename/regtype/domain.
 * In these routines, the "servicename" is NOT escaped. It does not need to be, since
 * it is, by definition, just a single literal string. Any characters in that string
 * represent exactly what they are. The "regtype" portion is, technically speaking,
 * escaped, but since legal regtypes are only allowed to contain US ASCII letters,
 * digits, and hyphens, there is nothing to escape, so the issue is moot.
 * The "domain" portion is also escaped, though most domains in use on the public
 * Internet today, like regtypes, don't contain any characters that need to be escaped.
 * As DNS-SD becomes more popular, rich-text domains for service discovery will
 * become common, so software should be written to cope with domains with escaping.
 *
 * The servicename may be up to 63 bytes of UTF-8 text (not counting the C-String
 * terminating NULL at the end). The regtype is of the form _service._tcp or
 * _service._udp, where the "service" part is 1-15 characters, which may be
 * letters, digits, or hyphens. The domain part of the three-part name may be
 * any legal domain, providing that the resulting servicename+regtype+domain
 * name does not exceed 256 bytes.
 *
 * For most software, these issues are transparent. When browsing, the discovered
 * servicenames should simply be displayed as-is. When resolving, the discovered
 * servicename/regtype/domain are simply passed unchanged to DNSServiceResolve().
 * When a DNSServiceResolve() succeeds, the returned fullname is already in
 * the correct format to pass to standard system DNS APIs such as res_query().
 * For converting from servicename/regtype/domain to a single properly-escaped
 * full DNS name, the helper function DNSServiceConstructFullName() is provided.
 *
 * The following (highly contrived) example illustrates the escaping process.
 * Suppose you have a service called "Dr. Smith\Dr. Johnson", of type "_ftp._tcp"
 * in subdomain "4th. Floor" of subdomain "Building 2" of domain "apple.com."
 * The full (escaped) DNS name of this service's SRV record would be:
 * Dr\.\032Smith\\Dr\.\032Johnson._ftp._tcp.4th\.\032Floor.Building\0322.apple.com.
 */


/*
 * Constants for specifying an interface index
 *
 * Specific interface indexes are identified via a 32-bit unsigned integer returned
 * by the if_nametoindex() family of calls.
 *
 * If the client passes 0 for interface index, that means "do the right thing",
 * which (at present) means, "if the name is in an mDNS local multicast domain
 * (e.g. 'local.', '254.169.in-addr.arpa.', '{8,9,A,B}.E.F.ip6.arpa.') then multicast
 * on all applicable interfaces, otherwise send via unicast to the appropriate
 * DNS server." Normally, most clients will use 0 for interface index to
 * automatically get the default sensible behaviour.
 *
 * If the client passes a positive interface index, then that indicates to do the
 * operation only on that one specified interface.
 *
 * If the client passes kDNSServiceInterfaceIndexLocalOnly when registering
 * a service, then that service will be found *only* by other local clients
 * on the same machine that are browsing using kDNSServiceInterfaceIndexLocalOnly
 * or kDNSServiceInterfaceIndexAny.
 * If a client has a 'private' service, accessible only to other processes
 * running on the same machine, this allows the client to advertise that service
 * in a way such that it does not inadvertently appear in service lists on
 * all the other machines on the network.
 *
 * If the client passes kDNSServiceInterfaceIndexLocalOnly when querying or
 * browsing, then the LocalOnly authoritative records and /etc/hosts caches
 * are searched and will find *all* records registered or configured on that
 * same local machine.
 *
 * If interested in getting negative answers to local questions while querying
 * or browsing, then set both the kDNSServiceInterfaceIndexLocalOnly and the
 * kDNSServiceFlagsReturnIntermediates flags. If no local answers exist at this
 * moment in time, then the reply will return an immediate negative answer. If
 * local records are subsequently created that answer the question, then those
 * answers will be delivered, for as long as the question is still active.
 *
 * If the kDNSServiceFlagsTimeout and kDNSServiceInterfaceIndexLocalOnly flags
 * are set simultaneously when either DNSServiceQueryRecord or DNSServiceGetAddrInfo
 * is called then both flags take effect. However, if DNSServiceQueryRecord is called
 * with both the kDNSServiceFlagsSuppressUnusable and kDNSServiceInterfaceIndexLocalOnly
 * flags set, then the kDNSServiceFlagsSuppressUnusable flag is ignored.
 *
 * Clients explicitly wishing to discover *only* LocalOnly services during a
 * browse may do this, without flags, by inspecting the interfaceIndex of each
 * service reported to a DNSServiceBrowseReply() callback function, and
 * discarding those answers where the interface index is not set to
 * kDNSServiceInterfaceIndexLocalOnly.
 *
 * kDNSServiceInterfaceIndexP2P is meaningful only in Browse, QueryRecord, Register,
 * and Resolve operations. It should not be used in other DNSService APIs.
 *
 * - If kDNSServiceInterfaceIndexP2P is passed to DNSServiceBrowse or
 *   DNSServiceQueryRecord, it restricts the operation to P2P.
 *
 * - If kDNSServiceInterfaceIndexP2P is passed to DNSServiceRegister, it is
 *   mapped internally to kDNSServiceInterfaceIndexAny with the kDNSServiceFlagsIncludeP2P
 *   set.
 *
 * - If kDNSServiceInterfaceIndexP2P is passed to DNSServiceResolve, it is
 *   mapped internally to kDNSServiceInterfaceIndexAny with the kDNSServiceFlagsIncludeP2P
 *   set, because resolving a P2P service may create and/or enable an interface whose
 *   index is not known a priori. The resolve callback will indicate the index of the
 *   interface via which the service can be accessed.
 *
 * If applications pass kDNSServiceInterfaceIndexAny to DNSServiceBrowse
 * or DNSServiceQueryRecord, they must set the kDNSServiceFlagsIncludeP2P flag
 * to include P2P. In this case, if a service instance or the record being queried
 * is found over P2P, the resulting ADD event will indicate kDNSServiceInterfaceIndexP2P
 * as the interface index.
 */

#define kDNSServiceInterfaceIndexAny 0
#define kDNSServiceInterfaceIndexLocalOnly ((uint32_t)-1)
#define kDNSServiceInterfaceIndexUnicast   ((uint32_t)-2)
#define kDNSServiceInterfaceIndexP2P       ((uint32_t)-3)
#define kDNSServiceInterfaceIndexBLE       ((uint32_t)-4)

typedef uint32_t DNSServiceFlags;
typedef uint32_t DNSServiceProtocol;
typedef int32_t DNSServiceErrorType;


/*********************************************************************************************
*
* Version checking
*
*********************************************************************************************/

/* DNSServiceGetProperty() Parameters:
 *
 * property:        The requested property.
 *                  Currently the only property defined is kDNSServiceProperty_DaemonVersion.
 *
 * result:          Place to store result.
 *                  For retrieving DaemonVersion, this should be the address of a uint32_t.
 *
 * size:            Pointer to uint32_t containing size of the result location.
 *                  For retrieving DaemonVersion, this should be sizeof(uint32_t).
 *                  On return the uint32_t is updated to the size of the data returned.
 *                  For DaemonVersion, the returned size is always sizeof(uint32_t), but
 *                  future properties could be defined which return variable-sized results.
 *
 * return value:    Returns kDNSServiceErr_NoError on success, or kDNSServiceErr_ServiceNotRunning
 *                  if the daemon (or "system service" on Windows) is not running.
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceGetProperty
(
    const char *property,  /* Requested property (i.e. kDNSServiceProperty_DaemonVersion) */
    void       *result,    /* Pointer to place to store result */
    uint32_t   *size       /* size of result location */
);

/*
 * When requesting kDNSServiceProperty_DaemonVersion, the result pointer must point
 * to a 32-bit unsigned integer, and the size parameter must be set to sizeof(uint32_t).
 *
 * On return, the 32-bit unsigned integer contains the API version number
 *
 * For example, Mac OS X 10.4.9 has API version 1080400.
 * This allows applications to do simple greater-than and less-than comparisons:
 * e.g. an application that requires at least API version 1080400 can check:
 *   if (version >= 1080400) ...
 *
 * Example usage:
 * uint32_t version;
 * uint32_t size = sizeof(version);
 * DNSServiceErrorType err = DNSServiceGetProperty(kDNSServiceProperty_DaemonVersion, &version, &size);
 * if (!err) printf("DNS_SD API version is %d.%d\n", version / 10000, version / 100 % 100);
 */

#define kDNSServiceProperty_DaemonVersion "DaemonVersion"

/*********************************************************************************************
*
* Unix Domain Socket access, DNSServiceRef deallocation, and data processing functions
*
*********************************************************************************************/

/* DNSServiceRefSockFD()
 *
 * Access underlying Unix domain socket for an initialized DNSServiceRef.
 * The DNS Service Discovery implementation uses this socket to communicate between the client and
 * the daemon. The application MUST NOT directly read from or write to this socket.
 * Access to the socket is provided so that it can be used as a kqueue event source, a CFRunLoop
 * event source, in a select() loop, etc. When the underlying event management subsystem (kqueue/
 * select/CFRunLoop etc.) indicates to the client that data is available for reading on the
 * socket, the client should call DNSServiceProcessResult(), which will extract the daemon's
 * reply from the socket, and pass it to the appropriate application callback. By using a run
 * loop or select(), results from the daemon can be processed asynchronously. Alternatively,
 * a client can choose to fork a thread and have it loop calling "DNSServiceProcessResult(ref);"
 * If DNSServiceProcessResult() is called when no data is available for reading on the socket, it
 * will block until data does become available, and then process the data and return to the caller.
 * The application is responsible for checking the return value of DNSServiceProcessResult()
 * to determine if the socket is valid and if it should continue to process data on the socket.
 * When data arrives on the socket, the client is responsible for calling DNSServiceProcessResult(ref)
 * in a timely fashion -- if the client allows a large backlog of data to build up the daemon
 * may terminate the connection.
 *
 * sdRef:           A DNSServiceRef initialized by any of the DNSService calls.
 *
 * return value:    The DNSServiceRef's underlying socket descriptor, or -1 on
 *                  error.
 */

DNSSD_EXPORT
dnssd_sock_t DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdRef);


/* DNSServiceProcessResult()
 *
 * Read a reply from the daemon, calling the appropriate application callback. This call will
 * block until the daemon's response is received. Use DNSServiceRefSockFD() in
 * conjunction with a run loop or select() to determine the presence of a response from the
 * server before calling this function to process the reply without blocking. Call this function
 * at any point if it is acceptable to block until the daemon's response arrives. Note that the
 * client is responsible for ensuring that DNSServiceProcessResult() is called whenever there is
 * a reply from the daemon - the daemon may terminate its connection with a client that does not
 * process the daemon's responses.
 *
 * sdRef:           A DNSServiceRef initialized by any of the DNSService calls
 *                  that take a callback parameter.
 *
 * return value:    Returns kDNSServiceErr_NoError on success, otherwise returns
 *                  an error code indicating the specific failure that occurred.
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceProcessResult(DNSServiceRef sdRef);


/* DNSServiceRefDeallocate()
 *
 * Terminate a connection with the daemon and free memory associated with the DNSServiceRef.
 * Any services or records registered with this DNSServiceRef will be deregistered. Any
 * Browse, Resolve, or Query operations called with this reference will be terminated.
 *
 * Note: If the reference's underlying socket is used in a run loop or select() call, it should
 * be removed BEFORE DNSServiceRefDeallocate() is called, as this function closes the reference's
 * socket.
 *
 * Note: If the reference was initialized with DNSServiceCreateConnection(), any DNSRecordRefs
 * created via this reference will be invalidated by this call - the resource records are
 * deregistered, and their DNSRecordRefs may not be used in subsequent functions. Similarly,
 * if the reference was initialized with DNSServiceRegister, and an extra resource record was
 * added to the service via DNSServiceAddRecord(), the DNSRecordRef created by the Add() call
 * is invalidated when this function is called - the DNSRecordRef may not be used in subsequent
 * functions.
 *
 * If the reference was passed to DNSServiceSetDispatchQueue(), DNSServiceRefDeallocate() must 
 * be called on the same queue originally passed as an argument to DNSServiceSetDispatchQueue().
 *
 * Note: This call is to be used only with the DNSServiceRef defined by this API.
 *
 * sdRef:           A DNSServiceRef initialized by any of the DNSService calls.
 *
 */

DNSSD_EXPORT
void DNSSD_API DNSServiceRefDeallocate(DNSServiceRef sdRef);


/*********************************************************************************************
*
* Domain Enumeration
*
*********************************************************************************************/

/* DNSServiceEnumerateDomains()
 *
 * Asynchronously enumerate domains available for browsing and registration.
 *
 * The enumeration MUST be cancelled via DNSServiceRefDeallocate() when no more domains
 * are to be found.
 *
 * Note that the names returned are (like all of DNS-SD) UTF-8 strings,
 * and are escaped using standard DNS escaping rules.
 * (See "Notes on DNS Name Escaping" earlier in this file for more details.)
 * A graphical browser displaying a hierarchical tree-structured view should cut
 * the names at the bare dots to yield individual labels, then de-escape each
 * label according to the escaping rules, and then display the resulting UTF-8 text.
 *
 * DNSServiceDomainEnumReply Callback Parameters:
 *
 * sdRef:           The DNSServiceRef initialized by DNSServiceEnumerateDomains().
 *
 * flags:           Possible values are:
 *                  kDNSServiceFlagsMoreComing
 *                  kDNSServiceFlagsAdd
 *                  kDNSServiceFlagsDefault
 *
 * interfaceIndex:  Specifies the interface on which the domain exists. (The index for a given
 *                  interface is determined via the if_nametoindex() family of calls.)
 *
 * errorCode:       Will be kDNSServiceErr_NoError (0) on success, otherwise indicates
 *                  the failure that occurred (other parameters are undefined if errorCode is nonzero).
 *
 * replyDomain:     The name of the domain.
 *
 * context:         The context pointer passed to DNSServiceEnumerateDomains.
 *
 */

typedef void (DNSSD_API *DNSServiceDomainEnumReply)
(
    DNSServiceRef sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    DNSServiceErrorType errorCode,
    const char                          *replyDomain,
    void                                *context
);


/* DNSServiceEnumerateDomains() Parameters:
 *
 * sdRef:           A pointer to an uninitialized DNSServiceRef
 *                  (or, if the kDNSServiceFlagsShareConnection flag is used,
 *                  a copy of the shared connection reference that is to be used).
 *                  If the call succeeds then it initializes (or updates) the DNSServiceRef,
 *                  returns kDNSServiceErr_NoError, and the enumeration operation
 *                  will remain active indefinitely until the client terminates it
 *                  by passing this DNSServiceRef to DNSServiceRefDeallocate()
 *                  (or by closing the underlying shared connection, if used).
 *
 * flags:           Possible values are:
 *                  kDNSServiceFlagsShareConnection to use a shared connection.
 *                  kDNSServiceFlagsBrowseDomains to enumerate domains recommended for browsing.
 *                  kDNSServiceFlagsRegistrationDomains to enumerate domains recommended
 *                  for registration.
 *
 * interfaceIndex:  If non-zero, specifies the interface on which to look for domains.
 *                  (the index for a given interface is determined via the if_nametoindex()
 *                  family of calls.) Most applications will pass 0 to enumerate domains on
 *                  all interfaces. See "Constants for specifying an interface index" for more details.
 *
 * callBack:        The function to be called when a domain is found or the call asynchronously
 *                  fails.
 *
 * context:         An application context pointer which is passed to the callback function
 *                  (may be NULL).
 *
 * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
 *                  errors are delivered to the callback), otherwise returns an error code indicating
 *                  the error that occurred (the callback is not invoked and the DNSServiceRef
 *                  is not initialized).
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
(
    DNSServiceRef                       *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    DNSServiceDomainEnumReply callBack,
    void                                *context  /* may be NULL */
);


/*********************************************************************************************
*
*  Service Registration
*
*********************************************************************************************/

/* Register a service that is discovered via Browse() and Resolve() calls.
 *
 * DNSServiceRegisterReply() Callback Parameters:
 *
 * sdRef:           The DNSServiceRef initialized by DNSServiceRegister().
 *
 * flags:           When a name is successfully registered, the callback will be
 *                  invoked with the kDNSServiceFlagsAdd flag set. When Wide-Area
 *                  DNS-SD is in use, it is possible for a single service to get
 *                  more than one success callback (e.g. one in the "local" multicast
 *                  DNS domain, and another in a wide-area unicast DNS domain).
 *                  If a successfully-registered name later suffers a name conflict
 *                  or similar problem and has to be deregistered, the callback will
 *                  be invoked with the kDNSServiceFlagsAdd flag not set. The callback
 *                  is *not* invoked in the case where the caller explicitly terminates
 *                  the service registration by calling DNSServiceRefDeallocate(ref);
 *
 * errorCode:       Will be kDNSServiceErr_NoError on success, otherwise will
 *                  indicate the failure that occurred (including name conflicts,
 *                  if the kDNSServiceFlagsNoAutoRename flag was used when registering.)
 *                  Other parameters are undefined if errorCode is nonzero.
 *
 * name:            The service name registered (if the application did not specify a name in
 *                  DNSServiceRegister(), this indicates what name was automatically chosen).
 *
 * regtype:         The type of service registered, as it was passed to the callout.
 *
 * domain:          The domain on which the service was registered (if the application did not
 *                  specify a domain in DNSServiceRegister(), this indicates the default domain
 *                  on which the service was registered).
 *
 * context:         The context pointer that was passed to the callout.
 *
 */

typedef void (DNSSD_API *DNSServiceRegisterReply)
(
    DNSServiceRef sdRef,
    DNSServiceFlags flags,
    DNSServiceErrorType errorCode,
    const char                          *name,
    const char                          *regtype,
    const char                          *domain,
    void                                *context
);


/* DNSServiceRegister() Parameters:
 *
 * sdRef:           A pointer to an uninitialized DNSServiceRef
 *                  (or, if the kDNSServiceFlagsShareConnection flag is used,
 *                  a copy of the shared connection reference that is to be used).
 *                  If the call succeeds then it initializes (or updates) the DNSServiceRef,
 *                  returns kDNSServiceErr_NoError, and the service registration
 *                  will remain active indefinitely until the client terminates it
 *                  by passing this DNSServiceRef to DNSServiceRefDeallocate()
 *                  (or by closing the underlying shared connection, if used).
 *
 * flags:           Possible values are:
 *                  kDNSServiceFlagsShareConnection to use a shared connection.
 *                  Other flags indicate the renaming behavior on name conflict
 *                  (not required for most applications).
 *                  See flag definitions above for details.
 *
 * interfaceIndex:  If non-zero, specifies the interface on which to register the service
 *                  (the index for a given interface is determined via the if_nametoindex()
 *                  family of calls.) Most applications will pass 0 to register on all
 *                  available interfaces. See "Constants for specifying an interface index" for more details.
 *
 * name:            If non-NULL, specifies the service name to be registered.
 *                  Most applications will not specify a name, in which case the computer
 *                  name is used (this name is communicated to the client via the callback).
 *                  If a name is specified, it must be 1-63 bytes of UTF-8 text.
 *                  If the name is longer than 63 bytes it will be automatically truncated
 *                  to a legal length, unless the NoAutoRename flag is set,
 *                  in which case kDNSServiceErr_BadParam will be returned.
 *
 * regtype:         The service type followed by the protocol, separated by a dot
 *                  (e.g. "_ftp._tcp"). The service type must be an underscore, followed
 *                  by 1-15 characters, which may be letters, digits, or hyphens.
 *                  The transport protocol must be "_tcp" or "_udp". New service types
 *                  should be registered at <http://www.dns-sd.org/ServiceTypes.html>.
 *
 *                  Additional subtypes of the primary service type (where a service
 *                  type has defined subtypes) follow the primary service type in a
 *                  comma-separated list, with no additional spaces, e.g.
 *                      "_primarytype._tcp,_subtype1,_subtype2,_subtype3"
 *                  Subtypes provide a mechanism for filtered browsing: A client browsing
 *                  for "_primarytype._tcp" will discover all instances of this type;
 *                  a client browsing for "_primarytype._tcp,_subtype2" will discover only
 *                  those instances that were registered with "_subtype2" in their list of
 *                  registered subtypes.
 *
 *                  The subtype mechanism can be illustrated with some examples using the
 *                  dns-sd command-line tool:
 *
 *                  % dns-sd -R Simple _test._tcp "" 1001 &
 *                  % dns-sd -R Better _test._tcp,HasFeatureA "" 1002 &
 *                  % dns-sd -R Best   _test._tcp,HasFeatureA,HasFeatureB "" 1003 &
 *
 *                  Now:
 *                  % dns-sd -B _test._tcp             # will find all three services
 *                  % dns-sd -B _test._tcp,HasFeatureA # finds "Better" and "Best"
 *                  % dns-sd -B _test._tcp,HasFeatureB # finds only "Best"
 *
 *                  Subtype labels may be up to 63 bytes long, and may contain any eight-
 *                  bit byte values, including zero bytes. However, due to the nature of
 *                  using a C-string-based API, conventional DNS escaping must be used for
 *                  dots ('.'), commas (','), backslashes ('\') and zero bytes, as shown below:
 *
 *                  % dns-sd -R Test '_test._tcp,s\.one,s\,two,s\\three,s\000four' local 123
 *
 * domain:          If non-NULL, specifies the domain on which to advertise the service.
 *                  Most applications will not specify a domain, instead automatically
 *                  registering in the default domain(s).
 *
 * host:            If non-NULL, specifies the SRV target host name. Most applications
 *                  will not specify a host, instead automatically using the machine's
 *                  default host name(s). Note that specifying a non-NULL host does NOT
 *                  create an address record for that host - the application is responsible
 *                  for ensuring that the appropriate address record exists, or creating it
 *                  via DNSServiceRegisterRecord().
 *
 * port:            The port, in network byte order, on which the service accepts connections.
 *                  Pass 0 for a "placeholder" service (i.e. a service that will not be discovered
 *                  by browsing, but will cause a name conflict if another client tries to
 *                  register that same name). Most clients will not use placeholder services.
 *
 * txtLen:          The length of the txtRecord, in bytes. Must be zero if the txtRecord is NULL.
 *
 * txtRecord:       The TXT record rdata. A non-NULL txtRecord MUST be a properly formatted DNS
 *                  TXT record, i.e. <length byte> <data> <length byte> <data> ...
 *                  Passing NULL for the txtRecord is allowed as a synonym for txtLen=1, txtRecord="",
 *                  i.e. it creates a TXT record of length one containing a single empty string.
 *                  RFC 1035 doesn't allow a TXT record to contain *zero* strings, so a single empty
 *                  string is the smallest legal DNS TXT record.
 *                  As with the other parameters, the DNSServiceRegister call copies the txtRecord
 *                  data; e.g. if you allocated the storage for the txtRecord parameter with malloc()
 *                  then you can safely free that memory right after the DNSServiceRegister call returns.
 *
 * callBack:        The function to be called when the registration completes or asynchronously
 *                  fails. The client MAY pass NULL for the callback -  The client will NOT be notified
 *                  of the default values picked on its behalf, and the client will NOT be notified of any
 *                  asynchronous errors (e.g. out of memory errors, etc.) that may prevent the registration
 *                  of the service. The client may NOT pass the NoAutoRename flag if the callback is NULL.
 *                  The client may still deregister the service at any time via DNSServiceRefDeallocate().
 *
 * context:         An application context pointer which is passed to the callback function
 *                  (may be NULL).
 *
 * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
 *                  errors are delivered to the callback), otherwise returns an error code indicating
 *                  the error that occurred (the callback is never invoked and the DNSServiceRef
 *                  is not initialized).
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceRegister
(
    DNSServiceRef                       *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char                          *name,         /* may be NULL */
    const char                          *regtype,
    const char                          *domain,       /* may be NULL */
    const char                          *host,         /* may be NULL */
    uint16_t port,                                     /* In network byte order */
    uint16_t txtLen,
    const void                          *txtRecord,    /* may be NULL */
    DNSServiceRegisterReply callBack,                  /* may be NULL */
    void                                *context       /* may be NULL */
);


/* DNSServiceAddRecord()
 *
 * Add a record to a registered service. The name of the record will be the same as the
 * registered service's name.
 * The record can later be updated or deregistered by passing the RecordRef initialized
 * by this function to DNSServiceUpdateRecord() or DNSServiceRemoveRecord().
 *
 * Note that the DNSServiceAddRecord/UpdateRecord/RemoveRecord are *NOT* thread-safe
 * with respect to a single DNSServiceRef. If you plan to have multiple threads
 * in your program simultaneously add, update, or remove records from the same
 * DNSServiceRef, then it's the caller's responsibility to use a mutex lock
 * or take similar appropriate precautions to serialize those calls.
 *
 * Parameters;
 *
 * sdRef:           A DNSServiceRef initialized by DNSServiceRegister().
 *
 * RecordRef:       A pointer to an uninitialized DNSRecordRef. Upon succesfull completion of this
 *                  call, this ref may be passed to DNSServiceUpdateRecord() or DNSServiceRemoveRecord().
 *                  If the above DNSServiceRef is passed to DNSServiceRefDeallocate(), RecordRef is also
 *                  invalidated and may not be used further.
 *
 * flags:           Currently ignored, reserved for future use.
 *
 * rrtype:          The type of the record (e.g. kDNSServiceType_TXT, kDNSServiceType_SRV, etc)
 *
 * rdlen:           The length, in bytes, of the rdata.
 *
 * rdata:           The raw rdata to be contained in the added resource record.
 *
 * ttl:             The time to live of the resource record, in seconds.
 *                  Most clients should pass 0 to indicate that the system should
 *                  select a sensible default value.
 *
 * return value:    Returns kDNSServiceErr_NoError on success, otherwise returns an
 *                  error code indicating the error that occurred (the RecordRef is not initialized).
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceAddRecord
(
    DNSServiceRef sdRef,
    DNSRecordRef                        *RecordRef,
    DNSServiceFlags flags,
    uint16_t rrtype,
    uint16_t rdlen,
    const void                          *rdata,
    uint32_t ttl
);


/* DNSServiceUpdateRecord
 *
 * Update a registered resource record. The record must either be:
 *   - The primary txt record of a service registered via DNSServiceRegister()
 *   - A record added to a registered service via DNSServiceAddRecord()
 *   - An individual record registered by DNSServiceRegisterRecord()
 *
 * Parameters:
 *
 * sdRef:           A DNSServiceRef that was initialized by DNSServiceRegister()
 *                  or DNSServiceCreateConnection().
 *
 * RecordRef:       A DNSRecordRef initialized by DNSServiceAddRecord, or NULL to update the
 *                  service's primary txt record.
 *
 * flags:           Currently ignored, reserved for future use.
 *
 * rdlen:           The length, in bytes, of the new rdata.
 *
 * rdata:           The new rdata to be contained in the updated resource record.
 *
 * ttl:             The time to live of the updated resource record, in seconds.
 *                  Most clients should pass 0 to indicate that the system should
 *                  select a sensible default value.
 *
 * return value:    Returns kDNSServiceErr_NoError on success, otherwise returns an
 *                  error code indicating the error that occurred.
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
(
    DNSServiceRef sdRef,
    DNSRecordRef RecordRef,                            /* may be NULL */
    DNSServiceFlags flags,
    uint16_t rdlen,
    const void                          *rdata,
    uint32_t ttl
);


/* DNSServiceRemoveRecord
 *
 * Remove a record previously added to a service record set via DNSServiceAddRecord(), or deregister
 * a record registered individually via DNSServiceRegisterRecord().
 *
 * Parameters:
 *
 * sdRef:           A DNSServiceRef initialized by DNSServiceRegister() (if the
 *                  record being removed was registered via DNSServiceAddRecord()) or by
 *                  DNSServiceCreateConnection() (if the record being removed was registered via
 *                  DNSServiceRegisterRecord()).
 *
 * recordRef:       A DNSRecordRef initialized by a successful call to DNSServiceAddRecord()
 *                  or DNSServiceRegisterRecord().
 *
 * flags:           Currently ignored, reserved for future use.
 *
 * return value:    Returns kDNSServiceErr_NoError on success, otherwise returns an
 *                  error code indicating the error that occurred.
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
(
    DNSServiceRef sdRef,
    DNSRecordRef RecordRef,
    DNSServiceFlags flags
);


/*********************************************************************************************
*
*  Service Discovery
*
*********************************************************************************************/

/* Browse for instances of a service.
 *
 * DNSServiceBrowseReply() Parameters:
 *
 * sdRef:           The DNSServiceRef initialized by DNSServiceBrowse().
 *
 * flags:           Possible values are kDNSServiceFlagsMoreComing and kDNSServiceFlagsAdd.
 *                  See flag definitions for details.
 *
 * interfaceIndex:  The interface on which the service is advertised. This index should
 *                  be passed to DNSServiceResolve() when resolving the service.
 *
 * errorCode:       Will be kDNSServiceErr_NoError (0) on success, otherwise will
 *                  indicate the failure that occurred. Other parameters are undefined if
 *                  the errorCode is nonzero.
 *
 * serviceName:     The discovered service name. This name should be displayed to the user,
 *                  and stored for subsequent use in the DNSServiceResolve() call.
 *
 * regtype:         The service type, which is usually (but not always) the same as was passed
 *                  to DNSServiceBrowse(). One case where the discovered service type may
 *                  not be the same as the requested service type is when using subtypes:
 *                  The client may want to browse for only those ftp servers that allow
 *                  anonymous connections. The client will pass the string "_ftp._tcp,_anon"
 *                  to DNSServiceBrowse(), but the type of the service that's discovered
 *                  is simply "_ftp._tcp". The regtype for each discovered service instance
 *                  should be stored along with the name, so that it can be passed to
 *                  DNSServiceResolve() when the service is later resolved.
 *
 * domain:          The domain of the discovered service instance. This may or may not be the
 *                  same as the domain that was passed to DNSServiceBrowse(). The domain for each
 *                  discovered service instance should be stored along with the name, so that
 *                  it can be passed to DNSServiceResolve() when the service is later resolved.
 *
 * context:         The context pointer that was passed to the callout.
 *
 */

typedef void (DNSSD_API *DNSServiceBrowseReply)
(
    DNSServiceRef sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    DNSServiceErrorType errorCode,
    const char                          *serviceName,
    const char                          *regtype,
    const char                          *replyDomain,
    void                                *context
);


/* DNSServiceBrowse() Parameters:
 *
 * sdRef:           A pointer to an uninitialized DNSServiceRef
 *                  (or, if the kDNSServiceFlagsShareConnection flag is used,
 *                  a copy of the shared connection reference that is to be used).
 *                  If the call succeeds then it initializes (or updates) the DNSServiceRef,
 *                  returns kDNSServiceErr_NoError, and the browse operation
 *                  will remain active indefinitely until the client terminates it
 *                  by passing this DNSServiceRef to DNSServiceRefDeallocate()
 *                  (or by closing the underlying shared connection, if used).
 *
 * flags:           Possible values are:
 *                  kDNSServiceFlagsShareConnection to use a shared connection.
 *
 * interfaceIndex:  If non-zero, specifies the interface on which to browse for services
 *                  (the index for a given interface is determined via the if_nametoindex()
 *                  family of calls.) Most applications will pass 0 to browse on all available
 *                  interfaces. See "Constants for specifying an interface index" for more details.
 *
 * regtype:         The service type being browsed for followed by the protocol, separated by a
 *                  dot (e.g. "_ftp._tcp"). The transport protocol must be "_tcp" or "_udp".
 *                  A client may optionally specify a single subtype to perform filtered browsing:
 *                  e.g. browsing for "_primarytype._tcp,_subtype" will discover only those
 *                  instances of "_primarytype._tcp" that were registered specifying "_subtype"
 *                  in their list of registered subtypes.
 *
 * domain:          If non-NULL, specifies the domain on which to browse for services.
 *                  Most applications will not specify a domain, instead browsing on the
 *                  default domain(s).
 *
 * callBack:        The function to be called when an instance of the service being browsed for
 *                  is found, or if the call asynchronously fails.
 *
 * context:         An application context pointer which is passed to the callback function
 *                  (may be NULL).
 *
 * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
 *                  errors are delivered to the callback), otherwise returns an error code indicating
 *                  the error that occurred (the callback is not invoked and the DNSServiceRef
 *                  is not initialized).
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceBrowse
(
    DNSServiceRef                       *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char                          *regtype,
    const char                          *domain,    /* may be NULL */
    DNSServiceBrowseReply callBack,
    void                                *context    /* may be NULL */
);


/* DNSServiceResolve()
 *
 * Resolve a service name discovered via DNSServiceBrowse() to a target host name, port number, and
 * txt record.
 *
 * Note: Applications should NOT use DNSServiceResolve() solely for txt record monitoring - use
 * DNSServiceQueryRecord() instead, as it is more efficient for this task.
 *
 * Note: When the desired results have been returned, the client MUST terminate the resolve by calling
 * DNSServiceRefDeallocate().
 *
 * Note: DNSServiceResolve() behaves correctly for typical services that have a single SRV record
 * and a single TXT record. To resolve non-standard services with multiple SRV or TXT records,
 * DNSServiceQueryRecord() should be used.
 *
 * DNSServiceResolveReply Callback Parameters:
 *
 * sdRef:           The DNSServiceRef initialized by DNSServiceResolve().
 *
 * flags:           Possible values: kDNSServiceFlagsMoreComing
 *
 * interfaceIndex:  The interface on which the service was resolved.
 *
 * errorCode:       Will be kDNSServiceErr_NoError (0) on success, otherwise will
 *                  indicate the failure that occurred. Other parameters are undefined if
 *                  the errorCode is nonzero.
 *
 * fullname:        The full service domain name, in the form <servicename>.<protocol>.<domain>.
 *                  (This name is escaped following standard DNS rules, making it suitable for
 *                  passing to standard system DNS APIs such as res_query(), or to the
 *                  special-purpose functions included in this API that take fullname parameters.
 *                  See "Notes on DNS Name Escaping" earlier in this file for more details.)
 *
 * hosttarget:      The target hostname of the machine providing the service. This name can
 *                  be passed to functions like gethostbyname() to identify the host's IP address.
 *
 * port:            The port, in network byte order, on which connections are accepted for this service.
 *
 * txtLen:          The length of the txt record, in bytes.
 *
 * txtRecord:       The service's primary txt record, in standard txt record format.
 *
 * context:         The context pointer that was passed to the callout.
 *
 * NOTE: In earlier versions of this header file, the txtRecord parameter was declared "const char *"
 * This is incorrect, since it contains length bytes which are values in the range 0 to 255, not -128 to +127.
 * Depending on your compiler settings, this change may cause signed/unsigned mismatch warnings.
 * These should be fixed by updating your own callback function definition to match the corrected
 * function signature using "const unsigned char *txtRecord". Making this change may also fix inadvertent
 * bugs in your callback function, where it could have incorrectly interpreted a length byte with value 250
 * as being -6 instead, with various bad consequences ranging from incorrect operation to software crashes.
 * If you need to maintain portable code that will compile cleanly with both the old and new versions of
 * this header file, you should update your callback function definition to use the correct unsigned value,
 * and then in the place where you pass your callback function to DNSServiceResolve(), use a cast to eliminate
 * the compiler warning, e.g.:
 *   DNSServiceResolve(sd, flags, index, name, regtype, domain, (DNSServiceResolveReply)MyCallback, context);
 * This will ensure that your code compiles cleanly without warnings (and more importantly, works correctly)
 * with both the old header and with the new corrected version.
 *
 */

typedef void (DNSSD_API *DNSServiceResolveReply)
(
    DNSServiceRef sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    DNSServiceErrorType errorCode,
    const char                          *fullname,
    const char                          *hosttarget,
    uint16_t port,                                   /* In network byte order */
    uint16_t txtLen,
    const unsigned char                 *txtRecord,
    void                                *context
);


/* DNSServiceResolve() Parameters
 *
 * sdRef:           A pointer to an uninitialized DNSServiceRef
 *                  (or, if the kDNSServiceFlagsShareConnection flag is used,
 *                  a copy of the shared connection reference that is to be used).
 *                  If the call succeeds then it initializes (or updates) the DNSServiceRef,
 *                  returns kDNSServiceErr_NoError, and the resolve operation
 *                  will remain active indefinitely until the client terminates it
 *                  by passing this DNSServiceRef to DNSServiceRefDeallocate()
 *                  (or by closing the underlying shared connection, if used).
 *
 * flags:           Possible values are:
 *                  kDNSServiceFlagsShareConnection to use a shared connection.
 *                  Specifying kDNSServiceFlagsForceMulticast will cause query to be
 *                  performed with a link-local mDNS query, even if the name is an
 *                  apparently non-local name (i.e. a name not ending in ".local.")
 *
 * interfaceIndex:  The interface on which to resolve the service. If this resolve call is
 *                  as a result of a currently active DNSServiceBrowse() operation, then the
 *                  interfaceIndex should be the index reported in the DNSServiceBrowseReply
 *                  callback. If this resolve call is using information previously saved
 *                  (e.g. in a preference file) for later use, then use interfaceIndex 0, because
 *                  the desired service may now be reachable via a different physical interface.
 *                  See "Constants for specifying an interface index" for more details.
 *
 * name:            The name of the service instance to be resolved, as reported to the
 *                  DNSServiceBrowseReply() callback.
 *
 * regtype:         The type of the service instance to be resolved, as reported to the
 *                  DNSServiceBrowseReply() callback.
 *
 * domain:          The domain of the service instance to be resolved, as reported to the
 *                  DNSServiceBrowseReply() callback.
 *
 * callBack:        The function to be called when a result is found, or if the call
 *                  asynchronously fails.
 *
 * context:         An application context pointer which is passed to the callback function
 *                  (may be NULL).
 *
 * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
 *                  errors are delivered to the callback), otherwise returns an error code indicating
 *                  the error that occurred (the callback is never invoked and the DNSServiceRef
 *                  is not initialized).
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceResolve
(
    DNSServiceRef                       *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char                          *name,
    const char                          *regtype,
    const char                          *domain,
    DNSServiceResolveReply callBack,
    void                                *context  /* may be NULL */
);


/*********************************************************************************************
*
*  Querying Individual Specific Records
*
*********************************************************************************************/

/* DNSServiceQueryRecord
 *
 * Query for an arbitrary DNS record.
 *
 * DNSServiceQueryRecordReply() Callback Parameters:
 *
 * sdRef:           The DNSServiceRef initialized by DNSServiceQueryRecord().
 *
 * flags:           Possible values are kDNSServiceFlagsMoreComing and
 *                  kDNSServiceFlagsAdd. The Add flag is NOT set for PTR records
 *                  with a ttl of 0, i.e. "Remove" events.
 *
 * interfaceIndex:  The interface on which the query was resolved (the index for a given
 *                  interface is determined via the if_nametoindex() family of calls).
 *                  See "Constants for specifying an interface index" for more details.
 *
 * errorCode:       Will be kDNSServiceErr_NoError on success, otherwise will
 *                  indicate the failure that occurred. Other parameters are undefined if
 *                  errorCode is nonzero.
 *
 * fullname:        The resource record's full domain name.
 *
 * rrtype:          The resource record's type (e.g. kDNSServiceType_PTR, kDNSServiceType_SRV, etc)
 *
 * rrclass:         The class of the resource record (usually kDNSServiceClass_IN).
 *
 * rdlen:           The length, in bytes, of the resource record rdata.
 *
 * rdata:           The raw rdata of the resource record.
 *
 * ttl:             If the client wishes to cache the result for performance reasons,
 *                  the TTL indicates how long the client may legitimately hold onto
 *                  this result, in seconds. After the TTL expires, the client should
 *                  consider the result no longer valid, and if it requires this data
 *                  again, it should be re-fetched with a new query. Of course, this
 *                  only applies to clients that cancel the asynchronous operation when
 *                  they get a result. Clients that leave the asynchronous operation
 *                  running can safely assume that the data remains valid until they
 *                  get another callback telling them otherwise. The ttl value is not
 *                  updated when the daemon answers from the cache, hence relying on
 *                  the accuracy of the ttl value is not recommended.
 *
 * context:         The context pointer that was passed to the callout.
 *
 */

typedef void (DNSSD_API *DNSServiceQueryRecordReply)
(
    DNSServiceRef sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    DNSServiceErrorType errorCode,
    const char                          *fullname,
    uint16_t rrtype,
    uint16_t rrclass,
    uint16_t rdlen,
    const void                          *rdata,
    uint32_t ttl,
    void                                *context
);


/* DNSServiceQueryRecord() Parameters:
 *
 * sdRef:           A pointer to an uninitialized DNSServiceRef
 *                  (or, if the kDNSServiceFlagsShareConnection flag is used,
 *                  a copy of the shared connection reference that is to be used).
 *                  If the call succeeds then it initializes (or updates) the DNSServiceRef,
 *                  returns kDNSServiceErr_NoError, and the query operation
 *                  will remain active indefinitely until the client terminates it
 *                  by passing this DNSServiceRef to DNSServiceRefDeallocate()
 *                  (or by closing the underlying shared connection, if used).
 *
 * flags:           Possible values are:
 *                  kDNSServiceFlagsShareConnection to use a shared connection.
 *                  kDNSServiceFlagsForceMulticast or kDNSServiceFlagsLongLivedQuery.
 *                  Pass kDNSServiceFlagsLongLivedQuery to create a "long-lived" unicast
 *                  query to a unicast DNS server that implements the protocol. This flag
 *                  has no effect on link-local multicast queries.
 *
 * interfaceIndex:  If non-zero, specifies the interface on which to issue the query
 *                  (the index for a given interface is determined via the if_nametoindex()
 *                  family of calls.) Passing 0 causes the name to be queried for on all
 *                  interfaces. See "Constants for specifying an interface index" for more details.
 *
 * fullname:        The full domain name of the resource record to be queried for.
 *
 * rrtype:          The numerical type of the resource record to be queried for
 *                  (e.g. kDNSServiceType_PTR, kDNSServiceType_SRV, etc)
 *
 * rrclass:         The class of the resource record (usually kDNSServiceClass_IN).
 *
 * callBack:        The function to be called when a result is found, or if the call
 *                  asynchronously fails.
 *
 * context:         An application context pointer which is passed to the callback function
 *                  (may be NULL).
 *
 * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
 *                  errors are delivered to the callback), otherwise returns an error code indicating
 *                  the error that occurred (the callback is never invoked and the DNSServiceRef
 *                  is not initialized).
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
(
    DNSServiceRef                       *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char                          *fullname,
    uint16_t rrtype,
    uint16_t rrclass,
    DNSServiceQueryRecordReply callBack,
    void                                *context  /* may be NULL */
);


/*********************************************************************************************
*
*  Unified lookup of both IPv4 and IPv6 addresses for a fully qualified hostname
*
*********************************************************************************************/

/* DNSServiceGetAddrInfo
 *
 * Queries for the IP address of a hostname by using either Multicast or Unicast DNS.
 *
 * DNSServiceGetAddrInfoReply() parameters:
 *
 * sdRef:           The DNSServiceRef initialized by DNSServiceGetAddrInfo().
 *
 * flags:           Possible values are kDNSServiceFlagsMoreComing and
 *                  kDNSServiceFlagsAdd.
 *
 * interfaceIndex:  The interface to which the answers pertain.
 *
 * errorCode:       Will be kDNSServiceErr_NoError on success, otherwise will
 *                  indicate the failure that occurred.  Other parameters are
 *                  undefined if errorCode is nonzero.
 *
 * hostname:        The fully qualified domain name of the host to be queried for.
 *
 * address:         IPv4 or IPv6 address.
 *
 * ttl:             If the client wishes to cache the result for performance reasons,
 *                  the TTL indicates how long the client may legitimately hold onto
 *                  this result, in seconds. After the TTL expires, the client should
 *                  consider the result no longer valid, and if it requires this data
 *                  again, it should be re-fetched with a new query. Of course, this
 *                  only applies to clients that cancel the asynchronous operation when
 *                  they get a result. Clients that leave the asynchronous operation
 *                  running can safely assume that the data remains valid until they
 *                  get another callback telling them otherwise. The ttl value is not
 *                  updated when the daemon answers from the cache, hence relying on
 *                  the accuracy of the ttl value is not recommended.
 *
 * context:         The context pointer that was passed to the callout.
 *
 */

typedef void (DNSSD_API *DNSServiceGetAddrInfoReply)
(
    DNSServiceRef sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    DNSServiceErrorType errorCode,
    const char                       *hostname,
    const struct sockaddr            *address,
    uint32_t ttl,
    void                             *context
);


/* DNSServiceGetAddrInfo() Parameters:
 *
 * sdRef:           A pointer to an uninitialized DNSServiceRef
 *                  (or, if the kDNSServiceFlagsShareConnection flag is used,
 *                  a copy of the shared connection reference that is to be used).
 *                  If the call succeeds then it initializes (or updates) the DNSServiceRef,
 *                  returns kDNSServiceErr_NoError, and the address query operation
 *                  will remain active indefinitely until the client terminates it
 *                  by passing this DNSServiceRef to DNSServiceRefDeallocate()
 *                  (or by closing the underlying shared connection, if used).
 *
 * flags:           Possible values are:
 *                  kDNSServiceFlagsShareConnection to use a shared connection.
 *                  kDNSServiceFlagsForceMulticast
 *
 * interfaceIndex:  The interface on which to issue the query.  Passing 0 causes the query to be
 *                  sent on all active interfaces via Multicast or the primary interface via Unicast.
 *
 * protocol:        Pass in kDNSServiceProtocol_IPv4 to look up IPv4 addresses, or kDNSServiceProtocol_IPv6
 *                  to look up IPv6 addresses, or both to look up both kinds. If neither flag is
 *                  set, the system will apply an intelligent heuristic, which is (currently)
 *                  that it will attempt to look up both, except:
 *
 *                   * If "hostname" is a wide-area unicast DNS hostname (i.e. not a ".local." name)
 *                     but this host has no routable IPv6 address, then the call will not try to
 *                     look up IPv6 addresses for "hostname", since any addresses it found would be
 *                     unlikely to be of any use anyway. Similarly, if this host has no routable
 *                     IPv4 address, the call will not try to look up IPv4 addresses for "hostname".
 *
 * hostname:        The fully qualified domain name of the host to be queried for.
 *
 * callBack:        The function to be called when the query succeeds or fails asynchronously.
 *
 * context:         An application context pointer which is passed to the callback function
 *                  (may be NULL).
 *
 * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
 *                  errors are delivered to the callback), otherwise returns an error code indicating
 *                  the error that occurred.
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
(
    DNSServiceRef                    *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    DNSServiceProtocol protocol,
    const char                       *hostname,
    DNSServiceGetAddrInfoReply callBack,
    void                             *context          /* may be NULL */
);


/*********************************************************************************************
*
*  Special Purpose Calls:
*  DNSServiceCreateConnection(), DNSServiceRegisterRecord(), DNSServiceReconfirmRecord()
*  (most applications will not use these)
*
*********************************************************************************************/

/* DNSServiceCreateConnection()
 *
 * Create a connection to the daemon allowing efficient registration of
 * multiple individual records.
 *
 * Parameters:
 *
 * sdRef:           A pointer to an uninitialized DNSServiceRef.
 *                  Deallocating the reference (via DNSServiceRefDeallocate())
 *                  severs the connection and cancels all operations and
 *                  deregisters all records registered on this connection.
 *
 * return value:    Returns kDNSServiceErr_NoError on success, otherwise returns
 *                  an error code indicating the specific failure that occurred
 *                  (in which case the DNSServiceRef is not initialized).
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceCreateConnection(DNSServiceRef *sdRef);

/* DNSServiceRegisterRecord
 *
 * Register an individual resource record on a connected DNSServiceRef.
 *
 * Note that name conflicts occurring for records registered via this call must be handled
 * by the client in the callback.
 *
 * DNSServiceRegisterRecordReply() parameters:
 *
 * sdRef:           The connected DNSServiceRef initialized by
 *                  DNSServiceCreateConnection().
 *
 * RecordRef:       The DNSRecordRef initialized by DNSServiceRegisterRecord(). If the above
 *                  DNSServiceRef is passed to DNSServiceRefDeallocate(), this DNSRecordRef is
 *                  invalidated, and may not be used further.
 *
 * flags:           Currently unused, reserved for future use.
 *
 * errorCode:       Will be kDNSServiceErr_NoError on success, otherwise will
 *                  indicate the failure that occurred (including name conflicts.)
 *                  Other parameters are undefined if errorCode is nonzero.
 *
 * context:         The context pointer that was passed to the callout.
 *
 */

typedef void (DNSSD_API *DNSServiceRegisterRecordReply)
(
    DNSServiceRef sdRef,
    DNSRecordRef RecordRef,
    DNSServiceFlags flags,
    DNSServiceErrorType errorCode,
    void                                *context
);


/* DNSServiceRegisterRecord() Parameters:
 *
 * sdRef:           A DNSServiceRef initialized by DNSServiceCreateConnection().
 *
 * RecordRef:       A pointer to an uninitialized DNSRecordRef. Upon succesfull completion of this
 *                  call, this ref may be passed to DNSServiceUpdateRecord() or DNSServiceRemoveRecord().
 *                  (To deregister ALL records registered on a single connected DNSServiceRef
 *                  and deallocate each of their corresponding DNSServiceRecordRefs, call
 *                  DNSServiceRefDeallocate()).
 *
 * flags:           One of either kDNSServiceFlagsShared, kDNSServiceFlagsUnique or kDNSServiceFlagsKnownUnique must be set.
 *
 * interfaceIndex:  If non-zero, specifies the interface on which to register the record
 *                  (the index for a given interface is determined via the if_nametoindex()
 *                  family of calls.) Passing 0 causes the record to be registered on all interfaces.
 *                  See "Constants for specifying an interface index" for more details.
 *
 * fullname:        The full domain name of the resource record.
 *
 * rrtype:          The numerical type of the resource record (e.g. kDNSServiceType_PTR, kDNSServiceType_SRV, etc)
 *
 * rrclass:         The class of the resource record (usually kDNSServiceClass_IN)
 *
 * rdlen:           Length, in bytes, of the rdata.
 *
 * rdata:           A pointer to the raw rdata, as it is to appear in the DNS record.
 *
 * ttl:             The time to live of the resource record, in seconds.
 *                  Most clients should pass 0 to indicate that the system should
 *                  select a sensible default value.
 *
 * callBack:        The function to be called when a result is found, or if the call
 *                  asynchronously fails (e.g. because of a name conflict.)
 *
 * context:         An application context pointer which is passed to the callback function
 *                  (may be NULL).
 *
 * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
 *                  errors are delivered to the callback), otherwise returns an error code indicating
 *                  the error that occurred (the callback is never invoked and the DNSRecordRef is
 *                  not initialized).
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
(
    DNSServiceRef sdRef,
    DNSRecordRef                        *RecordRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char                          *fullname,
    uint16_t rrtype,
    uint16_t rrclass,
    uint16_t rdlen,
    const void                          *rdata,
    uint32_t ttl,
    DNSServiceRegisterRecordReply callBack,
    void                                *context    /* may be NULL */
);


/* DNSServiceReconfirmRecord
 *
 * Instruct the daemon to verify the validity of a resource record that appears
 * to be out of date (e.g. because TCP connection to a service's target failed.)
 * Causes the record to be flushed from the daemon's cache (as well as all other
 * daemons' caches on the network) if the record is determined to be invalid.
 * Use this routine conservatively. Reconfirming a record necessarily consumes
 * network bandwidth, so this should not be done indiscriminately.
 *
 * Parameters:
 *
 * flags:           Not currently used.
 *
 * interfaceIndex:  Specifies the interface of the record in question.
 *                  The caller must specify the interface.
 *                  This API (by design) causes increased network traffic, so it requires
 *                  the caller to be precise about which record should be reconfirmed.
 *                  It is not possible to pass zero for the interface index to perform
 *                  a "wildcard" reconfirmation, where *all* matching records are reconfirmed.
 *
 * fullname:        The resource record's full domain name.
 *
 * rrtype:          The resource record's type (e.g. kDNSServiceType_PTR, kDNSServiceType_SRV, etc)
 *
 * rrclass:         The class of the resource record (usually kDNSServiceClass_IN).
 *
 * rdlen:           The length, in bytes, of the resource record rdata.
 *
 * rdata:           The raw rdata of the resource record.
 *
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
(
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char                         *fullname,
    uint16_t rrtype,
    uint16_t rrclass,
    uint16_t rdlen,
    const void                         *rdata
);


/*********************************************************************************************
*
*  NAT Port Mapping
*
*********************************************************************************************/

/* DNSServiceNATPortMappingCreate
 *
 * Request a port mapping in the NAT gateway, which maps a port on the local machine
 * to an external port on the NAT. The NAT should support either PCP, NAT-PMP or the
 * UPnP/IGD protocol for this API to create a successful mapping. Note that this API
 * currently supports IPv4 addresses/mappings only. If the NAT gateway supports PCP and
 * returns an IPv6 address (incorrectly, since this API specifically requests IPv4
 * addresses), the DNSServiceNATPortMappingReply callback will be invoked with errorCode
 * kDNSServiceErr_NATPortMappingUnsupported.
 *
 * The port mapping will be renewed indefinitely until the client process exits, or
 * explicitly terminates the port mapping request by calling DNSServiceRefDeallocate().
 * The client callback will be invoked, informing the client of the NAT gateway's
 * external IP address and the external port that has been allocated for this client.
 * The client should then record this external IP address and port using whatever
 * directory service mechanism it is using to enable peers to connect to it.
 * (Clients advertising services using Wide-Area DNS-SD DO NOT need to use this API
 * -- when a client calls DNSServiceRegister() NAT mappings are automatically created
 * and the external IP address and port for the service are recorded in the global DNS.
 * Only clients using some directory mechanism other than Wide-Area DNS-SD need to use
 * this API to explicitly map their own ports.)
 *
 * It's possible that the client callback could be called multiple times, for example
 * if the NAT gateway's IP address changes, or if a configuration change results in a
 * different external port being mapped for this client. Over the lifetime of any long-lived
 * port mapping, the client should be prepared to handle these notifications of changes
 * in the environment, and should update its recorded address and/or port as appropriate.
 *
 * NOTE: There are two unusual aspects of how the DNSServiceNATPortMappingCreate API works,
 * which were intentionally designed to help simplify client code:
 *
 *  1. It's not an error to request a NAT mapping when the machine is not behind a NAT gateway.
 *     In other NAT mapping APIs, if you request a NAT mapping and the machine is not behind a NAT
 *     gateway, then the API returns an error code -- it can't get you a NAT mapping if there's no
 *     NAT gateway. The DNSServiceNATPortMappingCreate API takes a different view. Working out
 *     whether or not you need a NAT mapping can be tricky and non-obvious, particularly on
 *     a machine with multiple active network interfaces. Rather than make every client recreate
 *     this logic for deciding whether a NAT mapping is required, the PortMapping API does that
 *     work for you. If the client calls the PortMapping API when the machine already has a
 *     routable public IP address, then instead of complaining about it and giving an error,
 *     the PortMapping API just invokes your callback, giving the machine's public address
 *     and your own port number. This means you don't need to write code to work out whether
 *     your client needs to call the PortMapping API -- just call it anyway, and if it wasn't
 *     necessary, no harm is done:
 *
 *     - If the machine already has a routable public IP address, then your callback
 *       will just be invoked giving your own address and port.
 *     - If a NAT mapping is required and obtained, then your callback will be invoked
 *       giving you the external address and port.
 *     - If a NAT mapping is required but not obtained from the local NAT gateway,
 *       or the machine has no network connectivity, then your callback will be
 *       invoked giving zero address and port.
 *
 *  2. In other NAT mapping APIs, if a laptop computer is put to sleep and woken up on a new
 *     network, it's the client's job to notice this, and work out whether a NAT mapping
 *     is required on the new network, and make a new NAT mapping request if necessary.
 *     The DNSServiceNATPortMappingCreate API does this for you, automatically.
 *     The client just needs to make one call to the PortMapping API, and its callback will
 *     be invoked any time the mapping state changes. This property complements point (1) above.
 *     If the client didn't make a NAT mapping request just because it determined that one was
 *     not required at that particular moment in time, the client would then have to monitor
 *     for network state changes to determine if a NAT port mapping later became necessary.
 *     By unconditionally making a NAT mapping request, even when a NAT mapping not to be
 *     necessary, the PortMapping API will then begin monitoring network state changes on behalf of
 *     the client, and if a NAT mapping later becomes necessary, it will automatically create a NAT
 *     mapping and inform the client with a new callback giving the new address and port information.
 *
 * DNSServiceNATPortMappingReply() parameters:
 *
 * sdRef:           The DNSServiceRef initialized by DNSServiceNATPortMappingCreate().
 *
 * flags:           Currently unused, reserved for future use.
 *
 * interfaceIndex:  The interface through which the NAT gateway is reached.
 *
 * errorCode:       Will be kDNSServiceErr_NoError on success.
 *                  Will be kDNSServiceErr_DoubleNAT when the NAT gateway is itself behind one or
 *                  more layers of NAT, in which case the other parameters have the defined values.
 *                  For other failures, will indicate the failure that occurred, and the other
 *                  parameters are undefined.
 *
 * externalAddress: Four byte IPv4 address in network byte order.
 *
 * protocol:        Will be kDNSServiceProtocol_UDP or kDNSServiceProtocol_TCP or both.
 *
 * internalPort:    The port on the local machine that was mapped.
 *
 * externalPort:    The actual external port in the NAT gateway that was mapped.
 *                  This is likely to be different than the requested external port.
 *
 * ttl:             The lifetime of the NAT port mapping created on the gateway.
 *                  This controls how quickly stale mappings will be garbage-collected
 *                  if the client machine crashes, suffers a power failure, is disconnected
 *                  from the network, or suffers some other unfortunate demise which
 *                  causes it to vanish without explicitly removing its NAT port mapping.
 *                  It's possible that the ttl value will differ from the requested ttl value.
 *
 * context:         The context pointer that was passed to the callout.
 *
 */

typedef void (DNSSD_API *DNSServiceNATPortMappingReply)
(
    DNSServiceRef sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    DNSServiceErrorType errorCode,
    uint32_t externalAddress,                           /* four byte IPv4 address in network byte order */
    DNSServiceProtocol protocol,
    uint16_t internalPort,                              /* In network byte order */
    uint16_t externalPort,                              /* In network byte order and may be different than the requested port */
    uint32_t ttl,                                       /* may be different than the requested ttl */
    void                             *context
);


/* DNSServiceNATPortMappingCreate() Parameters:
 *
 * sdRef:           A pointer to an uninitialized DNSServiceRef
 *                  (or, if the kDNSServiceFlagsShareConnection flag is used,
 *                  a copy of the shared connection reference that is to be used).
 *                  If the call succeeds then it initializes (or updates) the DNSServiceRef,
 *                  returns kDNSServiceErr_NoError, and the NAT port mapping
 *                  will remain active indefinitely until the client terminates it
 *                  by passing this DNSServiceRef to DNSServiceRefDeallocate()
 *                  (or by closing the underlying shared connection, if used).
 *
 * flags:           Possible values are:
 *                  kDNSServiceFlagsShareConnection to use a shared connection.
 *
 * interfaceIndex:  The interface on which to create port mappings in a NAT gateway.
 *                  Passing 0 causes the port mapping request to be sent on the primary interface.
 *
 * protocol:        To request a port mapping, pass in kDNSServiceProtocol_UDP, or kDNSServiceProtocol_TCP,
 *                  or (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP) to map both.
 *                  The local listening port number must also be specified in the internalPort parameter.
 *                  To just discover the NAT gateway's external IP address, pass zero for protocol,
 *                  internalPort, externalPort and ttl.
 *
 * internalPort:    The port number in network byte order on the local machine which is listening for packets.
 *
 * externalPort:    The requested external port in network byte order in the NAT gateway that you would
 *                  like to map to the internal port. Pass 0 if you don't care which external port is chosen for you.
 *
 * ttl:             The requested renewal period of the NAT port mapping, in seconds.
 *                  If the client machine crashes, suffers a power failure, is disconnected from
 *                  the network, or suffers some other unfortunate demise which causes it to vanish
 *                  unexpectedly without explicitly removing its NAT port mappings, then the NAT gateway
 *                  will garbage-collect old stale NAT port mappings when their lifetime expires.
 *                  Requesting a short TTL causes such orphaned mappings to be garbage-collected
 *                  more promptly, but consumes system resources and network bandwidth with
 *                  frequent renewal packets to keep the mapping from expiring.
 *                  Requesting a long TTL is more efficient on the network, but in the event of the
 *                  client vanishing, stale NAT port mappings will not be garbage-collected as quickly.
 *                  Most clients should pass 0 to use a system-wide default value.
 *
 * callBack:        The function to be called when the port mapping request succeeds or fails asynchronously.
 *
 * context:         An application context pointer which is passed to the callback function
 *                  (may be NULL).
 *
 * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
 *                  errors are delivered to the callback), otherwise returns an error code indicating
 *                  the error that occurred.
 *
 *                  If you don't actually want a port mapped, and are just calling the API
 *                  because you want to find out the NAT's external IP address (e.g. for UI
 *                  display) then pass zero for protocol, internalPort, externalPort and ttl.
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
(
    DNSServiceRef                    *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    DNSServiceProtocol protocol,                        /* TCP and/or UDP          */
    uint16_t internalPort,                              /* network byte order      */
    uint16_t externalPort,                              /* network byte order      */
    uint32_t ttl,                                       /* time to live in seconds */
    DNSServiceNATPortMappingReply callBack,
    void                             *context           /* may be NULL             */
);


/*********************************************************************************************
*
*  General Utility Functions
*
*********************************************************************************************/

/* DNSServiceConstructFullName()
 *
 * Concatenate a three-part domain name (as returned by the above callbacks) into a
 * properly-escaped full domain name. Note that callbacks in the above functions ALREADY ESCAPE
 * strings where necessary.
 *
 * Parameters:
 *
 * fullName:        A pointer to a buffer that where the resulting full domain name is to be written.
 *                  The buffer must be kDNSServiceMaxDomainName (1009) bytes in length to
 *                  accommodate the longest legal domain name without buffer overrun.
 *
 * service:         The service name - any dots or backslashes must NOT be escaped.
 *                  May be NULL (to construct a PTR record name, e.g.
 *                  "_ftp._tcp.apple.com.").
 *
 * regtype:         The service type followed by the protocol, separated by a dot
 *                  (e.g. "_ftp._tcp").
 *
 * domain:          The domain name, e.g. "apple.com.". Literal dots or backslashes,
 *                  if any, must be escaped, e.g. "1st\. Floor.apple.com."
 *
 * return value:    Returns kDNSServiceErr_NoError (0) on success, kDNSServiceErr_BadParam on error.
 *
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceConstructFullName
(
    char                            * const fullName,
    const char                      * const service,      /* may be NULL */
    const char                      * const regtype,
    const char                      * const domain
);


/*********************************************************************************************
*
*   TXT Record Construction Functions
*
*********************************************************************************************/

/*
 * A typical calling sequence for TXT record construction is something like:
 *
 * Client allocates storage for TXTRecord data (e.g. declare buffer on the stack)
 * TXTRecordCreate();
 * TXTRecordSetValue();
 * TXTRecordSetValue();
 * TXTRecordSetValue();
 * ...
 * DNSServiceRegister( ... TXTRecordGetLength(), TXTRecordGetBytesPtr() ... );
 * TXTRecordDeallocate();
 * Explicitly deallocate storage for TXTRecord data (if not allocated on the stack)
 */


/* TXTRecordRef
 *
 * Opaque internal data type.
 * Note: Represents a DNS-SD TXT record.
 */

typedef union _TXTRecordRef_t { char PrivateData[16]; char *ForceNaturalAlignment; } TXTRecordRef;


/* TXTRecordCreate()
 *
 * Creates a new empty TXTRecordRef referencing the specified storage.
 *
 * If the buffer parameter is NULL, or the specified storage size is not
 * large enough to hold a key subsequently added using TXTRecordSetValue(),
 * then additional memory will be added as needed using malloc(). Note that
 * an existing TXT record buffer should not be passed to TXTRecordCreate
 * to create a copy of another TXT Record. The correct way to copy TXTRecordRef
 * is creating an empty TXTRecordRef with TXTRecordCreate() first, and using
 * TXTRecordSetValue to set the same value.  
 *
 * On some platforms, when memory is low, malloc() may fail. In this
 * case, TXTRecordSetValue() will return kDNSServiceErr_NoMemory, and this
 * error condition will need to be handled as appropriate by the caller.
 *
 * You can avoid the need to handle this error condition if you ensure
 * that the storage you initially provide is large enough to hold all
 * the key/value pairs that are to be added to the record.
 * The caller can precompute the exact length required for all of the
 * key/value pairs to be added, or simply provide a fixed-sized buffer
 * known in advance to be large enough.
 * A no-value (key-only) key requires  (1 + key length) bytes.
 * A key with empty value requires     (1 + key length + 1) bytes.
 * A key with non-empty value requires (1 + key length + 1 + value length).
 * For most applications, DNS-SD TXT records are generally
 * less than 100 bytes, so in most cases a simple fixed-sized
 * 256-byte buffer will be more than sufficient.
 * Recommended size limits for DNS-SD TXT Records are discussed in RFC 6763
 * <https://tools.ietf.org/html/rfc6763#section-6.2>
 *
 * Note: When passing parameters to and from these TXT record APIs,
 * the key name does not include the '=' character. The '=' character
 * is the separator between the key and value in the on-the-wire
 * packet format; it is not part of either the key or the value.
 *
 * txtRecord:       A pointer to an uninitialized TXTRecordRef.
 *
 * bufferLen:       The size of the storage provided in the "buffer" parameter.
 *
 * buffer:          Optional caller-supplied storage used to hold the TXTRecord data.
 *                  This storage must remain valid for as long as
 *                  the TXTRecordRef.
 */

DNSSD_EXPORT
void DNSSD_API TXTRecordCreate
(
    TXTRecordRef     *txtRecord,
    uint16_t bufferLen,
    void             *buffer
);


/* TXTRecordDeallocate()
 *
 * Releases any resources allocated in the course of preparing a TXT Record
 * using TXTRecordCreate()/TXTRecordSetValue()/TXTRecordRemoveValue().
 * Ownership of the buffer provided in TXTRecordCreate() returns to the client.
 *
 * txtRecord:           A TXTRecordRef initialized by calling TXTRecordCreate().
 *
 */

DNSSD_EXPORT
void DNSSD_API TXTRecordDeallocate
(
    TXTRecordRef     *txtRecord
);


/* TXTRecordSetValue()
 *
 * Adds a key (optionally with value) to a TXTRecordRef. If the "key" already
 * exists in the TXTRecordRef, then the current value will be replaced with
 * the new value.
 * Keys may exist in four states with respect to a given TXT record:
 *  - Absent (key does not appear at all)
 *  - Present with no value ("key" appears alone)
 *  - Present with empty value ("key=" appears in TXT record)
 *  - Present with non-empty value ("key=value" appears in TXT record)
 * For more details refer to "Data Syntax for DNS-SD TXT Records" in RFC 6763
 * <https://tools.ietf.org/html/rfc6763#section-6>
 *
 * txtRecord:       A TXTRecordRef initialized by calling TXTRecordCreate().
 *
 * key:             A null-terminated string which only contains printable ASCII
 *                  values (0x20-0x7E), excluding '=' (0x3D). Keys should be
 *                  9 characters or fewer (not counting the terminating null).
 *
 * valueSize:       The size of the value.
 *
 * value:           Any binary value. For values that represent
 *                  textual data, UTF-8 is STRONGLY recommended.
 *                  For values that represent textual data, valueSize
 *                  should NOT include the terminating null (if any)
 *                  at the end of the string.
 *                  If NULL, then "key" will be added with no value.
 *                  If non-NULL but valueSize is zero, then "key=" will be
 *                  added with empty value.
 *
 * return value:    Returns kDNSServiceErr_NoError on success.
 *                  Returns kDNSServiceErr_Invalid if the "key" string contains
 *                  illegal characters.
 *                  Returns kDNSServiceErr_NoMemory if adding this key would
 *                  exceed the available storage.
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API TXTRecordSetValue
(
    TXTRecordRef     *txtRecord,
    const char       *key,
    uint8_t valueSize,                 /* may be zero */
    const void       *value            /* may be NULL */
);


/* TXTRecordRemoveValue()
 *
 * Removes a key from a TXTRecordRef. The "key" must be an
 * ASCII string which exists in the TXTRecordRef.
 *
 * txtRecord:       A TXTRecordRef initialized by calling TXTRecordCreate().
 *
 * key:             A key name which exists in the TXTRecordRef.
 *
 * return value:    Returns kDNSServiceErr_NoError on success.
 *                  Returns kDNSServiceErr_NoSuchKey if the "key" does not
 *                  exist in the TXTRecordRef.
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API TXTRecordRemoveValue
(
    TXTRecordRef     *txtRecord,
    const char       *key
);


/* TXTRecordGetLength()
 *
 * Allows you to determine the length of the raw bytes within a TXTRecordRef.
 *
 * txtRecord:       A TXTRecordRef initialized by calling TXTRecordCreate().
 *
 * return value:    Returns the size of the raw bytes inside a TXTRecordRef
 *                  which you can pass directly to DNSServiceRegister() or
 *                  to DNSServiceUpdateRecord().
 *                  Returns 0 if the TXTRecordRef is empty.
 */

DNSSD_EXPORT
uint16_t DNSSD_API TXTRecordGetLength
(
    const TXTRecordRef *txtRecord
);


/* TXTRecordGetBytesPtr()
 *
 * Allows you to retrieve a pointer to the raw bytes within a TXTRecordRef.
 *
 * txtRecord:       A TXTRecordRef initialized by calling TXTRecordCreate().
 *
 * return value:    Returns a pointer to the raw bytes inside the TXTRecordRef
 *                  which you can pass directly to DNSServiceRegister() or
 *                  to DNSServiceUpdateRecord().
 */

DNSSD_EXPORT
const void * DNSSD_API TXTRecordGetBytesPtr
(
    const TXTRecordRef *txtRecord
);


/*********************************************************************************************
*
*   TXT Record Parsing Functions
*
*********************************************************************************************/

/*
 * A typical calling sequence for TXT record parsing is something like:
 *
 * Receive TXT record data in DNSServiceResolve() callback
 * if (TXTRecordContainsKey(txtLen, txtRecord, "key")) then do something
 * val1ptr = TXTRecordGetValuePtr(txtLen, txtRecord, "key1", &len1);
 * val2ptr = TXTRecordGetValuePtr(txtLen, txtRecord, "key2", &len2);
 * ...
 * memcpy(myval1, val1ptr, len1);
 * memcpy(myval2, val2ptr, len2);
 * ...
 * return;
 *
 * If you wish to retain the values after return from the DNSServiceResolve()
 * callback, then you need to copy the data to your own storage using memcpy()
 * or similar, as shown in the example above.
 *
 * If for some reason you need to parse a TXT record you built yourself
 * using the TXT record construction functions above, then you can do
 * that using TXTRecordGetLength and TXTRecordGetBytesPtr calls:
 * TXTRecordGetValue(TXTRecordGetLength(x), TXTRecordGetBytesPtr(x), key, &len);
 *
 * Most applications only fetch keys they know about from a TXT record and
 * ignore the rest.
 * However, some debugging tools wish to fetch and display all keys.
 * To do that, use the TXTRecordGetCount() and TXTRecordGetItemAtIndex() calls.
 */

/* TXTRecordContainsKey()
 *
 * Allows you to determine if a given TXT Record contains a specified key.
 *
 * txtLen:          The size of the received TXT Record.
 *
 * txtRecord:       Pointer to the received TXT Record bytes.
 *
 * key:             A null-terminated ASCII string containing the key name.
 *
 * return value:    Returns 1 if the TXT Record contains the specified key.
 *                  Otherwise, it returns 0.
 */

DNSSD_EXPORT
int DNSSD_API TXTRecordContainsKey
(
    uint16_t txtLen,
    const void       *txtRecord,
    const char       *key
);


/* TXTRecordGetValuePtr()
 *
 * Allows you to retrieve the value for a given key from a TXT Record.
 *
 * txtLen:          The size of the received TXT Record
 *
 * txtRecord:       Pointer to the received TXT Record bytes.
 *
 * key:             A null-terminated ASCII string containing the key name.
 *
 * valueLen:        On output, will be set to the size of the "value" data.
 *
 * return value:    Returns NULL if the key does not exist in this TXT record,
 *                  or exists with no value (to differentiate between
 *                  these two cases use TXTRecordContainsKey()).
 *                  Returns pointer to location within TXT Record bytes
 *                  if the key exists with empty or non-empty value.
 *                  For empty value, valueLen will be zero.
 *                  For non-empty value, valueLen will be length of value data.
 */

DNSSD_EXPORT
const void * DNSSD_API TXTRecordGetValuePtr
(
    uint16_t txtLen,
    const void       *txtRecord,
    const char       *key,
    uint8_t          *valueLen
);


/* TXTRecordGetCount()
 *
 * Returns the number of keys stored in the TXT Record. The count
 * can be used with TXTRecordGetItemAtIndex() to iterate through the keys.
 *
 * txtLen:          The size of the received TXT Record.
 *
 * txtRecord:       Pointer to the received TXT Record bytes.
 *
 * return value:    Returns the total number of keys in the TXT Record.
 *
 */

DNSSD_EXPORT
uint16_t DNSSD_API TXTRecordGetCount
(
    uint16_t txtLen,
    const void       *txtRecord
);


/* TXTRecordGetItemAtIndex()
 *
 * Allows you to retrieve a key name and value pointer, given an index into
 * a TXT Record. Legal index values range from zero to TXTRecordGetCount()-1.
 * It's also possible to iterate through keys in a TXT record by simply
 * calling TXTRecordGetItemAtIndex() repeatedly, beginning with index zero
 * and increasing until TXTRecordGetItemAtIndex() returns kDNSServiceErr_Invalid.
 *
 * On return:
 * For keys with no value, *value is set to NULL and *valueLen is zero.
 * For keys with empty value, *value is non-NULL and *valueLen is zero.
 * For keys with non-empty value, *value is non-NULL and *valueLen is non-zero.
 *
 * txtLen:          The size of the received TXT Record.
 *
 * txtRecord:       Pointer to the received TXT Record bytes.
 *
 * itemIndex:       An index into the TXT Record.
 *
 * keyBufLen:       The size of the string buffer being supplied.
 *
 * key:             A string buffer used to store the key name.
 *                  On return, the buffer contains a null-terminated C-string
 *                  giving the key name. DNS-SD TXT keys are usually
 *                  9 characters or fewer. To hold the maximum possible
 *                  key name, the buffer should be 256 bytes long.
 *
 * valueLen:        On output, will be set to the size of the "value" data.
 *
 * value:           On output, *value is set to point to location within TXT
 *                  Record bytes that holds the value data.
 *
 * return value:    Returns kDNSServiceErr_NoError on success.
 *                  Returns kDNSServiceErr_NoMemory if keyBufLen is too short.
 *                  Returns kDNSServiceErr_Invalid if index is greater than
 *                  TXTRecordGetCount()-1.
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API TXTRecordGetItemAtIndex
(
    uint16_t txtLen,
    const void       *txtRecord,
    uint16_t itemIndex,
    uint16_t keyBufLen,
    char             *key,
    uint8_t          *valueLen,
    const void       **value
);

#if _DNS_SD_LIBDISPATCH
/*
 * DNSServiceSetDispatchQueue
 *
 * Allows you to schedule a DNSServiceRef on a serial dispatch queue for receiving asynchronous
 * callbacks.  It's the clients responsibility to ensure that the provided dispatch queue is running.
 *
 * A typical application that uses CFRunLoopRun or dispatch_main on its main thread will
 * usually schedule DNSServiceRefs on its main queue (which is always a serial queue)
 * using "DNSServiceSetDispatchQueue(sdref, dispatch_get_main_queue());"
 *
 * If there is any error during the processing of events, the application callback will
 * be called with an error code. For shared connections, each subordinate DNSServiceRef
 * will get its own error callback. Currently these error callbacks only happen
 * if the daemon is manually terminated or crashes, and the error
 * code in this case is kDNSServiceErr_ServiceNotRunning. The application must call
 * DNSServiceRefDeallocate to free the DNSServiceRef when it gets such an error code.
 * These error callbacks are rare and should not normally happen on customer machines,
 * but application code should be written defensively to handle such error callbacks
 * gracefully if they occur.
 *
 * After using DNSServiceSetDispatchQueue on a DNSServiceRef, calling DNSServiceProcessResult
 * on the same DNSServiceRef will result in undefined behavior and should be avoided.
 *
 * Once the application successfully schedules a DNSServiceRef on a serial dispatch queue using
 * DNSServiceSetDispatchQueue, it cannot remove the DNSServiceRef from the dispatch queue, or use
 * DNSServiceSetDispatchQueue a second time to schedule the DNSServiceRef onto a different serial dispatch
 * queue. Once scheduled onto a dispatch queue a DNSServiceRef will deliver events to that queue until
 * the application no longer requires that operation and terminates it using DNSServiceRefDeallocate.
 * Note that the call to DNSServiceRefDeallocate() must be done on the same queue originally passed 
 * as an argument to DNSServiceSetDispatchQueue().
 *
 * service:         DNSServiceRef that was allocated and returned to the application, when the
 *                  application calls one of the DNSService API.
 *
 * queue:           dispatch queue where the application callback will be scheduled
 *
 * return value:    Returns kDNSServiceErr_NoError on success.
 *                  Returns kDNSServiceErr_NoMemory if it cannot create a dispatch source
 *                  Returns kDNSServiceErr_BadParam if the service param is invalid or the
 *                  queue param is invalid
 */

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceSetDispatchQueue
(
    DNSServiceRef service,
    dispatch_queue_t queue
);
#endif //_DNS_SD_LIBDISPATCH

#if !defined(_WIN32)
typedef void (DNSSD_API *DNSServiceSleepKeepaliveReply)
(
    DNSServiceRef sdRef,
    DNSServiceErrorType errorCode,
    void                                *context
);
DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceSleepKeepalive
(
    DNSServiceRef                       *sdRef,
    DNSServiceFlags flags,
    int fd,
    unsigned int timeout,
    DNSServiceSleepKeepaliveReply callBack,
    void                                *context
);
#endif

/* Some C compiler cleverness. We can make the compiler check certain things for us,
 * and report errors at compile-time if anything is wrong. The usual way to do this would
 * be to use a run-time "if" statement or the conventional run-time "assert" mechanism, but
 * then you don't find out what's wrong until you run the software. This way, if the assertion
 * condition is false, the array size is negative, and the complier complains immediately.
 */

struct CompileTimeAssertionChecks_DNS_SD
{
    char assert0[(sizeof(union _TXTRecordRef_t) == 16) ? 1 : -1];
};

#ifdef  __cplusplus
}
#endif

#endif  /* _DNS_SD_H */
/*
 * Copyright (c) 2016-2020 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
 *
 *     https://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 _DNS_SD_INTERNAL_H
#define _DNS_SD_INTERNAL_H

// The mDNSResponder daemon doesn't call the private DNS-SD API.

#if !defined(DNS_SD_EXCLUDE_PRIVATE_API)
    #define DNS_SD_EXCLUDE_PRIVATE_API  1
#endif

#include "dns_sd_private.h"

#endif  // _DNS_SD_INTERNAL_H
/*
 * Copyright (c) 2015-2020 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
 *
 *     https://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 _DNS_SD_PRIVATE_H
#define _DNS_SD_PRIVATE_H

#include <dns_sd.h>

#if !defined(DNS_SD_EXCLUDE_PRIVATE_API)
    #if defined(__APPLE__)
        #define DNS_SD_EXCLUDE_PRIVATE_API  0
    #else
        #define DNS_SD_EXCLUDE_PRIVATE_API  1
    #endif
#endif

// Private flags (kDNSServiceFlagsPrivateOne, kDNSServiceFlagsPrivateTwo, kDNSServiceFlagsPrivateThree, kDNSServiceFlagsPrivateFour, kDNSServiceFlagsPrivateFive) from dns_sd.h
enum
{
    kDNSServiceFlagsDenyConstrained        = 0x2000,
    /*
     * This flag is meaningful only for Unicast DNS queries. When set, the daemon will restrict
     * DNS resolutions on interfaces defined as constrained for that request.
     */

    kDNSServiceFlagsDenyCellular           = 0x8000000,
    /*
     * This flag is meaningful only for Unicast DNS queries. When set, the daemon will restrict
     * DNS resolutions on the cellular interface for that request.
     */
    kDNSServiceFlagsServiceIndex           = 0x10000000,
    /*
     * This flag is meaningful only for DNSServiceGetAddrInfo() for Unicast DNS queries.
     * When set, DNSServiceGetAddrInfo() will interpret the "interfaceIndex" argument of the call
     * as the "serviceIndex".
     */

    kDNSServiceFlagsDenyExpensive          = 0x20000000,
    /*
     * This flag is meaningful only for Unicast DNS queries. When set, the daemon will restrict
     * DNS resolutions on interfaces defined as expensive for that request.
     */

    kDNSServiceFlagsPathEvaluationDone     = 0x40000000
    /*
     * This flag is meaningful for only Unicast DNS queries.
     * When set, it indicates that Network PathEvaluation has already been performed.
     */
};

#if !DNS_SD_EXCLUDE_PRIVATE_API
/* DNSServiceCreateDelegateConnection()
 *
 * Parameters:
 *
 * sdRef:           A pointer to an uninitialized DNSServiceRef. Deallocating
 *                  the reference (via DNSServiceRefDeallocate()) severs the
 *                  connection and deregisters all records registered on this connection.
 *
 * pid :            Process ID of the delegate
 *
 * uuid:            UUID of the delegate
 *
 *                  Note that only one of the two arguments (pid or uuid) can be specified. If pid
 *                  is zero, uuid will be assumed to be a valid value; otherwise pid will be used.
 *
 * return value:    Returns kDNSServiceErr_NoError on success, otherwise returns
 *                  an error code indicating the specific failure that occurred (in which
 *                  case the DNSServiceRef is not initialized). kDNSServiceErr_NotAuth is
 *                  returned to indicate that the calling process does not have entitlements
 *                  to use this API.
 */
DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceCreateDelegateConnection(DNSServiceRef *sdRef, int32_t pid, uuid_t uuid);

// Map the source port of the local UDP socket that was opened for sending the DNS query
// to the process ID of the application that triggered the DNS resolution.
//
/* DNSServiceGetPID() Parameters:
 *
 * srcport:         Source port (in network byte order) of the UDP socket that was created by
 *                  the daemon to send the DNS query on the wire.
 *
 * pid:             Process ID of the application that started the name resolution which triggered
 *                  the daemon to send the query on the wire. The value can be -1 if the srcport
 *                  cannot be mapped.
 *
 * return value:    Returns kDNSServiceErr_NoError on success, or kDNSServiceErr_ServiceNotRunning
 *                  if the daemon is not running. The value of the pid is undefined if the return
 *                  value has error.
 */
DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceGetPID
(
    uint16_t srcport,
    int32_t *pid
);

DNSSD_EXPORT
DNSServiceErrorType DNSSD_API DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags, const char *domain);

SPI_AVAILABLE(macos(10.15.4), ios(13.2.2), watchos(6.2), tvos(13.2))
DNSServiceErrorType DNSSD_API DNSServiceSleepKeepalive_sockaddr
(
    DNSServiceRef *                 sdRef,
    DNSServiceFlags                 flags,
    const struct sockaddr *         localAddr,
    const struct sockaddr *         remoteAddr,
    unsigned int                    timeout,
    DNSServiceSleepKeepaliveReply   callBack,
    void *                          context
);

/*!
 *  @brief
 *      Sets the default DNS resolver settings for the caller's process.
 *
 *  @param plist_data_ptr
 *      Pointer to an nw_resolver_config's binary property list data.
 *
 *  @param plist_data_len
 *      Byte-length of the binary property list data. Ignored if plist_data_ptr is NULL.
 *
 *  @param require_encryption
 *      Pass true if the process requires that DNS queries use an encrypted DNS service, such as DNS over HTTPS.
 *
 *  @result
 *      This function returns kDNSServiceErr_NoError on success, kDNSServiceErr_Invalid if plist_data_len
 *      exceeds 32,768, and kDNSServiceErr_NoMemory if it fails to allocate memory.
 *
 *  @discussion
 *      These settings only apply to the calling process's DNSServiceGetAddrInfo and DNSServiceQueryRecord
 *      requests. This function exists for code that may still use the legacy DNS-SD API for resolving
 *      hostnames, i.e., it implements the functionality of dnssd_getaddrinfo_set_need_encrypted_query(), but at
 *      a process-wide level of granularity.
 *
 *      Due to underlying IPC limitations, there's currently a 32 KB limit on the size of the binary property
 *      list data.
 */
SPI_AVAILABLE(macos(10.16), ios(14.0), watchos(7.0), tvos(14.0))
DNSServiceErrorType DNSSD_API DNSServiceSetResolverDefaults(const void *plist_data_ptr, size_t plist_data_len,
    bool require_encryption);
#endif  // !DNS_SD_EXCLUDE_PRIVATE_API

#define kDNSServiceCompPrivateDNS   "PrivateDNS"
#define kDNSServiceCompMulticastDNS "MulticastDNS"

#endif  // _DNS_SD_PRIVATE_H
/* -*- Mode: C; tab-width: 4 -*-
 *
 * Copyright (c) 2004-2018 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Inc. ("Apple") nor the names of its
 *     contributors may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#include <string.h>

#include "dns_sd.h"

#if defined(_WIN32)
// disable warning "conversion from <data> to uint16_t"
#pragma warning(disable:4244)
#define strncasecmp _strnicmp
#define strcasecmp _stricmp
#endif

/*********************************************************************************************
*
*  Supporting Functions
*
*********************************************************************************************/

#define mDNSIsDigit(X)     ((X) >= '0' && (X) <= '9')

// DomainEndsInDot returns 1 if name ends with a dot, 0 otherwise
// (DNSServiceConstructFullName depends this returning 1 for true, rather than any non-zero value meaning true)

static int DomainEndsInDot(const char *dom)
{
    while (dom[0] && dom[1])
    {
        if (dom[0] == '\\') // advance past escaped byte sequence
        {
            if (mDNSIsDigit(dom[1]) && mDNSIsDigit(dom[2]) && mDNSIsDigit(dom[3]))
                dom += 4;           // If "\ddd"    then skip four
            else dom += 2;          // else if "\x" then skip two
        }
        else dom++;                 // else goto next character
    }
    return (dom[0] == '.');
}

static uint8_t *InternalTXTRecordSearch
(
    uint16_t txtLen,
    const void       *txtRecord,
    const char       *key,
    unsigned long    *keylen
)
{
    uint8_t *p = (uint8_t*)txtRecord;
    uint8_t *e = p + txtLen;
    *keylen = (unsigned long) strlen(key);
    while (p<e)
    {
        uint8_t *x = p;
        p += 1 + p[0];
        if (p <= e && *keylen <= x[0] && !strncasecmp(key, (char*)x+1, *keylen))
            if (*keylen == x[0] || x[1+*keylen] == '=') return(x);
    }
    return(NULL);
}

/*********************************************************************************************
*
*  General Utility Functions
*
*********************************************************************************************/

// Note: Need to make sure we don't write more than kDNSServiceMaxDomainName (1009) bytes to fullName
// In earlier builds this constant was defined to be 1005, so to avoid buffer overruns on clients
// compiled with that constant we'll actually limit the output to 1005 bytes.

DNSServiceErrorType DNSSD_API DNSServiceConstructFullName
(
    char       *const fullName,
    const char *const service,      // May be NULL
    const char *const regtype,
    const char *const domain
)
{
    const size_t len = !regtype ? 0 : strlen(regtype) - DomainEndsInDot(regtype);
    char       *fn   = fullName;
    char *const lim  = fullName + 1005;
    const char *s    = service;
    const char *r    = regtype;
    const char *d    = domain;

    // regtype must be at least "x._udp" or "x._tcp"
    if (len < 6 || !domain || !domain[0]) return kDNSServiceErr_BadParam;
    if (strncasecmp((regtype + len - 4), "_tcp", 4) && strncasecmp((regtype + len - 4), "_udp", 4)) return kDNSServiceErr_BadParam;

    if (service && *service)
    {
        while (*s)
        {
            unsigned char c = *s++;             // Needs to be unsigned, or values like 0xFF will be interpreted as < 32
            if (c <= ' ')                       // Escape non-printable characters
            {
                if (fn+4 >= lim) goto fail;
                *fn++ = '\\';
                *fn++ = '0' + (c / 100);
                *fn++ = '0' + (c /  10) % 10;
                c     = '0' + (c      ) % 10;
            }
            else if (c == '.' || (c == '\\'))   // Escape dot and backslash literals
            {
                if (fn+2 >= lim) goto fail;
                *fn++ = '\\';
            }
            else
            if (fn+1 >= lim) goto fail;
            *fn++ = (char)c;
        }
        *fn++ = '.';
    }

    while (*r) if (fn+1 >= lim) goto fail;else *fn++ = *r++;
    if (!DomainEndsInDot(regtype)) { if (fn+1 >= lim) goto fail;else *fn++ = '.';}

    while (*d) if (fn+1 >= lim) goto fail;else *fn++ = *d++;
    if (!DomainEndsInDot(domain)) { if (fn+1 >= lim) goto fail;else *fn++ = '.';}

    *fn = '\0';
    return kDNSServiceErr_NoError;

fail:
    *fn = '\0';
    return kDNSServiceErr_BadParam;
}

/*********************************************************************************************
*
*   TXT Record Construction Functions
*
*********************************************************************************************/

typedef struct _TXTRecordRefRealType
{
    uint8_t  *buffer;       // Pointer to data
    uint16_t buflen;        // Length of buffer
    uint16_t datalen;       // Length currently in use
    uint16_t malloced;  // Non-zero if buffer was allocated via malloc()
} TXTRecordRefRealType;

#define txtRec ((TXTRecordRefRealType*)txtRecord)

// The opaque storage defined in the public dns_sd.h header is 16 bytes;
// make sure we don't exceed that.
struct CompileTimeAssertionCheck_dnssd_clientlib
{
    char assert0[(sizeof(TXTRecordRefRealType) <= 16) ? 1 : -1];
};

void DNSSD_API TXTRecordCreate
(
    TXTRecordRef     *txtRecord,
    uint16_t bufferLen,
    void             *buffer
)
{
    txtRec->buffer   = buffer;
    txtRec->buflen   = buffer ? bufferLen : (uint16_t)0;
    txtRec->datalen  = 0;
    txtRec->malloced = 0;
}

void DNSSD_API TXTRecordDeallocate(TXTRecordRef *txtRecord)
{
    if (txtRec->malloced) free(txtRec->buffer);
}

DNSServiceErrorType DNSSD_API TXTRecordSetValue
(
    TXTRecordRef     *txtRecord,
    const char       *key,
    uint8_t valueSize,
    const void       *value
)
{
    uint8_t *start, *p;
    const char *k;
    unsigned long keysize, keyvalsize;

    for (k = key; *k; k++) if (*k < 0x20 || *k > 0x7E || *k == '=') return(kDNSServiceErr_Invalid);
    keysize = (unsigned long)(k - key);
    keyvalsize = 1 + keysize + (value ? (1 + valueSize) : 0);
    if (keysize < 1 || keyvalsize > 255) return(kDNSServiceErr_Invalid);
    (void)TXTRecordRemoveValue(txtRecord, key);
    if (txtRec->datalen + keyvalsize > txtRec->buflen)
    {
        unsigned char *newbuf;
        unsigned long newlen = txtRec->datalen + keyvalsize;
        if (newlen > 0xFFFF) return(kDNSServiceErr_Invalid);
        newbuf = malloc((size_t)newlen);
        if (!newbuf) return(kDNSServiceErr_NoMemory);
        memcpy(newbuf, txtRec->buffer, txtRec->datalen);
        if (txtRec->malloced) free(txtRec->buffer);
        txtRec->buffer = newbuf;
        txtRec->buflen = (uint16_t)(newlen);
        txtRec->malloced = 1;
    }
    start = txtRec->buffer + txtRec->datalen;
    p = start + 1;
    memcpy(p, key, keysize);
    p += keysize;
    if (value)
    {
        *p++ = '=';
        memcpy(p, value, valueSize);
        p += valueSize;
    }
    *start = (uint8_t)(p - start - 1);
    txtRec->datalen += p - start;
    return(kDNSServiceErr_NoError);
}

DNSServiceErrorType DNSSD_API TXTRecordRemoveValue
(
    TXTRecordRef     *txtRecord,
    const char       *key
)
{
    unsigned long keylen, itemlen, remainder;
    uint8_t *item = InternalTXTRecordSearch(txtRec->datalen, txtRec->buffer, key, &keylen);
    if (!item) return(kDNSServiceErr_NoSuchKey);
    itemlen   = (unsigned long)(1 + item[0]);
    remainder = (unsigned long)((txtRec->buffer + txtRec->datalen) - (item + itemlen));
    // Use memmove because memcpy behaviour is undefined for overlapping regions
    memmove(item, item + itemlen, remainder);
    txtRec->datalen -= itemlen;
    return(kDNSServiceErr_NoError);
}

uint16_t DNSSD_API TXTRecordGetLength  (const TXTRecordRef *txtRecord) { return(txtRec->datalen); }
const void * DNSSD_API TXTRecordGetBytesPtr(const TXTRecordRef *txtRecord) { return(txtRec->buffer); }

/*********************************************************************************************
*
*   TXT Record Parsing Functions
*
*********************************************************************************************/

int DNSSD_API TXTRecordContainsKey
(
    uint16_t txtLen,
    const void       *txtRecord,
    const char       *key
)
{
    unsigned long keylen;
    return (InternalTXTRecordSearch(txtLen, txtRecord, key, &keylen) ? 1 : 0);
}

const void * DNSSD_API TXTRecordGetValuePtr
(
    uint16_t txtLen,
    const void       *txtRecord,
    const char       *key,
    uint8_t          *valueLen
)
{
    unsigned long keylen;
    uint8_t *item = InternalTXTRecordSearch(txtLen, txtRecord, key, &keylen);
    if (!item || item[0] <= keylen) return(NULL);   // If key not found, or found with no value, return NULL
    *valueLen = (uint8_t)(item[0] - (keylen + 1));
    return (item + 1 + keylen + 1);
}

uint16_t DNSSD_API TXTRecordGetCount
(
    uint16_t txtLen,
    const void       *txtRecord
)
{
    uint16_t count = 0;
    uint8_t *p = (uint8_t*)txtRecord;
    uint8_t *e = p + txtLen;
    while (p<e) { p += 1 + p[0]; count++; }
    return((p>e) ? (uint16_t)0 : count);
}

DNSServiceErrorType DNSSD_API TXTRecordGetItemAtIndex
(
    uint16_t txtLen,
    const void       *txtRecord,
    uint16_t itemIndex,
    uint16_t keyBufLen,
    char             *key,
    uint8_t          *valueLen,
    const void       **value
)
{
    uint16_t count = 0;
    uint8_t *p = (uint8_t*)txtRecord;
    uint8_t *e = p + txtLen;
    while (p<e && count<itemIndex) { p += 1 + p[0]; count++; }  // Find requested item
    if (p<e && p + 1 + p[0] <= e)   // If valid
    {
        uint8_t *x = p+1;
        unsigned long len = 0;
        e = p + 1 + p[0];
        while (x+len<e && x[len] != '=') len++;
        if (len >= keyBufLen) return(kDNSServiceErr_NoMemory);
        memcpy(key, x, len);
        key[len] = 0;
        if (x+len<e)        // If we found '='
        {
            *value = x + len + 1;
            *valueLen = (uint8_t)(p[0] - (len + 1));
        }
        else
        {
            *value = NULL;
            *valueLen = 0;
        }
        return(kDNSServiceErr_NoError);
    }
    return(kDNSServiceErr_Invalid);
}

/*********************************************************************************************
*
*   SCCS-compatible version string
*
*********************************************************************************************/

// For convenience when using the "strings" command, this is the last thing in the file

// 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)

// The "used" variable attribute prevents a non-exported variable from being stripped, even if its visibility is hidden,
// e.g., when compiling with -fvisibility=hidden.
#if defined(__GNUC__)
#define DNSSD_USED __attribute__((used))
#else
#define DNSSD_USED
#endif

// NOT static -- otherwise the compiler may optimize it out
// The "@(#) " pattern is a special prefix the "what" command looks for
#ifndef MDNS_VERSIONSTR_NODTS
const char VersionString_SCCS_libdnssd[] DNSSD_USED = "@(#) libdns_sd " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
#else
const char VersionString_SCCS_libdnssd[] = "@(#) libdns_sd " STRINGIFY(mDNSResponderVersion);
#endif
/* -*- Mode: C; tab-width: 4 -*-
 *
 * Copyright (c) 2003-2020 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Inc. ("Apple") nor the names of its
 *     contributors may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>

#include "dnssd_ipc.h"

#if APPLE_OSX_mDNSResponder
#include <mach-o/dyld.h>
#include <uuid/uuid.h>
#include <TargetConditionals.h>
#include "dns_sd_private.h"
#include "dnssd_clientstub_apple.h"
#include <CoreUtils/CommonServices.h>
#if !defined(__i386__)
#define CHECK_BUNDLE_VERSION  1
#else
#define CHECK_BUNDLE_VERSION  0
#endif
#endif

#if defined(_WIN32)

    #define _SSIZE_T
    #include <CommonServices.h>
    #include <DebugServices.h>
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <windows.h>
    #include <stdarg.h>
    #include <stdio.h>

    #define sockaddr_mdns sockaddr_in
    #define AF_MDNS AF_INET

// Disable warning: "'type cast' : from data pointer 'void *' to function pointer"
    #pragma warning(disable:4055)

// Disable warning: "nonstandard extension, function/data pointer conversion in expression"
    #pragma warning(disable:4152)

extern BOOL IsSystemServiceDisabled();

    #define sleep(X) Sleep((X) * 1000)

static int g_initWinsock = 0;
    #define LOG_WARNING kDebugLevelWarning
    #define LOG_INFO kDebugLevelInfo
static void syslog( int priority, const char * message, ...)
{
    va_list args;
    int len;
    char * buffer;
    DWORD err = WSAGetLastError();
    (void) priority;
    va_start( args, message );
    len = _vscprintf( message, args ) + 1;
    buffer = malloc( len * sizeof(char) );
    if ( buffer ) { vsnprintf( buffer, len, message, args ); OutputDebugString( buffer ); free( buffer ); }
    WSASetLastError( err );
}
#else

    #include <fcntl.h>      // For O_RDWR etc.
    #include <sys/time.h>
    #include <sys/socket.h>
    #include <syslog.h>

    #define sockaddr_mdns sockaddr_un
    #define AF_MDNS AF_LOCAL

#endif

#if CHECK_BUNDLE_VERSION
#include "bundle_utilities.h"
#include <os/feature_private.h>
#endif

#if defined(_WIN32)
// <rdar://problem/4096913> Specifies how many times we'll try and connect to the server.

#define DNSSD_CLIENT_MAXTRIES 4
#endif // _WIN32

// Uncomment the line below to use the old error return mechanism of creating a temporary named socket (e.g. in /var/tmp)
//#define USE_NAMED_ERROR_RETURN_SOCKET 1

// If the UDS client has not received a response from the daemon in 60 secs, it is unlikely to get one
// Note: Timeout of 3 secs should be sufficient in normal scenarios, but 60 secs is chosen as a safeguard since
// some clients may come up before mDNSResponder itself after a BOOT and on rare ocassions IOPM/Keychain/D2D calls
// in mDNSResponder's INIT may take a much longer time to return
#define DNSSD_CLIENT_TIMEOUT 60

#ifndef CTL_PATH_PREFIX
#define CTL_PATH_PREFIX "/var/tmp/dnssd_result_socket."
#endif

typedef struct
{
    ipc_msg_hdr ipc_hdr;
    DNSServiceFlags cb_flags;
    uint32_t cb_interface;
    DNSServiceErrorType cb_err;
} CallbackHeader;

typedef struct _DNSServiceRef_t DNSServiceOp;
typedef struct _DNSRecordRef_t DNSRecord;

#if !defined(_WIN32)
typedef struct
{
    void             *AppCallback;      // Client callback function and context
    void             *AppContext;
} SleepKAContext;
#endif

// client stub callback to process message from server and deliver results to client application
typedef void (*ProcessReplyFn)(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *msg, const char *const end);

#define ValidatorBits 0x12345678
#define DNSServiceRefValid(X) (dnssd_SocketValid((X)->sockfd) && (((X)->sockfd ^ (X)->validator) == ValidatorBits))

// When using kDNSServiceFlagsShareConnection, there is one primary _DNSServiceOp_t, and zero or more subordinates
// For the primary, the 'next' field points to the first subordinate, and its 'next' field points to the next, and so on.
// For the primary, the 'primary' field is NULL; for subordinates the 'primary' field points back to the associated primary
//
// _DNS_SD_LIBDISPATCH is defined where libdispatch/GCD is available. This does not mean that the application will use the
// DNSServiceSetDispatchQueue API. Hence any new code guarded with _DNS_SD_LIBDISPATCH should still be backwards compatible.
struct _DNSServiceRef_t
{
    DNSServiceOp     *next;             // For shared connection
    DNSServiceOp     *primary;          // For shared connection
    dnssd_sock_t sockfd;                // Connected socket between client and daemon
    dnssd_sock_t validator;             // Used to detect memory corruption, double disposals, etc.
    client_context_t uid;               // For shared connection requests, each subordinate DNSServiceRef has its own ID,
                                        // unique within the scope of the same shared parent DNSServiceRef
    uint32_t op;                        // request_op_t or reply_op_t
    uint32_t max_index;                 // Largest assigned record index - 0 if no additional records registered
    uint32_t logcounter;                // Counter used to control number of syslog messages we write
    int              *moreptr;          // Set while DNSServiceProcessResult working on this particular DNSServiceRef
    ProcessReplyFn ProcessReply;        // Function pointer to the code to handle received messages
    void             *AppCallback;      // Client callback function and context
    void             *AppContext;
    DNSRecord        *rec;
#if _DNS_SD_LIBDISPATCH
    dispatch_source_t disp_source;
    dispatch_queue_t disp_queue;
#endif
    void             *kacontext;
};

struct _DNSRecordRef_t
{
    DNSRecord       *recnext;
    void *AppContext;
    DNSServiceRegisterRecordReply AppCallback;
    DNSRecordRef recref;
    uint32_t record_index;  // index is unique to the ServiceDiscoveryRef
    client_context_t uid;  // For demultiplexing multiple DNSServiceRegisterRecord calls
    DNSServiceOp *sdr;
};

#if CHECK_BUNDLE_VERSION
static bool _should_return_noauth_error(void)
{
    static dispatch_once_t  s_once      = 0;
    static bool        s_should    = false;
    dispatch_once(&s_once,
    ^{
        s_should = bundle_sdk_is_ios14_or_later();
    });
    return s_should;
}
#endif

#if !defined(USE_TCP_LOOPBACK)
static void SetUDSPath(struct sockaddr_un *saddr, const char *path)
{
    size_t pathLen;

    pathLen = strlen(path);
    if (pathLen < sizeof(saddr->sun_path))
        memcpy(saddr->sun_path, path, pathLen + 1);
    else
        saddr->sun_path[0] = '\0';
}
#endif

enum { write_all_success = 0, write_all_fail = -1, write_all_defunct = -2 };

// Write len bytes. Return 0 on success, -1 on error
static int write_all(dnssd_sock_t sd, char *buf, size_t len)
{
    // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
    //if (send(sd, buf, len, MSG_WAITALL) != len) return write_all_fail;
    while (len)
    {
        ssize_t num_written = send(sd, buf, (long)len, 0);
        if (num_written < 0 || (size_t)num_written > len)
        {
            // Check whether socket has gone defunct,
            // otherwise, an error here indicates some OS bug
            // or that the mDNSResponder daemon crashed (which should never happen).
#if !defined(__ppc__) && defined(SO_ISDEFUNCT)
            int defunct = 0;
            socklen_t dlen = sizeof (defunct);
            if (getsockopt(sd, SOL_SOCKET, SO_ISDEFUNCT, &defunct, &dlen) < 0)
                syslog(LOG_WARNING, "dnssd_clientstub write_all: SO_ISDEFUNCT failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
            if (!defunct)
                syslog(LOG_WARNING, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd,
                       (long)num_written, (long)len,
                       (num_written < 0) ? dnssd_errno                 : 0,
                       (num_written < 0) ? dnssd_strerror(dnssd_errno) : "");
            else
                syslog(LOG_INFO, "dnssd_clientstub write_all(%d) DEFUNCT", sd);
            return defunct ? write_all_defunct : write_all_fail;
#else
            syslog(LOG_WARNING, "dnssd_clientstub write_all(%d) failed %ld/%ld %d %s", sd,
                   (long)num_written, (long)len,
                   (num_written < 0) ? dnssd_errno                 : 0,
                   (num_written < 0) ? dnssd_strerror(dnssd_errno) : "");
            return write_all_fail;
#endif
        }
        buf += num_written;
        len -= num_written;
    }
    return write_all_success;
}

enum { read_all_success = 0, read_all_fail = -1, read_all_wouldblock = -2, read_all_defunct = -3 };

// Read len bytes. Return 0 on success, read_all_fail on error, or read_all_wouldblock for
static int read_all(dnssd_sock_t sd, char *buf, int len)
{
    // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; use an explicit while() loop instead.
    //if (recv(sd, buf, len, MSG_WAITALL) != len) return -1;

    while (len)
    {
        ssize_t num_read = recv(sd, buf, len, 0);
        // It is valid to get an interrupted system call error e.g., somebody attaching
        // in a debugger, retry without failing
        if ((num_read < 0) && (errno == EINTR))
        {
            syslog(LOG_INFO, "dnssd_clientstub read_all: EINTR continue");
            continue;
        }
        if ((num_read == 0) || (num_read < 0) || (num_read > len))
        {
            int printWarn = 0;
            int defunct = 0;

            // Check whether socket has gone defunct,
            // otherwise, an error here indicates some OS bug
            // or that the mDNSResponder daemon crashed (which should never happen).
#if defined(WIN32)
            // <rdar://problem/7481776> Suppress logs for "A non-blocking socket operation
            //                          could not be completed immediately"
            if (WSAGetLastError() != WSAEWOULDBLOCK)
                printWarn = 1;
#endif
#if !defined(__ppc__) && defined(SO_ISDEFUNCT)
            {
                socklen_t dlen = sizeof (defunct);
                if (getsockopt(sd, SOL_SOCKET, SO_ISDEFUNCT, &defunct, &dlen) < 0)
                    syslog(LOG_WARNING, "dnssd_clientstub read_all: SO_ISDEFUNCT failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
            }
            if (!defunct)
                printWarn = 1;
#endif
            if (printWarn)
                syslog(LOG_WARNING, "dnssd_clientstub read_all(%d) failed %ld/%ld %d %s", sd,
                       (long)num_read, (long)len,
                       (num_read < 0) ? dnssd_errno                 : 0,
                       (num_read < 0) ? dnssd_strerror(dnssd_errno) : "");
            else if (defunct)
                syslog(LOG_INFO, "dnssd_clientstub read_all(%d) DEFUNCT", sd);
            return (num_read < 0 && dnssd_errno == dnssd_EWOULDBLOCK) ? read_all_wouldblock : (defunct ? read_all_defunct : read_all_fail);
        }
        buf += num_read;
        len -= num_read;
    }
    return read_all_success;
}

// Returns 1 if more bytes remain to be read on socket descriptor sd, 0 otherwise
static int more_bytes(dnssd_sock_t sd)
{
    struct timeval tv = { 0, 0 };
    fd_set readfds;
    fd_set *fs;
    int ret;

#if defined(_WIN32)
    fs = &readfds;
    FD_ZERO(fs);
    FD_SET(sd, fs);
    ret = select((int)sd+1, fs, (fd_set*)NULL, (fd_set*)NULL, &tv);
#else
    // This whole thing would probably be better done using kevent() instead of select()
    if (sd < FD_SETSIZE)
    {
        fs = &readfds;
        FD_ZERO(fs);
    }
    else
    {
        // Compute the number of integers needed for storing "sd". Internally fd_set is stored
        // as an array of ints with one bit for each fd and hence we need to compute
        // the number of ints needed rather than the number of bytes. If "sd" is 32, we need
        // two ints and not just one.
        int nfdbits = sizeof (int) * 8;
        int nints = (sd/nfdbits) + 1;
        fs = (fd_set *)calloc(nints, (size_t)sizeof(int));
        if (fs == NULL)
        {
            syslog(LOG_WARNING, "dnssd_clientstub more_bytes: malloc failed");
            return 0;
        }
    }
    FD_SET(sd, fs);
    ret = select((int)sd+1, fs, (fd_set*)NULL, (fd_set*)NULL, &tv);
    if (fs != &readfds)
        free(fs);
#endif
    return (ret > 0);
}

// set_waitlimit() implements a timeout using select. It is called from deliver_request() before recv() OR accept()
// to ensure the UDS clients are not blocked in these system calls indefinitely.
// Note: Ideally one should never be blocked here, because it indicates either mDNSResponder daemon is not yet up/hung/
// superbusy/crashed or some other OS bug. For eg: On Windows which suffers from 3rd party software
// (primarily 3rd party firewall software) interfering with proper functioning of the TCP protocol stack it is possible
// the next operation on this socket(recv/accept) is blocked since we depend on TCP to communicate with the system service.
static int set_waitlimit(dnssd_sock_t sock, int timeout)
{
    int gDaemonErr = kDNSServiceErr_NoError;

    // The comment below is wrong. The select() routine does not cause stack corruption.
    // The use of FD_SET out of range for the bitmap is what causes stack corruption.
    // For how to do this correctly, see the example using calloc() in more_bytes() above.
    // Even better, both should be changed to use kevent() instead of select().
    // To prevent stack corruption since select does not work with timeout if fds > FD_SETSIZE(1024)
    if (!gDaemonErr && sock < FD_SETSIZE)
    {
        struct timeval tv;
        fd_set set;

        FD_ZERO(&set);
        FD_SET(sock, &set);
        tv.tv_sec = timeout;
        tv.tv_usec = 0;
        if (!select((int)(sock + 1), &set, NULL, NULL, &tv))
        {
            // Ideally one should never hit this case: See comments before set_waitlimit()
            syslog(LOG_WARNING, "dnssd_clientstub set_waitlimit:_daemon timed out (%d secs) without any response: Socket %d", timeout, sock);
            gDaemonErr = kDNSServiceErr_Timeout;
        }
    }
    return gDaemonErr;
}

/* create_hdr
 *
 * allocate and initialize an ipc message header. Value of len should initially be the
 * length of the data, and is set to the value of the data plus the header. data_start
 * is set to point to the beginning of the data section. SeparateReturnSocket should be
 * non-zero for calls that can't receive an immediate error return value on their primary
 * socket, and therefore require a separate return path for the error code result.
 * if zero, the path to a control socket is appended at the beginning of the message buffer.
 * data_start is set past this string.
 */
static ipc_msg_hdr *create_hdr(uint32_t op, size_t *len, char **data_start, int SeparateReturnSocket, DNSServiceOp *ref)
{
    char *msg = NULL;
    ipc_msg_hdr *hdr;
    int datalen;
#if !defined(USE_TCP_LOOPBACK)
    char ctrl_path[64] = "";    // "/var/tmp/dnssd_result_socket.xxxxxxxxxx-xxx-xxxxxx"
#endif

    if (SeparateReturnSocket)
    {
#if defined(USE_TCP_LOOPBACK)
        *len += 2;  // Allocate space for two-byte port number
#elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
        struct timeval tv;
        if (gettimeofday(&tv, NULL) < 0)
        { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: gettimeofday failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno)); return NULL; }
        snprintf(ctrl_path, sizeof(ctrl_path), "%s%d-%.3lx-%.6lu", CTL_PATH_PREFIX, (int)getpid(),
                (unsigned long)(tv.tv_sec & 0xFFF), (unsigned long)(tv.tv_usec));
        *len += strlen(ctrl_path) + 1;
#else
        *len += 1;      // Allocate space for single zero byte (empty C string)
#endif
    }

    datalen = (int) *len;
    *len += sizeof(ipc_msg_hdr);

    // Write message to buffer
    msg = malloc(*len);
    if (!msg) { syslog(LOG_WARNING, "dnssd_clientstub create_hdr: malloc failed"); return NULL; }

    memset(msg, 0, *len);
    hdr = (ipc_msg_hdr *)msg;
    hdr->version                = VERSION;
    hdr->datalen                = datalen;
    hdr->ipc_flags              = 0;
    hdr->op                     = op;
    hdr->client_context         = ref->uid;
    hdr->reg_index              = 0;
    *data_start = msg + sizeof(ipc_msg_hdr);
#if defined(USE_TCP_LOOPBACK)
    // Put dummy data in for the port, since we don't know what it is yet.
    // The data will get filled in before we send the message. This happens in deliver_request().
    if (SeparateReturnSocket) put_uint16(0, data_start);
#else
    if (SeparateReturnSocket) put_string(ctrl_path, data_start);
#endif
    return hdr;
}

static void FreeDNSRecords(DNSServiceOp *sdRef)
{
    DNSRecord *rec = sdRef->rec;
    while (rec)
    {
        DNSRecord *next = rec->recnext;
        free(rec);
        rec = next;
    }
}

static void FreeDNSServiceOp(DNSServiceOp *x)
{
    // We don't use our DNSServiceRefValid macro here because if we're cleaning up after a socket() call failed
    // then sockfd could legitimately contain a failing value (e.g. dnssd_InvalidSocket)
    if ((x->sockfd ^ x->validator) != ValidatorBits)
    {
    }
    else
    {
        x->next         = NULL;
        x->primary      = NULL;
        x->sockfd       = dnssd_InvalidSocket;
        x->validator    = 0xDDDDDDDD;
        x->op           = request_op_none;
        x->max_index    = 0;
        x->logcounter   = 0;
        x->moreptr      = NULL;
        x->ProcessReply = NULL;
        x->AppCallback  = NULL;
        x->AppContext   = NULL;
#if _DNS_SD_LIBDISPATCH
        if (x->disp_source) dispatch_release(x->disp_source);
        x->disp_source  = NULL;
        x->disp_queue   = NULL;
#endif
        // DNSRecords may have been added to subordinate sdRef e.g., DNSServiceRegister/DNSServiceAddRecord
        // or on the main sdRef e.g., DNSServiceCreateConnection/DNSServiceRegisterRecord.
        // DNSRecords may have been freed if the application called DNSRemoveRecord.
        FreeDNSRecords(x);
        if (x->kacontext)
        {
            free(x->kacontext);
            x->kacontext = NULL;
        }
        free(x);
    }
}

// Return a connected service ref (deallocate with DNSServiceRefDeallocate)
static DNSServiceErrorType ConnectToServer(DNSServiceRef *ref, DNSServiceFlags flags, uint32_t op, ProcessReplyFn ProcessReply, void *AppCallback, void *AppContext)
{
    #if defined(_WIN32)
    int NumTries = 0;
    #endif // _WIN32

    dnssd_sockaddr_t saddr;
    DNSServiceOp *sdr;

    if (!ref)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSService operation with NULL DNSServiceRef");
        return kDNSServiceErr_BadParam;
    }

    if (flags & kDNSServiceFlagsShareConnection)
    {
        if (!*ref)
        {
            syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with NULL DNSServiceRef");
            return kDNSServiceErr_BadParam;
        }
        if (!DNSServiceRefValid(*ref) || ((*ref)->op != connection_request && (*ref)->op != connection_delegate_request) || (*ref)->primary)
        {
            syslog(LOG_WARNING, "dnssd_clientstub kDNSServiceFlagsShareConnection used with invalid DNSServiceRef %p %08X %08X op %d",
                   (*ref), (*ref)->sockfd, (*ref)->validator, (*ref)->op);
            *ref = NULL;
            return kDNSServiceErr_BadReference;
        }
    }

    #if defined(_WIN32)
    if (!g_initWinsock)
    {
        WSADATA wsaData;
        g_initWinsock = 1;
        if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { *ref = NULL; return kDNSServiceErr_ServiceNotRunning; }
    }
    // <rdar://problem/4096913> If the system service is disabled, we only want to try to connect once
    if (IsSystemServiceDisabled())
        NumTries = DNSSD_CLIENT_MAXTRIES;
    #endif

    sdr = malloc(sizeof(DNSServiceOp));
    if (!sdr)
    {
        syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: malloc failed");
        *ref = NULL;
        return kDNSServiceErr_NoMemory;
    }
    sdr->next          = NULL;
    sdr->primary       = NULL;
    sdr->sockfd        = dnssd_InvalidSocket;
    sdr->validator     = sdr->sockfd ^ ValidatorBits;
    sdr->op            = op;
    sdr->max_index     = 0;
    sdr->logcounter    = 0;
    sdr->moreptr       = NULL;
    sdr->uid.u32[0]    = 0;
    sdr->uid.u32[1]    = 0;
    sdr->ProcessReply  = ProcessReply;
    sdr->AppCallback   = AppCallback;
    sdr->AppContext    = AppContext;
    sdr->rec           = NULL;
#if _DNS_SD_LIBDISPATCH
    sdr->disp_source   = NULL;
    sdr->disp_queue    = NULL;
#endif
    sdr->kacontext     = NULL;
    
    if (flags & kDNSServiceFlagsShareConnection)
    {
        DNSServiceOp **p = &(*ref)->next;       // Append ourselves to end of primary's list
        while (*p)
            p = &(*p)->next;
        *p = sdr;
        // Preincrement counter before we use it -- it helps with debugging if we know the all-zeroes ID should never appear
        if (++(*ref)->uid.u32[0] == 0)
            ++(*ref)->uid.u32[1];               // In parent DNSServiceOp increment UID counter
        sdr->primary    = *ref;                 // Set our primary pointer
        sdr->sockfd     = (*ref)->sockfd;       // Inherit primary's socket
        sdr->validator  = (*ref)->validator;
        sdr->uid        = (*ref)->uid;
        //printf("ConnectToServer sharing socket %d\n", sdr->sockfd);
    }
    else
    {
        #ifdef SO_NOSIGPIPE
        const unsigned long optval = 1;
        #endif
        #ifndef USE_TCP_LOOPBACK
        char* uds_serverpath = getenv(MDNS_UDS_SERVERPATH_ENVVAR);
        if (uds_serverpath == NULL)
            uds_serverpath = MDNS_UDS_SERVERPATH;
        else if (strlen(uds_serverpath) >= MAX_CTLPATH)
        {
            uds_serverpath = MDNS_UDS_SERVERPATH;
            syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: using default path since env len is invalid");
        }
        #endif
        *ref = NULL;
        sdr->sockfd    = socket(AF_DNSSD, SOCK_STREAM, 0);
        sdr->validator = sdr->sockfd ^ ValidatorBits;
        if (!dnssd_SocketValid(sdr->sockfd))
        {
            syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: socket failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
            FreeDNSServiceOp(sdr);
            return kDNSServiceErr_NoMemory;
        }
#if !defined(_WIN32)
        int fcntl_flags = fcntl(sdr->sockfd, F_GETFD);
        if (fcntl_flags != -1)
        {
            fcntl_flags |= FD_CLOEXEC;
            int ret = fcntl(sdr->sockfd, F_SETFD, fcntl_flags);
            if (ret == -1)
                syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: Failed to set FD_CLOEXEC on socket %d %s",
                       dnssd_errno, dnssd_strerror(dnssd_errno));
        }
        else
        {
            syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: Failed to get the file descriptor flags of socket %d %s",
                   dnssd_errno, dnssd_strerror(dnssd_errno));
        }
#endif // !defined(_WIN32)
        #ifdef SO_NOSIGPIPE
        // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
        if (setsockopt(sdr->sockfd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
            syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_NOSIGPIPE failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
        #endif
        #if defined(USE_TCP_LOOPBACK)
        saddr.sin_family      = AF_INET;
        saddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
        saddr.sin_port        = htons(MDNS_TCP_SERVERPORT);
        #else
        saddr.sun_family      = AF_LOCAL;
        SetUDSPath(&saddr, uds_serverpath);
        #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
        {
            int defunct = 1;
            if (setsockopt(sdr->sockfd, SOL_SOCKET, SO_DEFUNCTOK, &defunct, sizeof(defunct)) < 0)
                syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: SO_DEFUNCTOK failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
        }
        #endif
        #endif

        #if defined(_WIN32)
        while (1)
        {
            int err = connect(sdr->sockfd, (struct sockaddr *) &saddr, sizeof(saddr));
            if (!err)
                break; // If we succeeded, return sdr

            // If we failed, then it may be because the daemon is still launching.
            // This can happen for processes that launch early in the boot process, while the
            // daemon is still coming up. Rather than fail here, we wait 1 sec and try again.
            // If, after DNSSD_CLIENT_MAXTRIES, we still can't connect to the daemon,
            // then we give up and return a failure code.
            if (++NumTries < DNSSD_CLIENT_MAXTRIES)
            {
                syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: connect()-> No of tries: %d", NumTries);
                sleep(1); // Sleep a bit, then try again
            }
            else
            {
                #if !defined(USE_TCP_LOOPBACK)
                syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: connect() failed path:%s Socket:%d Err:%d Errno:%d %s",
                       uds_serverpath, sdr->sockfd, err, dnssd_errno, dnssd_strerror(dnssd_errno));
                #endif
                dnssd_close(sdr->sockfd);
                FreeDNSServiceOp(sdr);
                return kDNSServiceErr_ServiceNotRunning;
            }
        }
        #else
        int err = connect(sdr->sockfd, (struct sockaddr *) &saddr, sizeof(saddr));
        if (err)
        {
            #if !defined(USE_TCP_LOOPBACK)
            syslog(LOG_WARNING, "dnssd_clientstub ConnectToServer: connect() failed path:%s Socket:%d Err:%d Errno:%d %s",
                   uds_serverpath, sdr->sockfd, err, dnssd_errno, dnssd_strerror(dnssd_errno));
            #endif
            dnssd_close(sdr->sockfd);
            FreeDNSServiceOp(sdr);
            return kDNSServiceErr_ServiceNotRunning;
        }
        #endif
    }

    *ref = sdr;
    return kDNSServiceErr_NoError;
}

#define deliver_request_bailout(MSG) \
    syslog(LOG_WARNING, "dnssd_clientstub deliver_request: %s failed %d (%s)", (MSG), dnssd_errno, dnssd_strerror(dnssd_errno)); goto cleanup

static DNSServiceErrorType deliver_request(ipc_msg_hdr *hdr, DNSServiceOp *sdr)
{
    uint32_t datalen;
    dnssd_sock_t listenfd = dnssd_InvalidSocket, errsd = dnssd_InvalidSocket;
    DNSServiceErrorType err = kDNSServiceErr_Unknown;   // Default for the "goto cleanup" cases
    int MakeSeparateReturnSocket;
    int ioresult;
    #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
    char *data;
    #endif

    if (!hdr)
    {
        syslog(LOG_WARNING, "dnssd_clientstub deliver_request: !hdr");
        return kDNSServiceErr_Unknown;
    }

    datalen = hdr->datalen;    // We take a copy here because we're going to convert hdr->datalen to network byte order
    #if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
    data = (char *)hdr + sizeof(ipc_msg_hdr);
    #endif

    // Note: need to check hdr->op, not sdr->op.
    // hdr->op contains the code for the specific operation we're currently doing, whereas sdr->op
    // contains the original parent DNSServiceOp (e.g. for an add_record_request, hdr->op will be
    // add_record_request but the parent sdr->op will be connection_request or reg_service_request)
    MakeSeparateReturnSocket = (sdr->primary ||
        hdr->op == reg_record_request || hdr->op == add_record_request || hdr->op == update_record_request || hdr->op == remove_record_request);

    if (!DNSServiceRefValid(sdr))
    {
        if (hdr)
            free(hdr);
        syslog(LOG_WARNING, "dnssd_clientstub deliver_request: invalid DNSServiceRef %p %08X %08X", sdr, sdr->sockfd, sdr->validator);
        return kDNSServiceErr_BadReference;
    }

    if (MakeSeparateReturnSocket)
    {
        #if defined(USE_TCP_LOOPBACK)
        {
            union { uint16_t s; u_char b[2]; } port;
            dnssd_sockaddr_t caddr;
            dnssd_socklen_t len = (dnssd_socklen_t) sizeof(caddr);
            listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
            if (!dnssd_SocketValid(listenfd)) {
		deliver_request_bailout("TCP socket");
	    }

            caddr.sin_family      = AF_INET;
            caddr.sin_port        = 0;
            caddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
            if (bind(listenfd, (struct sockaddr*) &caddr, sizeof(caddr)) < 0) {
		deliver_request_bailout("TCP bind");
	    }
            if (getsockname(listenfd, (struct sockaddr*) &caddr, &len) < 0) {
		deliver_request_bailout("TCP getsockname");
	    }
            if (listen(listenfd, 1) < 0) {
		deliver_request_bailout("TCP listen");
	    }
            port.s = caddr.sin_port;
            data[0] = port.b[0];  // don't switch the byte order, as the
            data[1] = port.b[1];  // daemon expects it in network byte order
        }
        #elif defined(USE_NAMED_ERROR_RETURN_SOCKET)
        {
            mode_t mask;
            int bindresult;
            dnssd_sockaddr_t caddr;
            listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
            if (!dnssd_SocketValid(listenfd)) {
		deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET socket");
	    }

            caddr.sun_family = AF_LOCAL;
            // According to Stevens (section 3.2), there is no portable way to
            // determine whether sa_len is defined on a particular platform.
            #ifndef NOT_HAVE_SA_LEN
            caddr.sun_len = sizeof(struct sockaddr_un);
            #endif
            SetUDSPath(&caddr, data);
            mask = umask(0);
            bindresult = bind(listenfd, (struct sockaddr *)&caddr, sizeof(caddr));
            umask(mask);
            if (bindresult < 0) {
		deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET bind");
	    }
            if (listen(listenfd, 1) < 0) {
		deliver_request_bailout("USE_NAMED_ERROR_RETURN_SOCKET listen");
	    }
        }
        #else
        {
            dnssd_sock_t sp[2];
            if (socketpair(AF_DNSSD, SOCK_STREAM, 0, sp) < 0) {
		deliver_request_bailout("socketpair");
	    }
            else
            {
                errsd    = sp[0];   // We'll read our four-byte error code from sp[0]
                listenfd = sp[1];   // We'll send sp[1] to the daemon
                #if !defined(__ppc__) && defined(SO_DEFUNCTOK)
                {
                    int defunct = 1;
                    if (setsockopt(errsd, SOL_SOCKET, SO_DEFUNCTOK, &defunct, sizeof(defunct)) < 0)
                        syslog(LOG_WARNING, "dnssd_clientstub deliver_request: SO_DEFUNCTOK failed %d %s", dnssd_errno, dnssd_strerror(dnssd_errno));
                }
                #endif
            }
        }
        #endif
    }

#if !defined(USE_TCP_LOOPBACK) && !defined(USE_NAMED_ERROR_RETURN_SOCKET)
    // If we're going to make a separate error return socket, and pass it to the daemon
    // using sendmsg, then we'll hold back one data byte to go with it.
    // On some versions of Unix (including Leopard) sending a control message without
    // any associated data does not work reliably -- e.g. one particular issue we ran
    // into is that if the receiving program is in a kqueue loop waiting to be notified
    // of the received message, it doesn't get woken up when the control message arrives.
    if (MakeSeparateReturnSocket || sdr->op == send_bpf)
        datalen--;     // Okay to use sdr->op when checking for op == send_bpf
#endif

    // At this point, our listening socket is set up and waiting, if necessary, for the daemon to connect back to
    ConvertHeaderBytes(hdr);
    //syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %lu bytes", (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
    //if (MakeSeparateReturnSocket) syslog(LOG_WARNING, "dnssd_clientstub deliver_request name is %s", data);
#if TEST_SENDING_ONE_BYTE_AT_A_TIME
    unsigned int i;
    for (i=0; i<datalen + sizeof(ipc_msg_hdr); i++)
    {
        syslog(LOG_WARNING, "dnssd_clientstub deliver_request writing %d", i);
        ioresult = write_all(sdr->sockfd, ((char *)hdr)+i, 1);
        if (ioresult < write_all_success)
        {
            syslog(LOG_WARNING, "dnssd_clientstub deliver_request write_all (byte %u) failed", i);
            err = (ioresult == write_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning;
            goto cleanup;
        }
        usleep(10000);
    }
#else
    ioresult = write_all(sdr->sockfd, (char *)hdr, datalen + sizeof(ipc_msg_hdr));
    if (ioresult < write_all_success)
    {
        // write_all already prints an error message if there is an error writing to
        // the socket except for DEFUNCT. Logging here is unnecessary and also wrong
        // in the case of DEFUNCT sockets
        syslog(LOG_INFO, "dnssd_clientstub deliver_request ERROR: write_all(%d, %lu bytes) failed",
               sdr->sockfd, (unsigned long)(datalen + sizeof(ipc_msg_hdr)));
        err = (ioresult == write_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning;
        goto cleanup;
    }
#endif

    if (!MakeSeparateReturnSocket)
        errsd = sdr->sockfd;
    if (MakeSeparateReturnSocket || sdr->op == send_bpf)    // Okay to use sdr->op when checking for op == send_bpf
    {
#if defined(USE_TCP_LOOPBACK) || defined(USE_NAMED_ERROR_RETURN_SOCKET)
        // At this point we may wait in accept for a few milliseconds waiting for the daemon to connect back to us,
        // but that's okay -- the daemon should not take more than a few milliseconds to respond.
        // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
        dnssd_sockaddr_t daddr;
        dnssd_socklen_t len = sizeof(daddr);
        if ((err = set_waitlimit(listenfd, DNSSD_CLIENT_TIMEOUT)) != kDNSServiceErr_NoError)
            goto cleanup;
        errsd = accept(listenfd, (struct sockaddr *)&daddr, &len);
        if (!dnssd_SocketValid(errsd)) {
            deliver_request_bailout("accept");
	}
#else

        struct iovec vec = { ((char *)hdr) + sizeof(ipc_msg_hdr) + datalen, 1 }; // Send the last byte along with the SCM_RIGHTS
        struct msghdr msg;
        struct cmsghdr *cmsg;
        char cbuf[CMSG_SPACE(4 * sizeof(dnssd_sock_t))];

        msg.msg_name       = 0;
        msg.msg_namelen    = 0;
        msg.msg_iov        = &vec;
        msg.msg_iovlen     = 1;
        msg.msg_flags      = 0;
        if (MakeSeparateReturnSocket || sdr->op == send_bpf)    // Okay to use sdr->op when checking for op == send_bpf
        {
            if (sdr->op == send_bpf)
            {
                int i;
                char p[12];     // Room for "/dev/bpf999" with terminating null
                for (i=0; i<100; i++)
                {
                    snprintf(p, sizeof(p), "/dev/bpf%d", i);
                    listenfd = open(p, O_RDWR, 0);
                    //if (dnssd_SocketValid(listenfd)) syslog(LOG_WARNING, "dnssd_clientstub deliver_request Sending fd %d for %s", listenfd, p);
                    if (!dnssd_SocketValid(listenfd) && dnssd_errno != EBUSY)
                        syslog(LOG_WARNING, "dnssd_clientstub deliver_request Error opening %s %d (%s)", p, dnssd_errno, dnssd_strerror(dnssd_errno));
                    if (dnssd_SocketValid(listenfd) || dnssd_errno != EBUSY) break;
                }
            }
            msg.msg_control    = cbuf;
            msg.msg_controllen = CMSG_LEN(sizeof(dnssd_sock_t));

            cmsg = CMSG_FIRSTHDR(&msg);
            cmsg->cmsg_len     = CMSG_LEN(sizeof(dnssd_sock_t));
            cmsg->cmsg_level   = SOL_SOCKET;
            cmsg->cmsg_type    = SCM_RIGHTS;
            *((dnssd_sock_t *)CMSG_DATA(cmsg)) = listenfd;
        }

#if TEST_KQUEUE_CONTROL_MESSAGE_BUG
        sleep(1);
#endif

#if DEBUG_64BIT_SCM_RIGHTS
        syslog(LOG_WARNING, "dnssd_clientstub deliver_request sendmsg read sd=%d write sd=%d %ld %ld %ld/%ld/%ld/%ld",
               errsd, listenfd, sizeof(dnssd_sock_t), sizeof(void*),
               sizeof(struct cmsghdr) + sizeof(dnssd_sock_t),
               CMSG_LEN(sizeof(dnssd_sock_t)), (long)CMSG_SPACE(sizeof(dnssd_sock_t)),
               (long)((char*)CMSG_DATA(cmsg) + 4 - cbuf));
#endif // DEBUG_64BIT_SCM_RIGHTS

        if (sendmsg(sdr->sockfd, &msg, 0) < 0)
        {
            syslog(LOG_WARNING, "dnssd_clientstub deliver_request ERROR: sendmsg failed read sd=%d write sd=%d errno %d (%s)",
                   errsd, listenfd, dnssd_errno, dnssd_strerror(dnssd_errno));
            err = kDNSServiceErr_Incompatible;
            goto cleanup;
        }

#if DEBUG_64BIT_SCM_RIGHTS
        syslog(LOG_WARNING, "dnssd_clientstub deliver_request sendmsg read sd=%d write sd=%d okay", errsd, listenfd);
#endif // DEBUG_64BIT_SCM_RIGHTS

#endif
        // Close our end of the socketpair *before* calling read_all() to get the four-byte error code.
        // Otherwise, if the daemon closes our socket (or crashes), we will have to wait for a timeout
        // in read_all() because the socket is not closed (we still have an open reference to it)
        // Note: listenfd is overwritten in the case of send_bpf above and that will be closed here
        // for send_bpf operation.
        dnssd_close(listenfd);
        listenfd = dnssd_InvalidSocket; // Make sure we don't close it a second time in the cleanup handling below
    }

    // At this point we may wait in read_all for a few milliseconds waiting for the daemon to send us the error code,
    // but that's okay -- the daemon should not take more than a few milliseconds to respond.
    // set_waitlimit() ensures we do not block indefinitely just in case something is wrong
    if (sdr->op == send_bpf)    // Okay to use sdr->op when checking for op == send_bpf
        err = kDNSServiceErr_NoError;
    else if ((err = set_waitlimit(errsd, DNSSD_CLIENT_TIMEOUT)) == kDNSServiceErr_NoError)
    {
        ioresult = read_all(errsd, (char*)&err, (int)sizeof(err));
        if (ioresult < read_all_success)
            err = (ioresult == read_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning; // On failure read_all will have written a message to syslog for us
        else
            err = ntohl(err);
    }
    //syslog(LOG_WARNING, "dnssd_clientstub deliver_request: retrieved error code %d", err);

cleanup:
    if (MakeSeparateReturnSocket)
    {
        if (dnssd_SocketValid(listenfd)) dnssd_close(listenfd);
        if (dnssd_SocketValid(errsd)) dnssd_close(errsd);
#if defined(USE_NAMED_ERROR_RETURN_SOCKET)
        // syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removing UDS: %s", data);
        if (unlink(data) != 0)
            syslog(LOG_WARNING, "dnssd_clientstub WARNING: unlink(\"%s\") failed errno %d (%s)", data, dnssd_errno, dnssd_strerror(dnssd_errno));
        // else syslog(LOG_WARNING, "dnssd_clientstub deliver_request: removed UDS: %s", data);
#endif
    }

    free(hdr);
    return err;
}

dnssd_sock_t DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdRef)
{
    if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with NULL DNSServiceRef"); return dnssd_InvalidSocket; }

    if (!DNSServiceRefValid(sdRef))
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD called with invalid DNSServiceRef %p %08X %08X",
               sdRef, sdRef->sockfd, sdRef->validator);
        return dnssd_InvalidSocket;
    }

    if (sdRef->primary)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefSockFD undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
        return dnssd_InvalidSocket;
    }

    return sdRef->sockfd;
}

#if _DNS_SD_LIBDISPATCH
static void CallbackWithError(DNSServiceRef sdRef, DNSServiceErrorType error)
{
    DNSServiceOp *sdr = sdRef;
    DNSServiceOp *sdrNext;
    DNSRecord *rec;
    DNSRecord *recnext;
    int morebytes;

    while (sdr)
    {
        // We can't touch the sdr after the callback as it can be deallocated in the callback
        sdrNext = sdr->next;
        morebytes = 1;
        sdr->moreptr = &morebytes;
        switch (sdr->op)
        {
        case resolve_request:
            if (sdr->AppCallback) ((DNSServiceResolveReply)    sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, 0, 0, NULL,    sdr->AppContext);
            break;
        case query_request:
            if (sdr->AppCallback) ((DNSServiceQueryRecordReply)sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, 0, 0, NULL, 0, sdr->AppContext);
            break;
        case addrinfo_request:
            if (sdr->AppCallback) ((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, 0, 0, error, NULL, NULL, 0,          sdr->AppContext);
            break;
        case browse_request:
            if (sdr->AppCallback) ((DNSServiceBrowseReply)     sdr->AppCallback)(sdr, 0, 0, error, NULL, 0, NULL,          sdr->AppContext);
            break;
        case reg_service_request:
            if (sdr->AppCallback) ((DNSServiceRegisterReply)   sdr->AppCallback)(sdr, 0,    error, NULL, 0, NULL,          sdr->AppContext);
            break;
        case enumeration_request:
            if (sdr->AppCallback) ((DNSServiceDomainEnumReply) sdr->AppCallback)(sdr, 0, 0, error, NULL,                   sdr->AppContext);
            break;
        case connection_request:
        case connection_delegate_request:
            // This means Register Record, walk the list of DNSRecords to do the callback
            rec = sdr->rec;
            while (rec)
            {
                recnext = rec->recnext;
                if (rec->AppCallback) ((DNSServiceRegisterRecordReply)rec->AppCallback)(sdr, 0, 0, error, rec->AppContext);
                // The Callback can call DNSServiceRefDeallocate which in turn frees sdr and all the records.
                // Detect that and return early
                if (!morebytes) { syslog(LOG_WARNING, "dnssd_clientstub:Record: CallbackwithError morebytes zero"); return; }
                rec = recnext;
            }
            break;
        case port_mapping_request:
            if (sdr->AppCallback) ((DNSServiceNATPortMappingReply)sdr->AppCallback)(sdr, 0, 0, error, 0, 0, 0, 0, 0, sdr->AppContext);
            break;
        default:
            syslog(LOG_WARNING, "dnssd_clientstub CallbackWithError called with bad op %d", sdr->op);
        }
        // If DNSServiceRefDeallocate was called in the callback, morebytes will be zero. As the sdRef
        // (and its subordinates) have been freed, we should not proceed further. Note that when we
        // call the callback with a subordinate sdRef the application can call DNSServiceRefDeallocate
        // on the main sdRef and DNSServiceRefDeallocate handles this case by walking all the sdRefs and
        // clears the moreptr so that we can terminate here.
        //
        // If DNSServiceRefDeallocate was not called in the callback, then set moreptr to NULL so that
        // we don't access the stack variable after we return from this function.
        if (!morebytes) { syslog(LOG_WARNING, "dnssd_clientstub:sdRef: CallbackwithError morebytes zero sdr %p", sdr); return; }
        else {sdr->moreptr = NULL;}
        sdr = sdrNext;
    }
}
#endif // _DNS_SD_LIBDISPATCH

// Handle reply from server, calling application client callback. If there is no reply
// from the daemon on the socket contained in sdRef, the call will block.
DNSServiceErrorType DNSSD_API DNSServiceProcessResult(DNSServiceRef sdRef)
{
    int morebytes = 0;
    int ioresult;
    DNSServiceErrorType error;

    if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }

    if (!DNSServiceRefValid(sdRef))
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
        return kDNSServiceErr_BadReference;
    }

    if (sdRef->primary)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult undefined for kDNSServiceFlagsShareConnection subordinate DNSServiceRef %p", sdRef);
        return kDNSServiceErr_BadReference;
    }

    if (!sdRef->ProcessReply)
    {
        static int num_logs = 0;
        if (num_logs < 10) syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult called with DNSServiceRef with no ProcessReply function");
        if (num_logs < 1000) num_logs++;else sleep(1);
        return kDNSServiceErr_BadReference;
    }

    do
    {
        CallbackHeader cbh;
        char *data;

        // return NoError on EWOULDBLOCK. This will handle the case
        // where a non-blocking socket is told there is data, but it was a false positive.
        // On error, read_all will write a message to syslog for us, so don't need to duplicate that here
        // Note: If we want to properly support using non-blocking sockets in the future
        ioresult = read_all(sdRef->sockfd, (void *)&cbh.ipc_hdr, sizeof(cbh.ipc_hdr));
        if (ioresult == read_all_fail || ioresult == read_all_defunct)
        {
            error = (ioresult == read_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning;
            
            // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
            // in the callback.
            sdRef->ProcessReply = NULL;
#if _DNS_SD_LIBDISPATCH
            // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
            // is not called by the application and hence need to communicate the error. Cancel the
            // source so that we don't get any more events
            // Note: read_all fails if we could not read from the daemon which can happen if the
            // daemon dies or the file descriptor is disconnected (defunct).
            if (sdRef->disp_source)
            {
                dispatch_source_cancel(sdRef->disp_source);
                dispatch_release(sdRef->disp_source);
                sdRef->disp_source = NULL;
                CallbackWithError(sdRef, error);
            }
#endif
            // Don't touch sdRef anymore as it might have been deallocated
            return error;
        }
        else if (ioresult == read_all_wouldblock)
        {
            if (morebytes && sdRef->logcounter < 100)
            {
                sdRef->logcounter++;
                syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult error: select indicated data was waiting but read_all returned EWOULDBLOCK");
            }
            return kDNSServiceErr_NoError;
        }

        ConvertHeaderBytes(&cbh.ipc_hdr);
        if (cbh.ipc_hdr.version != VERSION)
        {
            syslog(LOG_WARNING, "dnssd_clientstub DNSServiceProcessResult daemon version %d does not match client version %d", cbh.ipc_hdr.version, VERSION);
            sdRef->ProcessReply = NULL;
            return kDNSServiceErr_Incompatible;
        }

        data = malloc(cbh.ipc_hdr.datalen);
        if (!data) return kDNSServiceErr_NoMemory;
        ioresult = read_all(sdRef->sockfd, data, cbh.ipc_hdr.datalen);
        if (ioresult < read_all_success) // On error, read_all will write a message to syslog for us
        {
            error = (ioresult == read_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning;
            
            // Set the ProcessReply to NULL before callback as the sdRef can get deallocated
            // in the callback.
            sdRef->ProcessReply = NULL;
#if _DNS_SD_LIBDISPATCH
            // Call the callbacks with an error if using the dispatch API, as DNSServiceProcessResult
            // is not called by the application and hence need to communicate the error. Cancel the
            // source so that we don't get any more events
            if (sdRef->disp_source)
            {
                dispatch_source_cancel(sdRef->disp_source);
                dispatch_release(sdRef->disp_source);
                sdRef->disp_source = NULL;
                CallbackWithError(sdRef, error);
            }
#endif
            // Don't touch sdRef anymore as it might have been deallocated
            free(data);
            return error;
        }
        else
        {
            const char *ptr = data;
            cbh.cb_flags     = get_flags     (&ptr, data + cbh.ipc_hdr.datalen);
            cbh.cb_interface = get_uint32    (&ptr, data + cbh.ipc_hdr.datalen);
            cbh.cb_err       = get_error_code(&ptr, data + cbh.ipc_hdr.datalen);

            // CAUTION: We have to handle the case where the client calls DNSServiceRefDeallocate from within the callback function.
            // To do this we set moreptr to point to morebytes. If the client does call DNSServiceRefDeallocate(),
            // then that routine will clear morebytes for us, and cause us to exit our loop.
            morebytes = more_bytes(sdRef->sockfd);
            if (morebytes)
            {
                cbh.cb_flags |= kDNSServiceFlagsMoreComing;
                sdRef->moreptr = &morebytes;
            }
            if (ptr) sdRef->ProcessReply(sdRef, &cbh, ptr, data + cbh.ipc_hdr.datalen);
            // Careful code here:
            // If morebytes is non-zero, that means we set sdRef->moreptr above, and the operation was not
            // cancelled out from under us, so now we need to clear sdRef->moreptr so we don't leave a stray
            // dangling pointer pointing to a long-gone stack variable.
            // If morebytes is zero, then one of two thing happened:
            // (a) morebytes was 0 above, so we didn't set sdRef->moreptr, so we don't need to clear it
            // (b) morebytes was 1 above, and we set sdRef->moreptr, but the operation was cancelled (with DNSServiceRefDeallocate()),
            //     so we MUST NOT try to dereference our stale sdRef pointer.
            if (morebytes) sdRef->moreptr = NULL;
        }
        free(data);
    } while (morebytes);

    return kDNSServiceErr_NoError;
}

void DNSSD_API DNSServiceRefDeallocate(DNSServiceRef sdRef)
{
    if (!sdRef) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with NULL DNSServiceRef"); return; }

    if (!DNSServiceRefValid(sdRef))     // Also verifies dnssd_SocketValid(sdRef->sockfd) for us too
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRefDeallocate called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
        return;
    }

    // If we're in the middle of a DNSServiceProcessResult() invocation for this DNSServiceRef, clear its morebytes flag to break it out of its while loop
    if (sdRef->moreptr) *(sdRef->moreptr) = 0;

    if (sdRef->primary)     // If this is a subordinate DNSServiceOp, just send a 'stop' command
    {
        DNSServiceOp **p = &sdRef->primary->next;
        while (*p && *p != sdRef) p = &(*p)->next;
        if (*p)
        {
            char *ptr;
            size_t len = 0;
            ipc_msg_hdr *hdr = create_hdr(cancel_request, &len, &ptr, 0, sdRef);
            if (hdr)
            {
                ConvertHeaderBytes(hdr);
                write_all(sdRef->sockfd, (char *)hdr, len);
                free(hdr);
            }
            *p = sdRef->next;
            FreeDNSServiceOp(sdRef);
        }
    }
    else                    // else, make sure to terminate all subordinates as well
    {
#if _DNS_SD_LIBDISPATCH
        // The cancel handler will close the fd if a dispatch source has been set
        if (sdRef->disp_source)
        {
            // By setting the ProcessReply to NULL, we make sure that we never call
            // the application callbacks ever, after returning from this function. We
            // assume that DNSServiceRefDeallocate is called from the serial queue
            // that was passed to DNSServiceSetDispatchQueue. Hence, dispatch_source_cancel
            // should cancel all the blocks on the queue and hence there should be no more
            // callbacks when we return from this function. Setting ProcessReply to NULL
            // provides extra protection.
            sdRef->ProcessReply = NULL;
            shutdown(sdRef->sockfd, SHUT_WR);
            dispatch_source_cancel(sdRef->disp_source);
            dispatch_release(sdRef->disp_source);
            sdRef->disp_source = NULL;
        }
        // if disp_queue is set, it means it used the DNSServiceSetDispatchQueue API. In that case,
        // when the source was cancelled, the fd was closed in the handler. Currently the source
        // is cancelled only when the mDNSResponder daemon dies
        else if (!sdRef->disp_queue) dnssd_close(sdRef->sockfd);
#else
        dnssd_close(sdRef->sockfd);
#endif
        // Free DNSRecords added in DNSRegisterRecord if they have not
        // been freed in DNSRemoveRecord
        while (sdRef)
        {
            DNSServiceOp *p = sdRef;
            sdRef = sdRef->next;
            // When there is an error reading from the daemon e.g., bad fd, CallbackWithError
            // is called which sets moreptr. It might set the moreptr on a subordinate sdRef
            // but the application might call DNSServiceRefDeallocate with the main sdRef from
            // the callback. Hence, when we loop through the subordinate sdRefs, we need
            // to clear the moreptr so that CallbackWithError can terminate itself instead of
            // walking through the freed sdRefs.
            if (p->moreptr) *(p->moreptr) = 0;
            FreeDNSServiceOp(p);
        }
    }
}

DNSServiceErrorType DNSSD_API DNSServiceGetProperty(const char *property, void *result, uint32_t *size)
{
    DNSServiceErrorType err;
    char *ptr;
    size_t len;
    ipc_msg_hdr *hdr;
    DNSServiceOp *tmp;
    uint32_t actualsize;
    int ioresult;

    if (!property || !result || !size)
        return kDNSServiceErr_BadParam;

    len = strlen(property) + 1;
    err = ConnectToServer(&tmp, 0, getproperty_request, NULL, NULL, NULL);
    if (err) return err;

    hdr = create_hdr(getproperty_request, &len, &ptr, 0, tmp);
    if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }

    put_string(property, &ptr);
    err = deliver_request(hdr, tmp);        // Will free hdr for us
    if (err) { DNSServiceRefDeallocate(tmp); return err; }

    ioresult = read_all(tmp->sockfd, (char*)&actualsize, (int)sizeof(actualsize));
    if (ioresult < read_all_success)
    { DNSServiceRefDeallocate(tmp); return (ioresult == read_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning; }

    actualsize = ntohl(actualsize);
    ioresult = read_all(tmp->sockfd, (char*)result, actualsize < *size ? actualsize : *size);
    if (ioresult < read_all_success)
    { DNSServiceRefDeallocate(tmp); return (ioresult == read_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning; }
    DNSServiceRefDeallocate(tmp);

    // Swap version result back to local process byte order
    if (!strcmp(property, kDNSServiceProperty_DaemonVersion) && *size >= 4)
        *(uint32_t*)result = ntohl(*(uint32_t*)result);

    *size = actualsize;
    return kDNSServiceErr_NoError;
}

DNSServiceErrorType DNSSD_API DNSServiceGetPID(const uint16_t srcport, int32_t *pid)
{
    char *ptr;
    ipc_msg_hdr *hdr;
    DNSServiceOp *tmp = NULL;
    size_t len = sizeof(int32_t);
    int ioresult;

    DNSServiceErrorType err = ConnectToServer(&tmp, 0, getpid_request, NULL, NULL, NULL);
    if (err) return err;

    hdr = create_hdr(getpid_request, &len, &ptr, 0, tmp);
    if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }

    put_uint16(srcport, &ptr);
    err = deliver_request(hdr, tmp);        // Will free hdr for us
    if (err) { DNSServiceRefDeallocate(tmp); return err; }

    ioresult = read_all(tmp->sockfd, (char*)pid, sizeof(int32_t));
    if (ioresult < read_all_success)
    { DNSServiceRefDeallocate(tmp); return (ioresult == read_all_defunct) ? kDNSServiceErr_DefunctConnection : kDNSServiceErr_ServiceNotRunning; }

    DNSServiceRefDeallocate(tmp);
    return kDNSServiceErr_NoError;
}

static void handle_resolve_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *end)
{
    char fullname[kDNSServiceMaxDomainName];
    char target[kDNSServiceMaxDomainName];
    uint16_t txtlen;
    union { uint16_t s; u_char b[2]; } port;
    unsigned char *txtrecord;

    get_string(&data, end, fullname, kDNSServiceMaxDomainName);
    get_string(&data, end, target,   kDNSServiceMaxDomainName);
    if (!data || data + 2 > end) goto fail;

    port.b[0] = *data++;
    port.b[1] = *data++;
    txtlen = get_uint16(&data, end);
    txtrecord = (unsigned char *)get_rdata(&data, end, txtlen);

    if (!data) goto fail;
    ((DNSServiceResolveReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, fullname, target, port.s, txtlen, txtrecord, sdr->AppContext);
    return;
    // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
fail:
    syslog(LOG_WARNING, "dnssd_clientstub handle_resolve_response: error reading result from daemon");
}

#if TARGET_OS_IPHONE

static int32_t libSystemVersion = 0;

// Return true if the iOS application linked against a version of libsystem where P2P
// interfaces were included by default when using kDNSServiceInterfaceIndexAny.
// Using 160.0.0 == 0xa00000 as the version threshold.
static int includeP2PWithIndexAny()
{
    if (libSystemVersion == 0)
        libSystemVersion = NSVersionOfLinkTimeLibrary("System");

    if (libSystemVersion < 0xa00000)
        return 1;
    else
        return 0;
}

#else   // TARGET_OS_IPHONE

// always return false for non iOS platforms
static int includeP2PWithIndexAny()
{
    return 0;
}

#endif  // TARGET_OS_IPHONE

DNSServiceErrorType DNSSD_API DNSServiceResolve
(
    DNSServiceRef                 *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char                    *name,
    const char                    *regtype,
    const char                    *domain,
    DNSServiceResolveReply callBack,
    void                          *context
)
{
    char *ptr;
    size_t len;
    ipc_msg_hdr *hdr;
    DNSServiceErrorType err;

    if (!sdRef || !name || !regtype || !domain || !callBack) return kDNSServiceErr_BadParam;

    // Need a real InterfaceID for WakeOnResolve
    if ((flags & kDNSServiceFlagsWakeOnResolve) != 0 &&
        ((interfaceIndex == kDNSServiceInterfaceIndexAny) ||
         (interfaceIndex == kDNSServiceInterfaceIndexLocalOnly) ||
         (interfaceIndex == kDNSServiceInterfaceIndexUnicast) ||
         (interfaceIndex == kDNSServiceInterfaceIndexP2P) ||
         (interfaceIndex == kDNSServiceInterfaceIndexBLE)))
    {
        return kDNSServiceErr_BadParam;
    }

    if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
        flags |= kDNSServiceFlagsIncludeP2P;

    err = ConnectToServer(sdRef, flags, resolve_request, handle_resolve_response, (void *)callBack, context);
    if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL

    // Calculate total message length
    len = sizeof(flags);
    len += sizeof(interfaceIndex);
    len += strlen(name) + 1;
    len += strlen(regtype) + 1;
    len += strlen(domain) + 1;

    hdr = create_hdr(resolve_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
    if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }

    put_flags(flags, &ptr);
    put_uint32(interfaceIndex, &ptr);
    put_string(name, &ptr);
    put_string(regtype, &ptr);
    put_string(domain, &ptr);

    err = deliver_request(hdr, *sdRef);     // Will free hdr for us
#if CHECK_BUNDLE_VERSION
    if (err == kDNSServiceErr_NoAuth && !_should_return_noauth_error())
    {
        err = kDNSServiceErr_NoError;
    }
#endif
    if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
    return err;
}

static void handle_query_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
{
#if CHECK_BUNDLE_VERSION
    if (cbh->cb_err == kDNSServiceErr_PolicyDenied && !_should_return_noauth_error())
    {
        return;
    }
#endif
    uint32_t ttl;
    char name[kDNSServiceMaxDomainName];
    uint16_t rrtype, rrclass, rdlen;
    const char *rdata;

    get_string(&data, end, name, kDNSServiceMaxDomainName);
    rrtype  = get_uint16(&data, end);
    rrclass = get_uint16(&data, end);
    rdlen   = get_uint16(&data, end);
    rdata   = get_rdata(&data, end, rdlen);
    ttl     = get_uint32(&data, end);

    if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_query_response: error reading result from daemon");
    else ((DNSServiceQueryRecordReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, name, rrtype, rrclass, rdlen, rdata, ttl, sdr->AppContext);
    // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
}

#if APPLE_OSX_mDNSResponder
static size_t get_required_length_for_defaults(const xpc_object_t defaults)
{
    size_t required_len = 0;
    size_t plist_data_len = 0;
    // Add length for IPC_TLV_TYPE_RESOLVER_CONFIG_PLIST_DATA.
    if (xpc_dictionary_get_data(defaults, kDNSServiceDefaultsKey_ResolverConfigPListData, &plist_data_len))
    {
        required_len += get_required_tlv16_length(plist_data_len);
    }
    // Add length for IPC_TLV_TYPE_REQUIRE_PRIVACY.
    required_len += get_required_tlv16_length(sizeof(uint8_t));
    return required_len;
}

static void put_tlvs_for_defaults(const xpc_object_t defaults, ipc_msg_hdr *const hdr, char **ptr)
{
    uint8_t require_privacy;
    size_t plist_data_len = 0;
    const uint8_t *const plist_data_ptr = xpc_dictionary_get_data(defaults,
        kDNSServiceDefaultsKey_ResolverConfigPListData, &plist_data_len);
    if (plist_data_ptr)
    {
        put_tlv16(IPC_TLV_TYPE_RESOLVER_CONFIG_PLIST_DATA, (uint16_t)plist_data_len, plist_data_ptr, ptr);
    }
    require_privacy = xpc_dictionary_get_bool(defaults, kDNSServiceDefaultsKey_RequirePrivacy) ? 1 : 0;
    put_tlv16(IPC_TLV_TYPE_REQUIRE_PRIVACY, sizeof(require_privacy), &require_privacy, ptr);
    hdr->ipc_flags |= IPC_FLAGS_TRAILING_TLVS;
}
#endif

DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
(
    DNSServiceRef              *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char                 *name,
    uint16_t rrtype,
    uint16_t rrclass,
    DNSServiceQueryRecordReply callBack,
    void                       *context
)
{
    char *ptr;
    size_t len;
    ipc_msg_hdr *hdr;
    DNSServiceErrorType err;
#if APPLE_OSX_mDNSResponder
    xpc_object_t defaults;
#endif
    // NULL name handled below.
    if (!sdRef || !callBack) return kDNSServiceErr_BadParam;

    if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
        flags |= kDNSServiceFlagsIncludeP2P;

    err = ConnectToServer(sdRef, flags, query_request, handle_query_response, (void *)callBack, context);
    if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL

    if (!name) name = "\0";

    // Calculate total message length
    len = sizeof(flags);
    len += sizeof(uint32_t);  // interfaceIndex
    len += strlen(name) + 1;
    len += 2 * sizeof(uint16_t);  // rrtype, rrclass
#if APPLE_OSX_mDNSResponder
    defaults = DNSServiceGetRetainedResolverDefaults();
    if (defaults)
    {
        len += get_required_length_for_defaults(defaults);
    }
#endif
    hdr = create_hdr(query_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
    if (!hdr)
    {
        DNSServiceRefDeallocate(*sdRef);
        *sdRef = NULL;
#if APPLE_OSX_mDNSResponder
        xpc_forget(&defaults);
#endif
        return kDNSServiceErr_NoMemory;
    }
    put_flags(flags, &ptr);
    put_uint32(interfaceIndex, &ptr);
    put_string(name, &ptr);
    put_uint16(rrtype, &ptr);
    put_uint16(rrclass, &ptr);
#if APPLE_OSX_mDNSResponder
    if (defaults)
    {
        put_tlvs_for_defaults(defaults, hdr, &ptr);
        xpc_forget(&defaults);
    }
#endif
    err = deliver_request(hdr, *sdRef);     // Will free hdr for us
#if CHECK_BUNDLE_VERSION
    if (err == kDNSServiceErr_NoAuth && !_should_return_noauth_error())
    {
        err = kDNSServiceErr_NoError;
    }
#endif
    if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
    return err;
}

static void handle_addrinfo_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
{
#if CHECK_BUNDLE_VERSION
    if (cbh->cb_err == kDNSServiceErr_PolicyDenied && !_should_return_noauth_error())
    {
        return;
    }
#endif
    char hostname[kDNSServiceMaxDomainName];
    uint16_t rrtype, rrclass, rdlen;
    const char *rdata;
    uint32_t ttl;

    get_string(&data, end, hostname, kDNSServiceMaxDomainName);
    rrtype  = get_uint16(&data, end);
    rrclass = get_uint16(&data, end);
    rdlen   = get_uint16(&data, end);
    rdata   = get_rdata (&data, end, rdlen);
    ttl     = get_uint32(&data, end);
    (void)rrclass; // Unused

    // We only generate client callbacks for A and AAAA results (including NXDOMAIN results for
    // those types, if the client has requested those with the kDNSServiceFlagsReturnIntermediates).
    // Other result types, specifically CNAME referrals, are not communicated to the client, because
    // the DNSServiceGetAddrInfoReply interface doesn't have any meaningful way to communiate CNAME referrals.
    if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_addrinfo_response: error reading result from daemon");
    else if (rrtype == kDNSServiceType_A || rrtype == kDNSServiceType_AAAA)
    {
        struct sockaddr_in sa4;
        struct sockaddr_in6 sa6;
        const struct sockaddr *const sa = (rrtype == kDNSServiceType_A) ? (struct sockaddr*)&sa4 : (struct sockaddr*)&sa6;
        if (rrtype == kDNSServiceType_A)
        {
            memset(&sa4, 0, sizeof(sa4));
            #ifndef NOT_HAVE_SA_LEN
            sa4.sin_len = sizeof(struct sockaddr_in);
            #endif
            sa4.sin_family = AF_INET;
            //  sin_port   = 0;
            if (!cbh->cb_err) memcpy(&sa4.sin_addr, rdata, rdlen);
        }
        else
        {
            memset(&sa6, 0, sizeof(sa6));
            #ifndef NOT_HAVE_SA_LEN
            sa6.sin6_len = sizeof(struct sockaddr_in6);
            #endif
            sa6.sin6_family     = AF_INET6;
            //  sin6_port     = 0;
            //  sin6_flowinfo = 0;
            //  sin6_scope_id = 0;
            if (!cbh->cb_err)
            {
                memcpy(&sa6.sin6_addr, rdata, rdlen);
                if (IN6_IS_ADDR_LINKLOCAL(&sa6.sin6_addr)) sa6.sin6_scope_id = cbh->cb_interface;
            }
        }

		((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, hostname, sa, ttl, sdr->AppContext);
    }
    else if (cbh->cb_err == kDNSServiceErr_PolicyDenied)
    {
        ((DNSServiceGetAddrInfoReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, hostname, NULL, ttl, sdr->AppContext);
    }
}

DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
(
    DNSServiceRef                    *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    uint32_t protocol,
    const char                       *hostname,
    DNSServiceGetAddrInfoReply callBack,
    void                             *context          /* may be NULL */
)
{
    char *ptr;
    size_t len;
    ipc_msg_hdr *hdr;
    DNSServiceErrorType err;
#if APPLE_OSX_mDNSResponder
    xpc_object_t defaults;
#endif

    if (!sdRef || !hostname || !callBack) return kDNSServiceErr_BadParam;

    err = ConnectToServer(sdRef, flags, addrinfo_request, handle_addrinfo_response, (void *)callBack, context);
    if (err)
    {
         return err;    // On error ConnectToServer leaves *sdRef set to NULL
    }

    // Calculate total message length
    len = sizeof(flags);
    len += sizeof(uint32_t);      // interfaceIndex
    len += sizeof(uint32_t);      // protocol
    len += strlen(hostname) + 1;
#if APPLE_OSX_mDNSResponder
    defaults = DNSServiceGetRetainedResolverDefaults();
    if (defaults)
    {
        len += get_required_length_for_defaults(defaults);
    }
#endif
    hdr = create_hdr(addrinfo_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
    if (!hdr)
    {
        DNSServiceRefDeallocate(*sdRef);
        *sdRef = NULL;
#if APPLE_OSX_mDNSResponder
        xpc_forget(&defaults);
#endif
        return kDNSServiceErr_NoMemory;
    }
    put_flags(flags, &ptr);
    put_uint32(interfaceIndex, &ptr);
    put_uint32(protocol, &ptr);
    put_string(hostname, &ptr);
#if APPLE_OSX_mDNSResponder
    if (defaults)
    {
        put_tlvs_for_defaults(defaults, hdr, &ptr);
        xpc_forget(&defaults);
    }
#endif
    err = deliver_request(hdr, *sdRef);     // Will free hdr for us
#if CHECK_BUNDLE_VERSION
    if (err == kDNSServiceErr_NoAuth && !_should_return_noauth_error())
    {
        err = kDNSServiceErr_NoError;
    }
#endif
    if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
    return err;
}

static void handle_browse_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
{
#if CHECK_BUNDLE_VERSION
    if (cbh->cb_err == kDNSServiceErr_PolicyDenied && !_should_return_noauth_error())
    {
        return;
    }
#endif
    char replyName[256], replyType[kDNSServiceMaxDomainName], replyDomain[kDNSServiceMaxDomainName];
    get_string(&data, end, replyName, 256);
    get_string(&data, end, replyType, kDNSServiceMaxDomainName);
    get_string(&data, end, replyDomain, kDNSServiceMaxDomainName);
    if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_browse_response: error reading result from daemon");
    else ((DNSServiceBrowseReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, replyName, replyType, replyDomain, sdr->AppContext);
    // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
}

DNSServiceErrorType DNSSD_API DNSServiceBrowse
(
    DNSServiceRef         *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char            *regtype,
    const char            *domain,
    DNSServiceBrowseReply callBack,
    void                  *context
)
{
    char *ptr;
    size_t len;
    ipc_msg_hdr *hdr;
    DNSServiceErrorType err;

    // NULL domain handled below
    if (!sdRef || !regtype || !callBack) return kDNSServiceErr_BadParam;

    if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
        flags |= kDNSServiceFlagsIncludeP2P;

    err = ConnectToServer(sdRef, flags, browse_request, handle_browse_response, (void *)callBack, context);
    if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL

    if (!domain) domain = "";
    len = sizeof(flags);
    len += sizeof(interfaceIndex);
    len += strlen(regtype) + 1;
    len += strlen(domain) + 1;

    hdr = create_hdr(browse_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
    if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }

    put_flags(flags, &ptr);
    put_uint32(interfaceIndex, &ptr);
    put_string(regtype, &ptr);
    put_string(domain, &ptr);

    err = deliver_request(hdr, *sdRef);     // Will free hdr for us
#if CHECK_BUNDLE_VERSION
    if (err == kDNSServiceErr_NoAuth && !_should_return_noauth_error())
    {
        err = kDNSServiceErr_NoError;
    }
#endif
    if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
    return err;
}

DNSServiceErrorType DNSSD_API DNSServiceSetDefaultDomainForUser(DNSServiceFlags flags, const char *domain)
{
    DNSServiceErrorType err;
    DNSServiceOp *tmp;
    char *ptr;
    size_t len;
    ipc_msg_hdr *hdr;

    if (!domain) return kDNSServiceErr_BadParam;
    len = sizeof(flags) + strlen(domain) + 1;

    err = ConnectToServer(&tmp, 0, setdomain_request, NULL, NULL, NULL);
    if (err) return err;

    hdr = create_hdr(setdomain_request, &len, &ptr, 0, tmp);
    if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }

    put_flags(flags, &ptr);
    put_string(domain, &ptr);
    err = deliver_request(hdr, tmp);        // Will free hdr for us
    DNSServiceRefDeallocate(tmp);
    return err;
}

static void handle_regservice_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
{
#if CHECK_BUNDLE_VERSION
    if (cbh->cb_err == kDNSServiceErr_PolicyDenied && !_should_return_noauth_error())
    {
        return;
    }
#endif
    char name[256], regtype[kDNSServiceMaxDomainName], domain[kDNSServiceMaxDomainName];
    get_string(&data, end, name, 256);
    get_string(&data, end, regtype, kDNSServiceMaxDomainName);
    get_string(&data, end, domain,  kDNSServiceMaxDomainName);
    if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_regservice_response: error reading result from daemon");
    else ((DNSServiceRegisterReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_err, name, regtype, domain, sdr->AppContext);
    // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
}

DNSServiceErrorType DNSSD_API DNSServiceRegister
(
    DNSServiceRef                       *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char                          *name,
    const char                          *regtype,
    const char                          *domain,
    const char                          *host,
    uint16_t PortInNetworkByteOrder,
    uint16_t txtLen,
    const void                          *txtRecord,
    DNSServiceRegisterReply callBack,
    void                                *context
)
{
    char *ptr;
    size_t len;
    ipc_msg_hdr *hdr;
    DNSServiceErrorType err;
    union { uint16_t s; u_char b[2]; } port = { PortInNetworkByteOrder };

    if (!sdRef || !regtype) return kDNSServiceErr_BadParam;
    if (!name) name = "";
    if (!domain) domain = "";
    if (!host) host = "";
    if (!txtRecord) txtRecord = (void*)"";

    // No callback must have auto-rename
    if (!callBack && (flags & kDNSServiceFlagsNoAutoRename)) return kDNSServiceErr_BadParam;

    if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
        flags |= kDNSServiceFlagsIncludeP2P;

    err = ConnectToServer(sdRef, flags, reg_service_request, callBack ? handle_regservice_response : NULL, (void *)callBack, context);
    if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL

    len = sizeof(DNSServiceFlags);
    len += sizeof(uint32_t);  // interfaceIndex
    len += strlen(name) + strlen(regtype) + strlen(domain) + strlen(host) + 4;
    len += 2 * sizeof(uint16_t);  // port, txtLen
    len += txtLen;

    hdr = create_hdr(reg_service_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
    if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }
    if (!callBack) hdr->ipc_flags |= IPC_FLAGS_NOREPLY;

    put_flags(flags, &ptr);
    put_uint32(interfaceIndex, &ptr);
    put_string(name, &ptr);
    put_string(regtype, &ptr);
    put_string(domain, &ptr);
    put_string(host, &ptr);
    *ptr++ = port.b[0];
    *ptr++ = port.b[1];
    put_uint16(txtLen, &ptr);
    put_rdata(txtLen, txtRecord, &ptr);

    err = deliver_request(hdr, *sdRef);     // Will free hdr for us
#if CHECK_BUNDLE_VERSION
    if (err == kDNSServiceErr_NoAuth && !_should_return_noauth_error())
    {
        err = kDNSServiceErr_NoError;
    }
#endif
    if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
    return err;
}

static void handle_enumeration_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
{
    char domain[kDNSServiceMaxDomainName];
    get_string(&data, end, domain, kDNSServiceMaxDomainName);
    if (!data) syslog(LOG_WARNING, "dnssd_clientstub handle_enumeration_response: error reading result from daemon");
    else ((DNSServiceDomainEnumReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, domain, sdr->AppContext);
    // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
}

DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
(
    DNSServiceRef             *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    DNSServiceDomainEnumReply callBack,
    void                      *context
)
{
    char *ptr;
    size_t len;
    ipc_msg_hdr *hdr;
    DNSServiceErrorType err;
    int f1;
    int f2;

    if (!sdRef || !callBack) return kDNSServiceErr_BadParam;

    f1 = (flags & kDNSServiceFlagsBrowseDomains) != 0;
    f2 = (flags & kDNSServiceFlagsRegistrationDomains) != 0;
    if (f1 + f2 != 1) return kDNSServiceErr_BadParam;

    err = ConnectToServer(sdRef, flags, enumeration_request, handle_enumeration_response, (void *)callBack, context);
    if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL

    len = sizeof(DNSServiceFlags);
    len += sizeof(uint32_t);

    hdr = create_hdr(enumeration_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
    if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }

    put_flags(flags, &ptr);
    put_uint32(interfaceIndex, &ptr);

    err = deliver_request(hdr, *sdRef);     // Will free hdr for us
    if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
    return err;
}

static void ConnectionResponse(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *const data, const char *const end)
{
    (void)data; // Unused

    //printf("ConnectionResponse got %d\n", cbh->ipc_hdr.op);
    if (cbh->ipc_hdr.op != reg_record_reply_op)
    {
        // When using kDNSServiceFlagsShareConnection, need to search the list of associated DNSServiceOps
        // to find the one this response is intended for, and then call through to its ProcessReply handler.
        // We start with our first subordinate DNSServiceRef -- don't want to accidentally match the parent DNSServiceRef.
        DNSServiceOp *op = sdr->next;
        while (op && (op->uid.u32[0] != cbh->ipc_hdr.client_context.u32[0] || op->uid.u32[1] != cbh->ipc_hdr.client_context.u32[1]))
            op = op->next;
        // Note: We may sometimes not find a matching DNSServiceOp, in the case where the client has
        // cancelled the subordinate DNSServiceOp, but there are still messages in the pipeline from the daemon
        if (op && op->ProcessReply) op->ProcessReply(op, cbh, data, end);
        // WARNING: Don't touch op or sdr after this -- client may have called DNSServiceRefDeallocate
        return;
    }
    else
    {
#if CHECK_BUNDLE_VERSION
        if (cbh->cb_err == kDNSServiceErr_PolicyDenied && !_should_return_noauth_error())
        {
            return;
        }
#endif
        DNSRecordRef rec;
        for (rec = sdr->rec; rec; rec = rec->recnext)
        {
            if (rec->uid.u32[0] == cbh->ipc_hdr.client_context.u32[0] && rec->uid.u32[1] == cbh->ipc_hdr.client_context.u32[1])
                break;
        }
        // The record might have been freed already and hence not an
        // error if the record is not found.
        if (!rec)
        {
            syslog(LOG_INFO, "dnssd_clientstub ConnectionResponse: Record not found");
            return;
        }
        if (rec->sdr != sdr)
        {
            syslog(LOG_WARNING, "dnssd_clientstub ConnectionResponse: Record sdr mismatch: rec %p sdr %p", rec->sdr, sdr);
            return;
        }

        if (sdr->op == connection_request || sdr->op == connection_delegate_request)
        {
            rec->AppCallback(rec->sdr, rec, cbh->cb_flags, cbh->cb_err, rec->AppContext);
        }
        else
        {
            syslog(LOG_WARNING, "dnssd_clientstub ConnectionResponse: sdr->op != connection_request");
            rec->AppCallback(rec->sdr, rec, 0, kDNSServiceErr_Unknown, rec->AppContext);
        }
        // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function
    }
}

DNSServiceErrorType DNSSD_API DNSServiceCreateConnection(DNSServiceRef *sdRef)
{
    DNSServiceErrorType err;
    char *ptr;
    size_t len = 0;
    ipc_msg_hdr *hdr;

    if (!sdRef) return kDNSServiceErr_BadParam;
    err = ConnectToServer(sdRef, 0, connection_request, ConnectionResponse, NULL, NULL);
    if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL

    hdr = create_hdr(connection_request, &len, &ptr, 0, *sdRef);
    if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }

    err = deliver_request(hdr, *sdRef);     // Will free hdr for us
    if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
    return err;
}

#if APPLE_OSX_mDNSResponder && !TARGET_OS_SIMULATOR
DNSServiceErrorType DNSSD_API DNSServiceCreateDelegateConnection(DNSServiceRef *sdRef, int32_t pid, uuid_t uuid)
{
    char *ptr;
    size_t len = 0;
    ipc_msg_hdr *hdr;

    if (!sdRef) return kDNSServiceErr_BadParam;
    DNSServiceErrorType err = ConnectToServer(sdRef, 0, connection_delegate_request, ConnectionResponse, NULL, NULL);
    if (err)
    {
         return err;    // On error ConnectToServer leaves *sdRef set to NULL
    }

    // Only one of the two options can be set. If pid is zero, uuid is used.
    // If both are specified only pid will be used. We send across the pid
    // so that the daemon knows what to read from the socket.

    len += sizeof(int32_t);

    hdr = create_hdr(connection_delegate_request, &len, &ptr, 0, *sdRef);
    if (!hdr)
    {
        DNSServiceRefDeallocate(*sdRef);
        *sdRef = NULL;
        return kDNSServiceErr_NoMemory;
    }

    if (pid && setsockopt((*sdRef)->sockfd, SOL_SOCKET, SO_DELEGATED, &pid, sizeof(pid)) == -1)
    { 
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceCreateDelegateConnection: Could not setsockopt() for PID[%d], no entitlements or process(pid) invalid errno:%d (%s)", pid, errno, strerror(errno)); 
        // Free the hdr in case we return before calling deliver_request() 
        if (hdr)
            free(hdr);
        DNSServiceRefDeallocate(*sdRef);
        *sdRef = NULL;
        return kDNSServiceErr_NoAuth;
    }

    if (!pid && setsockopt((*sdRef)->sockfd, SOL_SOCKET, SO_DELEGATED_UUID, uuid, sizeof(uuid_t)) == -1)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceCreateDelegateConnection: Could not setsockopt() for UUID, no entitlements or process(uuid) invalid errno:%d (%s) ", errno, strerror(errno));
        // Free the hdr in case we return before calling deliver_request()
        if (hdr)
            free(hdr);
        DNSServiceRefDeallocate(*sdRef);
        *sdRef = NULL;
        return kDNSServiceErr_NoAuth;
    }

    put_uint32(pid, &ptr);

    err = deliver_request(hdr, *sdRef);     // Will free hdr for us
    if (err)
    {
        DNSServiceRefDeallocate(*sdRef);
        *sdRef = NULL;
    }
    return err;
}
#elif TARGET_OS_SIMULATOR // This hack is for Simulator platform only
DNSServiceErrorType DNSSD_API DNSServiceCreateDelegateConnection(DNSServiceRef *sdRef, int32_t pid, uuid_t uuid)
{
    (void) pid;
    (void) uuid;
    return DNSServiceCreateConnection(sdRef);
}
#endif

DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
(
    DNSServiceRef sdRef,
    DNSRecordRef                  *RecordRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char                    *fullname,
    uint16_t rrtype,
    uint16_t rrclass,
    uint16_t rdlen,
    const void                    *rdata,
    uint32_t ttl,
    DNSServiceRegisterRecordReply callBack,
    void                          *context
)
{
    DNSServiceErrorType err;
    char *ptr;
    size_t len;
    ipc_msg_hdr *hdr = NULL;
    DNSRecordRef rref = NULL;
    DNSRecord **p;
    // Verify that only one of the following flags is set.
    int f1 = (flags & kDNSServiceFlagsShared) != 0;
    int f2 = (flags & kDNSServiceFlagsUnique) != 0;
    int f3 = (flags & kDNSServiceFlagsKnownUnique) != 0;
    if (f1 + f2 + f3 != 1) return kDNSServiceErr_BadParam;

    if ((interfaceIndex == kDNSServiceInterfaceIndexAny) && includeP2PWithIndexAny())
        flags |= kDNSServiceFlagsIncludeP2P;

    if (!sdRef || !RecordRef || !fullname || (!rdata && rdlen) || !callBack)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with NULL parameter");
        return kDNSServiceErr_BadParam;
    }

    if (!DNSServiceRefValid(sdRef))
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
        return kDNSServiceErr_BadReference;
    }

    if (sdRef->op != connection_request && sdRef->op != connection_delegate_request)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRegisterRecord called with non-DNSServiceCreateConnection DNSServiceRef %p %d", sdRef, sdRef->op);
        return kDNSServiceErr_BadReference;
    }

    *RecordRef = NULL;

    len = sizeof(DNSServiceFlags);
    len += 2 * sizeof(uint32_t);  // interfaceIndex, ttl
    len += 3 * sizeof(uint16_t);  // rrtype, rrclass, rdlen
    len += strlen(fullname) + 1;
    len += rdlen;

    // Bump up the uid. Normally for shared operations (kDNSServiceFlagsShareConnection), this
    // is done in ConnectToServer. For DNSServiceRegisterRecord, ConnectToServer has already
    // been called. As multiple DNSServiceRegisterRecords can be multiplexed over a single
    // connection, we need a way to demultiplex the response so that the callback corresponding
    // to the right DNSServiceRegisterRecord instance can be called. Use the same mechanism that
    // is used by kDNSServiceFlagsShareConnection. create_hdr copies the uid value to ipc
    // hdr->client_context which will be returned in the ipc response.
    if (++sdRef->uid.u32[0] == 0)
        ++sdRef->uid.u32[1];
    hdr = create_hdr(reg_record_request, &len, &ptr, 1, sdRef);
    if (!hdr) return kDNSServiceErr_NoMemory;

    put_flags(flags, &ptr);
    put_uint32(interfaceIndex, &ptr);
    put_string(fullname, &ptr);
    put_uint16(rrtype, &ptr);
    put_uint16(rrclass, &ptr);
    put_uint16(rdlen, &ptr);
    put_rdata(rdlen, rdata, &ptr);
    put_uint32(ttl, &ptr);

    rref = malloc(sizeof(DNSRecord));
    if (!rref) { free(hdr); return kDNSServiceErr_NoMemory; }
    rref->AppContext = context;
    rref->AppCallback = callBack;
    rref->record_index = sdRef->max_index++;
    rref->sdr = sdRef;
    rref->recnext = NULL;
    *RecordRef = rref;
    // Remember the uid that we are sending across so that we can match
    // when the response comes back.
    rref->uid = sdRef->uid;
    hdr->reg_index = rref->record_index;

    p = &(sdRef)->rec;
    while (*p) p = &(*p)->recnext;
    *p = rref;

    err = deliver_request(hdr, sdRef);     // Will free hdr for us
#if CHECK_BUNDLE_VERSION
    if (err == kDNSServiceErr_NoAuth && !_should_return_noauth_error())
    {
        err = kDNSServiceErr_NoError;
    }
#endif
    return err;
}

// sdRef returned by DNSServiceRegister()
DNSServiceErrorType DNSSD_API DNSServiceAddRecord
(
    DNSServiceRef sdRef,
    DNSRecordRef    *RecordRef,
    DNSServiceFlags flags,
    uint16_t rrtype,
    uint16_t rdlen,
    const void      *rdata,
    uint32_t ttl
)
{
    ipc_msg_hdr *hdr;
    size_t len = 0;
    char *ptr;
    DNSRecordRef rref;
    DNSRecord **p;

    if (!sdRef || !RecordRef || (!rdata && rdlen))
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with NULL parameter");
        return kDNSServiceErr_BadParam;
    }
    if (sdRef->op != reg_service_request)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with non-DNSServiceRegister DNSServiceRef %p %d", sdRef, sdRef->op);
        return kDNSServiceErr_BadReference;
    }

    if (!DNSServiceRefValid(sdRef))
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceAddRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
        return kDNSServiceErr_BadReference;
    }

    *RecordRef = NULL;

    len += 2 * sizeof(uint16_t);  // rrtype, rdlen
    len += rdlen;
    len += sizeof(uint32_t);
    len += sizeof(DNSServiceFlags);

    hdr = create_hdr(add_record_request, &len, &ptr, 1, sdRef);
    if (!hdr) return kDNSServiceErr_NoMemory;
    put_flags(flags, &ptr);
    put_uint16(rrtype, &ptr);
    put_uint16(rdlen, &ptr);
    put_rdata(rdlen, rdata, &ptr);
    put_uint32(ttl, &ptr);

    rref = malloc(sizeof(DNSRecord));
    if (!rref) { free(hdr); return kDNSServiceErr_NoMemory; }
    rref->AppContext = NULL;
    rref->AppCallback = NULL;
    rref->record_index = sdRef->max_index++;
    rref->sdr = sdRef;
    rref->recnext = NULL;
    *RecordRef = rref;
    hdr->reg_index = rref->record_index;

    p = &(sdRef)->rec;
    while (*p) p = &(*p)->recnext;
    *p = rref;

    return deliver_request(hdr, sdRef);     // Will free hdr for us
}

// DNSRecordRef returned by DNSServiceRegisterRecord or DNSServiceAddRecord
DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
(
    DNSServiceRef sdRef,
    DNSRecordRef RecordRef,
    DNSServiceFlags flags,
    uint16_t rdlen,
    const void      *rdata,
    uint32_t ttl
)
{
    ipc_msg_hdr *hdr;
    size_t len = 0;
    char *ptr;

    if (!sdRef || (!rdata && rdlen))
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with NULL parameter");
        return kDNSServiceErr_BadParam;
    }

    if (!DNSServiceRefValid(sdRef))
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceUpdateRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
        return kDNSServiceErr_BadReference;
    }

    // Note: RecordRef is allowed to be NULL

    len += sizeof(uint16_t);
    len += rdlen;
    len += sizeof(uint32_t);
    len += sizeof(DNSServiceFlags);

    hdr = create_hdr(update_record_request, &len, &ptr, 1, sdRef);
    if (!hdr) return kDNSServiceErr_NoMemory;
    hdr->reg_index = RecordRef ? RecordRef->record_index : TXT_RECORD_INDEX;
    put_flags(flags, &ptr);
    put_uint16(rdlen, &ptr);
    put_rdata(rdlen, rdata, &ptr);
    put_uint32(ttl, &ptr);
    return deliver_request(hdr, sdRef);     // Will free hdr for us
}

DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
(
    DNSServiceRef sdRef,
    DNSRecordRef RecordRef,
    DNSServiceFlags flags
)
{
    ipc_msg_hdr *hdr;
    size_t len = 0;
    char *ptr;
    DNSServiceErrorType err;

    if (!sdRef)            { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSServiceRef"); return kDNSServiceErr_BadParam; }
    if (!RecordRef)        { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with NULL DNSRecordRef");  return kDNSServiceErr_BadParam; }
    if (!sdRef->max_index) { syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with bad DNSServiceRef");  return kDNSServiceErr_BadReference; }

    if (!DNSServiceRefValid(sdRef))
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceRemoveRecord called with invalid DNSServiceRef %p %08X %08X", sdRef, sdRef->sockfd, sdRef->validator);
        return kDNSServiceErr_BadReference;
    }

    len += sizeof(flags);
    hdr = create_hdr(remove_record_request, &len, &ptr, 1, sdRef);
    if (!hdr) return kDNSServiceErr_NoMemory;
    hdr->reg_index = RecordRef->record_index;
    put_flags(flags, &ptr);
    err = deliver_request(hdr, sdRef);      // Will free hdr for us
    if (!err)
    {
        // This RecordRef could have been allocated in DNSServiceRegisterRecord or DNSServiceAddRecord.
        // If so, delink from the list before freeing
        DNSRecord **p = &sdRef->rec;
        while (*p && *p != RecordRef) p = &(*p)->recnext;
        if (*p) *p = RecordRef->recnext;
        free(RecordRef);
    }
    return err;
}

DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
(
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    const char      *fullname,
    uint16_t rrtype,
    uint16_t rrclass,
    uint16_t rdlen,
    const void      *rdata
)
{
    DNSServiceErrorType err;
    char *ptr;
    size_t len;
    ipc_msg_hdr *hdr;
    DNSServiceOp *tmp = NULL;

    if (!fullname || (!rdata && rdlen)) return kDNSServiceErr_BadParam;

    err = ConnectToServer(&tmp, flags, reconfirm_record_request, NULL, NULL, NULL);
    if (err) return err;

    len = sizeof(DNSServiceFlags);
    len += sizeof(uint32_t);
    len += strlen(fullname) + 1;
    len += 3 * sizeof(uint16_t);
    len += rdlen;
    hdr = create_hdr(reconfirm_record_request, &len, &ptr, 0, tmp);
    if (!hdr) { DNSServiceRefDeallocate(tmp); return kDNSServiceErr_NoMemory; }

    put_flags(flags, &ptr);
    put_uint32(interfaceIndex, &ptr);
    put_string(fullname, &ptr);
    put_uint16(rrtype, &ptr);
    put_uint16(rrclass, &ptr);
    put_uint16(rdlen, &ptr);
    put_rdata(rdlen, rdata, &ptr);

    err = deliver_request(hdr, tmp);        // Will free hdr for us
    DNSServiceRefDeallocate(tmp);
    return err;
}


static void handle_port_mapping_response(DNSServiceOp *const sdr, const CallbackHeader *const cbh, const char *data, const char *const end)
{
    union { uint32_t l; u_char b[4]; } addr;
    uint8_t protocol;
    union { uint16_t s; u_char b[2]; } internalPort;
    union { uint16_t s; u_char b[2]; } externalPort;
    uint32_t ttl;

    if (!data || data + 13 > end) goto fail;

    addr.b[0] = *data++;
    addr.b[1] = *data++;
    addr.b[2] = *data++;
    addr.b[3] = *data++;
    protocol          = *data++;
    internalPort.b[0] = *data++;
    internalPort.b[1] = *data++;
    externalPort.b[0] = *data++;
    externalPort.b[1] = *data++;
    ttl               = get_uint32(&data, end);
    if (!data) goto fail;

    ((DNSServiceNATPortMappingReply)sdr->AppCallback)(sdr, cbh->cb_flags, cbh->cb_interface, cbh->cb_err, addr.l, protocol, internalPort.s, externalPort.s, ttl, sdr->AppContext);
    return;
    // MUST NOT touch sdr after invoking AppCallback -- client is allowed to dispose it from within callback function

    fail :
    syslog(LOG_WARNING, "dnssd_clientstub handle_port_mapping_response: error reading result from daemon");
}

DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
(
    DNSServiceRef                       *sdRef,
    DNSServiceFlags flags,
    uint32_t interfaceIndex,
    uint32_t protocol,                                /* TCP and/or UDP */
    uint16_t internalPortInNetworkByteOrder,
    uint16_t externalPortInNetworkByteOrder,
    uint32_t ttl,                                     /* time to live in seconds */
    DNSServiceNATPortMappingReply callBack,
    void                                *context      /* may be NULL */
)
{
    char *ptr;
    size_t len;
    ipc_msg_hdr *hdr;
    union { uint16_t s; u_char b[2]; } internalPort = { internalPortInNetworkByteOrder };
    union { uint16_t s; u_char b[2]; } externalPort = { externalPortInNetworkByteOrder };

    DNSServiceErrorType err = ConnectToServer(sdRef, flags, port_mapping_request, handle_port_mapping_response, (void *)callBack, context);
    if (err) return err;    // On error ConnectToServer leaves *sdRef set to NULL

    len = sizeof(flags);
    len += sizeof(interfaceIndex);
    len += sizeof(protocol);
    len += sizeof(internalPort);
    len += sizeof(externalPort);
    len += sizeof(ttl);

    hdr = create_hdr(port_mapping_request, &len, &ptr, (*sdRef)->primary ? 1 : 0, *sdRef);
    if (!hdr) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; return kDNSServiceErr_NoMemory; }

    put_flags(flags, &ptr);
    put_uint32(interfaceIndex, &ptr);
    put_uint32(protocol, &ptr);
    *ptr++ = internalPort.b[0];
    *ptr++ = internalPort.b[1];
    *ptr++ = externalPort.b[0];
    *ptr++ = externalPort.b[1];
    put_uint32(ttl, &ptr);

    err = deliver_request(hdr, *sdRef);     // Will free hdr for us
    if (err) { DNSServiceRefDeallocate(*sdRef); *sdRef = NULL; }
    return err;
}

#if _DNS_SD_LIBDISPATCH
DNSServiceErrorType DNSSD_API DNSServiceSetDispatchQueue
(
    DNSServiceRef service,
    dispatch_queue_t queue
)
{
    int dnssd_fd  = DNSServiceRefSockFD(service);
    if (dnssd_fd == dnssd_InvalidSocket) return kDNSServiceErr_BadParam;
    if (!queue)
    {
        syslog(LOG_WARNING, "dnssd_clientstub: DNSServiceSetDispatchQueue dispatch queue NULL");
        return kDNSServiceErr_BadParam;
    }
    if (service->disp_queue)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSetDispatchQueue dispatch queue set already");
        return kDNSServiceErr_BadParam;
    }
    if (service->disp_source)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSetDispatchQueue dispatch source set already");
        return kDNSServiceErr_BadParam;
    }
    service->disp_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, dnssd_fd, 0, queue);
    if (!service->disp_source)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSetDispatchQueue dispatch_source_create failed");
        return kDNSServiceErr_NoMemory;
    }
    service->disp_queue = queue;
    dispatch_source_set_event_handler(service->disp_source, ^{DNSServiceProcessResult(service);});
    dispatch_source_set_cancel_handler(service->disp_source, ^{dnssd_close(dnssd_fd);});
    dispatch_resume(service->disp_source);
    return kDNSServiceErr_NoError;
}
#endif // _DNS_SD_LIBDISPATCH

#if !defined(_WIN32)

static void DNSSD_API SleepKeepaliveCallback(DNSServiceRef sdRef, DNSRecordRef rec, const DNSServiceFlags flags,
                                             DNSServiceErrorType errorCode, void *context)
{
    SleepKAContext *ka = (SleepKAContext *)context;
    (void)rec;      // Unused
    (void)flags;    // Unused

    if (sdRef->kacontext != context)
        syslog(LOG_WARNING, "dnssd_clientstub SleepKeepaliveCallback context mismatch");

    if (ka->AppCallback)
        ((DNSServiceSleepKeepaliveReply)ka->AppCallback)(sdRef, errorCode, ka->AppContext);
}

static DNSServiceErrorType _DNSServiceSleepKeepalive_sockaddr
(
    DNSServiceRef *                 sdRef,
    DNSServiceFlags                 flags,
    const struct sockaddr *         localAddr,
    const struct sockaddr *         remoteAddr,
    unsigned int                    timeout,
    DNSServiceSleepKeepaliveReply   callBack,
    void *                          context
);

DNSServiceErrorType DNSSD_API DNSServiceSleepKeepalive
(
    DNSServiceRef                       *sdRef,
    DNSServiceFlags flags,
    int fd,
    unsigned int timeout,
    DNSServiceSleepKeepaliveReply callBack,
    void                                *context
)
{
    struct sockaddr_storage lss;
    struct sockaddr_storage rss;
    socklen_t len1, len2;

    len1 = sizeof(lss);
    if (getsockname(fd, (struct sockaddr *)&lss, &len1) < 0)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive: getsockname %d\n", errno);
        return kDNSServiceErr_BadParam;
    }

    len2 = sizeof(rss);
    if (getpeername(fd, (struct sockaddr *)&rss, &len2) < 0)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive: getpeername %d\n", errno);
        return kDNSServiceErr_BadParam;
    }

    if (len1 != len2)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive local/remote info not same");
        return kDNSServiceErr_Unknown;
    }
    return _DNSServiceSleepKeepalive_sockaddr(sdRef, flags, (const struct sockaddr *)&lss, (const struct sockaddr *)&rss,
        timeout, callBack, context);
}

DNSServiceErrorType DNSSD_API DNSServiceSleepKeepalive_sockaddr
(
    DNSServiceRef *                 sdRef,
    DNSServiceFlags                 flags,
    const struct sockaddr *         localAddr,
    const struct sockaddr *         remoteAddr,
    unsigned int                    timeout,
    DNSServiceSleepKeepaliveReply   callBack,
    void *                          context
)
{
    return _DNSServiceSleepKeepalive_sockaddr(sdRef, flags, localAddr, remoteAddr, timeout, callBack, context );
}

static DNSServiceErrorType _DNSServiceSleepKeepalive_sockaddr
(
    DNSServiceRef *                 sdRef,
    DNSServiceFlags                 flags,
    const struct sockaddr *         localAddr,
    const struct sockaddr *         remoteAddr,
    unsigned int                    timeout,
    DNSServiceSleepKeepaliveReply   callBack,
    void *                          context
)
{
    char source_str[INET6_ADDRSTRLEN];
    char target_str[INET6_ADDRSTRLEN];
    unsigned int len, proxyreclen;
    char buf[256];
    DNSServiceErrorType err;
    DNSRecordRef record = NULL;
    char name[10];
    char recname[128];
    SleepKAContext *ka;
    unsigned int i, unique;

    (void) flags; //unused
    if (!timeout) return kDNSServiceErr_BadParam;

    unique = 0;
    if ((localAddr->sa_family == AF_INET) && (remoteAddr->sa_family == AF_INET))
    {
        const struct sockaddr_in *sl = (const struct sockaddr_in *)localAddr;
        const struct sockaddr_in *sr = (const struct sockaddr_in *)remoteAddr;
        unsigned char *ptr = (unsigned char *)&sl->sin_addr;

        if (!inet_ntop(AF_INET, (const void *)&sr->sin_addr, target_str, sizeof (target_str)))
        {
            syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive remote info failed %d", errno);
            return kDNSServiceErr_Unknown;
        }
        if (!inet_ntop(AF_INET, (const void *)&sl->sin_addr, source_str, sizeof (source_str)))
        {
            syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive local info failed %d", errno);
            return kDNSServiceErr_Unknown;
        }
        // Sum of all bytes in the local address and port should result in a unique
        // number in the local network
        for (i = 0; i < sizeof(struct in_addr); i++)
            unique += ptr[i];
        unique += sl->sin_port;
        len = snprintf(buf+1, sizeof(buf) - 1, "t=%u h=%s d=%s l=%u r=%u", timeout, source_str, target_str, ntohs(sl->sin_port), ntohs(sr->sin_port));
    }
    else if ((localAddr->sa_family == AF_INET6) && (remoteAddr->sa_family == AF_INET6))
    {
        const struct sockaddr_in6 *sl6 = (const struct sockaddr_in6 *)localAddr;
        const struct sockaddr_in6 *sr6 = (const struct sockaddr_in6 *)remoteAddr;
        unsigned char *ptr = (unsigned char *)&sl6->sin6_addr;

        if (!inet_ntop(AF_INET6, (const void *)&sr6->sin6_addr, target_str, sizeof (target_str)))
        {
            syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive remote6 info failed %d", errno);
            return kDNSServiceErr_Unknown;
        }
        if (!inet_ntop(AF_INET6, (const void *)&sl6->sin6_addr, source_str, sizeof (source_str)))
        {
            syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive local6 info failed %d", errno);
            return kDNSServiceErr_Unknown;
        }
        for (i = 0; i < sizeof(struct in6_addr); i++)
            unique += ptr[i];
        unique += sl6->sin6_port;
        len = snprintf(buf+1, sizeof(buf) - 1, "t=%u H=%s D=%s l=%u r=%u", timeout, source_str, target_str, ntohs(sl6->sin6_port), ntohs(sr6->sin6_port));
    }
    else
    {
        return kDNSServiceErr_BadParam;
    }

    if (len >= (sizeof(buf) - 1))
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive could not fit local/remote info");
        return kDNSServiceErr_Unknown;
    }
    // Include the NULL byte also in the first byte. The total length of the record includes the
    // first byte also.
    buf[0] = len + 1;
    proxyreclen = len + 2;

    len = snprintf(name, sizeof(name), "%u", unique);
    if (len >= sizeof(name))
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive could not fit unique");
        return kDNSServiceErr_Unknown;
    }

    len = snprintf(recname, sizeof(recname), "%s.%s", name, "_keepalive._dns-sd._udp.local");
    if (len >= sizeof(recname))
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive could not fit name");
        return kDNSServiceErr_Unknown;
    }

    ka = malloc(sizeof(SleepKAContext));
    if (!ka) return kDNSServiceErr_NoMemory;
    ka->AppCallback = (void *)callBack;
    ka->AppContext = context;

    err = DNSServiceCreateConnection(sdRef);
    if (err)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive cannot create connection");
        free(ka);
        return err;
    }

    // we don't care about the "record". When sdRef gets deallocated later, it will be freed too
    err = DNSServiceRegisterRecord(*sdRef, &record, kDNSServiceFlagsUnique, 0, recname,
                                   kDNSServiceType_NULL,  kDNSServiceClass_IN, proxyreclen, buf,  kDNSServiceInterfaceIndexAny, SleepKeepaliveCallback, ka);
    if (err)
    {
        syslog(LOG_WARNING, "dnssd_clientstub DNSServiceSleepKeepalive cannot create connection");
        free(ka);
        return err;
    }
    (*sdRef)->kacontext = ka;
    return kDNSServiceErr_NoError;
}
#endif
/*
 * Copyright (c) 2003-2020 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Inc. ("Apple") nor the names of its
 *     contributors may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "dnssd_ipc.h"
#if APPLE_OSX_mDNSResponder
#include "mdns_tlv.h"
#endif

#if defined(_WIN32)

char *win32_strerror(int inErrorCode)
{
    static char buffer[1024];
    DWORD n;
    memset(buffer, 0, sizeof(buffer));
    n = FormatMessageA(
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        (DWORD) inErrorCode,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        buffer,
        sizeof(buffer),
        NULL);
    if (n > 0)
    {
        // Remove any trailing CR's or LF's since some messages have them.
        while ((n > 0) && isspace(((unsigned char *) buffer)[n - 1]))
            buffer[--n] = '\0';
    }
    return buffer;
}

#endif

void put_uint32(const uint32_t l, char **ptr)
{
    (*ptr)[0] = (char)((l >> 24) &  0xFF);
    (*ptr)[1] = (char)((l >> 16) &  0xFF);
    (*ptr)[2] = (char)((l >>  8) &  0xFF);
    (*ptr)[3] = (char)((l      ) &  0xFF);
    *ptr += sizeof(uint32_t);
}

uint32_t get_uint32(const char **ptr, const char *end)
{
    if (!*ptr || *ptr + sizeof(uint32_t) > end)
    {
        *ptr = NULL;
        return(0);
    }
    else
    {
        uint8_t *p = (uint8_t*) *ptr;
        *ptr += sizeof(uint32_t);
        return((uint32_t) ((uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]));
    }
}

void put_uint16(uint16_t s, char **ptr)
{
    (*ptr)[0] = (char)((s >>  8) &  0xFF);
    (*ptr)[1] = (char)((s      ) &  0xFF);
    *ptr += sizeof(uint16_t);
}

uint16_t get_uint16(const char **ptr, const char *end)
{
    if (!*ptr || *ptr + sizeof(uint16_t) > end)
    {
        *ptr = NULL;
        return(0);
    }
    else
    {
        uint8_t *p = (uint8_t*) *ptr;
        *ptr += sizeof(uint16_t);
        return((uint16_t) ((uint16_t)p[0] << 8 | p[1]));
    }
}

int put_string(const char *str, char **ptr)
{
    size_t len;
    if (!str) str = "";
    len = strlen(str) + 1;
    memcpy(*ptr, str, len);
    *ptr += len;
    return 0;
}

int get_string(const char **ptr, const char *const end, char *buffer, int buflen)
{
    if (!*ptr)
    {
        *buffer = 0;
        return(-1);
    }
    else
    {
        char *lim = buffer + buflen;    // Calculate limit
        while (*ptr < end && buffer < lim)
        {
            char c = *buffer++ = *(*ptr)++;
            if (c == 0) return(0);      // Success
        }
        if (buffer == lim) buffer--;
        *buffer = 0;                    // Failed, so terminate string,
        *ptr = NULL;                    // clear pointer,
        return(-1);                     // and return failure indication
    }
}

void put_rdata(const int rdlen, const unsigned char *rdata, char **ptr)
{
    memcpy(*ptr, rdata, rdlen);
    *ptr += rdlen;
}

const char *get_rdata(const char **ptr, const char *end, int rdlen)
{
    if (!*ptr || *ptr + rdlen > end)
    {
        *ptr = NULL;
        return(0);
    }
    else
    {
        const char *rd = *ptr;
        *ptr += rdlen;
        return rd;
    }
}

#if APPLE_OSX_mDNSResponder
size_t get_required_tlv16_length(const uint16_t valuelen)
{
    return mdns_tlv16_get_required_length(valuelen);
}

void put_tlv16(const uint16_t type, const uint16_t length, const uint8_t *value, char **ptr)
{
	uint8_t *dst = (uint8_t *)*ptr;
	mdns_tlv16_set(dst, NULL, type, length, value, &dst);
    *ptr = (char *)dst;
}
#endif

void ConvertHeaderBytes(ipc_msg_hdr *hdr)
{
    hdr->version   = htonl(hdr->version);
    hdr->datalen   = htonl(hdr->datalen);
    hdr->ipc_flags = htonl(hdr->ipc_flags);
    hdr->op        = htonl(hdr->op );
    hdr->reg_index = htonl(hdr->reg_index);
}
/* -*- Mode: C; tab-width: 4 -*-
 *
 * Copyright (c) 2003-2020 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1.  Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Inc. ("Apple") nor the names of its
 *     contributors may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef DNSSD_IPC_H
#define DNSSD_IPC_H

#include "dns_sd.h"

//
// Common cross platform services
//
#if defined(WIN32)
#   include <winsock2.h>
#   define dnssd_InvalidSocket  INVALID_SOCKET
#   define dnssd_SocketValid(s) ((s) != INVALID_SOCKET)
#   define dnssd_EWOULDBLOCK    WSAEWOULDBLOCK
#   define dnssd_EINTR          WSAEINTR
#   define dnssd_ECONNRESET     WSAECONNRESET
#   define dnssd_socklen_t      int
#   define dnssd_close(sock)    closesocket(sock)
#   define dnssd_errno          WSAGetLastError()
#   define dnssd_strerror(X)    win32_strerror(X)
#   define ssize_t              int
#   define getpid               _getpid
#   define unlink               _unlink
extern char *win32_strerror(int inErrorCode);
#else
#   include <sys/types.h>
#   include <unistd.h>
#   include <sys/un.h>
#   include <string.h>
#   include <stdio.h>
#   include <stdlib.h>
#   include <sys/stat.h>
#   include <sys/socket.h>
#   include <netinet/in.h>
#   include <arpa/inet.h>
#   define dnssd_InvalidSocket  -1
#   define dnssd_SocketValid(s) ((s) >= 0)
#   define dnssd_EWOULDBLOCK    EWOULDBLOCK
#   define dnssd_EINTR          EINTR
#   define dnssd_ECONNRESET     ECONNRESET
#   define dnssd_EPIPE          EPIPE
#   define dnssd_socklen_t      unsigned int
#   define dnssd_close(sock)    close(sock)
#   define dnssd_errno          errno
#   define dnssd_strerror(X)    strerror(X)
#endif

#if defined(USE_TCP_LOOPBACK)
#   define AF_DNSSD             AF_INET
#   define MDNS_TCP_SERVERADDR  "127.0.0.1"
#   define MDNS_TCP_SERVERPORT  5354
#   define LISTENQ              5
#   define dnssd_sockaddr_t     struct sockaddr_in
#else
#   define AF_DNSSD             AF_LOCAL
#   ifndef MDNS_UDS_SERVERPATH
#       define MDNS_UDS_SERVERPATH  "/var/run/mDNSResponder"
#   endif
#   define MDNS_UDS_SERVERPATH_ENVVAR "DNSSD_UDS_PATH"
#   define LISTENQ              100
// longest legal control path length
#   define MAX_CTLPATH          (sizeof(((struct sockaddr_un*)0)->sun_path))
#   define dnssd_sockaddr_t     struct sockaddr_un
#endif

// Compatibility workaround
#ifndef AF_LOCAL
#define AF_LOCAL    AF_UNIX
#endif

// General UDS constants
#define TXT_RECORD_INDEX ((uint32_t)(-1))   // record index for default text record

// IPC data encoding constants and types
#define VERSION 1
#define IPC_FLAGS_NOREPLY       (1U << 0) // Set flag if no asynchronous replies are to be sent to client.
#define IPC_FLAGS_TRAILING_TLVS (1U << 1) // Set flag if TLVs follow the standard request data.

#define IPC_TLV_TYPE_RESOLVER_CONFIG_PLIST_DATA 1   // An nw_resolver_config as a binary property list.
#define IPC_TLV_TYPE_REQUIRE_PRIVACY            2   // A uint8. Non-zero means privacy is required, zero means not required.

// Structure packing macro. If we're not using GNUC, it's not fatal. Most compilers naturally pack the on-the-wire
// structures correctly anyway, so a plain "struct" is usually fine. In the event that structures are not packed
// correctly, our compile-time assertion checks will catch it and prevent inadvertent generation of non-working code.
#ifndef packedstruct
 #if ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
  #define packedstruct struct __attribute__((__packed__))
  #define packedunion  union  __attribute__((__packed__))
 #else
  #define packedstruct struct
  #define packedunion  union
 #endif
#endif

typedef enum
{
    request_op_none = 0,    // No request yet received on this connection
    connection_request = 1, // connected socket via DNSServiceConnect()
    reg_record_request,     // reg/remove record only valid for connected sockets
    remove_record_request,
    enumeration_request,
    reg_service_request,
    browse_request,
    resolve_request,
    query_request,
    reconfirm_record_request,
    add_record_request,
    update_record_request,
    setdomain_request,      // Up to here is in Tiger and B4W 1.0.3
    getproperty_request,    // New in B4W 1.0.4
    port_mapping_request,   // New in Leopard and B4W 2.0
    addrinfo_request,
    send_bpf,               // New in SL
    getpid_request,
    release_request,
    connection_delegate_request,

    cancel_request = 63
} request_op_t;

typedef enum
{
    enumeration_reply_op = 64,
    reg_service_reply_op,
    browse_reply_op,
    resolve_reply_op,
    query_reply_op,
    reg_record_reply_op,    // Up to here is in Tiger and B4W 1.0.3
    getproperty_reply_op,   // New in B4W 1.0.4
    port_mapping_reply_op,  // New in Leopard and B4W 2.0
    addrinfo_reply_op
} reply_op_t;

#if defined(_WIN64)
#   pragma pack(push,4)
#elif !defined(__GNUC__)
#   pragma pack(1)
#endif

// Define context object big enough to hold a 64-bit pointer,
// to accomodate 64-bit clients communicating with 32-bit daemon.
// There's no reason for the daemon to ever be a 64-bit process, but its clients might be
typedef packedunion
{
    void *context;
    uint32_t u32[2];
} client_context_t;

typedef packedstruct
{
    uint32_t version;
    uint32_t datalen;
    uint32_t ipc_flags;
    uint32_t op;        // request_op_t or reply_op_t
    client_context_t client_context; // context passed from client, returned by server in corresponding reply
    uint32_t reg_index;            // identifier for a record registered via DNSServiceRegisterRecord() on a
    // socket connected by DNSServiceCreateConnection().  Must be unique in the scope of the connection, such that and
    // index/socket pair uniquely identifies a record.  (Used to select records for removal by DNSServiceRemoveRecord())
} ipc_msg_hdr;

#if defined(_WIN64)
#   pragma pack(pop)
#elif !defined(__GNUC__)
#   pragma pack()
#endif

// routines to write to and extract data from message buffers.
// caller responsible for bounds checking.
// ptr is the address of the pointer to the start of the field.
// it is advanced to point to the next field, or the end of the message

void put_uint32(const uint32_t l, char **ptr);
uint32_t get_uint32(const char **ptr, const char *end);

void put_uint16(uint16_t s, char **ptr);
uint16_t get_uint16(const char **ptr, const char *end);

#define put_flags put_uint32
#define get_flags get_uint32

#define put_error_code put_uint32
#define get_error_code get_uint32

int put_string(const char *str, char **ptr);
int get_string(const char **ptr, const char *const end, char *buffer, int buflen);

void put_rdata(const int rdlen, const unsigned char *rdata, char **ptr);
const char *get_rdata(const char **ptr, const char *end, int rdlen);  // return value is rdata pointed to by *ptr -
// rdata is not copied from buffer.

#if APPLE_OSX_mDNSResponder
size_t get_required_tlv16_length(const uint16_t valuelen);
void put_tlv16(const uint16_t type, const uint16_t length, const uint8_t *value, char **ptr);
#endif

void ConvertHeaderBytes(ipc_msg_hdr *hdr);

struct CompileTimeAssertionChecks_dnssd_ipc
{
    // Check that the compiler generated our on-the-wire packet format structure definitions
    // properly packed, without adding padding bytes to align fields on 32-bit or 64-bit boundaries.
    char assert0[(sizeof(client_context_t) ==  8) ? 1 : -1];
    char assert1[(sizeof(ipc_msg_hdr)      == 28) ? 1 : -1];
};

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

#include <stdio.h>

#if defined(WIN32) || defined(EFI32) || defined(EFI64) || defined(EFIX64)
// Need to add Windows/EFI syslog support here
#define LOG_PID 0x01
#define LOG_CONS 0x02
#define LOG_PERROR 0x20
#else
#include <syslog.h>
#endif

#include "mDNSEmbeddedAPI.h"

mDNSexport int mDNS_LoggingEnabled       = 0;
mDNSexport int mDNS_PacketLoggingEnabled = 0;
mDNSexport int mDNS_McastLoggingEnabled  = 0;
mDNSexport int mDNS_McastTracingEnabled  = 0;

#if MDNS_DEBUGMSGS
mDNSexport int mDNS_DebugMode = mDNStrue;
#else
mDNSexport int mDNS_DebugMode = mDNSfalse;
#endif

// Note, this uses mDNS_vsnprintf instead of standard "vsnprintf", because mDNS_vsnprintf knows
// how to print special data types like IP addresses and length-prefixed domain names
#if MDNS_DEBUGMSGS > 1
mDNSexport void verbosedebugf_(const char *format, ...)
{
    char buffer[512];
    va_list args;
    va_start(args, format);
    buffer[mDNS_vsnprintf(buffer, sizeof(buffer), format, args)] = 0;
    va_end(args);
    mDNSPlatformWriteDebugMsg(buffer);
}
#endif

// Log message with default "mDNSResponder" ident string at the start
#if MDNSRESPONDER_SUPPORTS(APPLE, OS_LOG)
mDNSlocal void LogMsgWithLevelv(os_log_t category, os_log_type_t level, const char *format, va_list args)
{
    char buffer[512];
    mDNS_vsnprintf(buffer, (mDNSu32)sizeof(buffer), format, args);
    os_log_with_type(category ? category : mDNSLogCategory_Default, level, "%{private}s", buffer);
}
#else
mDNSlocal void LogMsgWithLevelv(const char *category, mDNSLogLevel_t level, const char *format, va_list args)
{
    char buffer[512];
    char *dst = buffer;
    const char *const lim = &buffer[512];
    if (category) mDNS_snprintf_add(&dst, lim, "%s: ", category);
    mDNS_vsnprintf(dst, (mDNSu32)(lim - dst), format, args);
    mDNSPlatformWriteLogMsg(ProgramName, buffer, level);
}
#endif

#define LOG_HELPER_BODY(CATEGORY, LEVEL) \
    { \
        va_list args; \
        va_start(args,format); \
        LogMsgWithLevelv(CATEGORY, LEVEL, format, args); \
        va_end(args); \
    }

// see mDNSDebug.h
#if !MDNS_HAS_VA_ARG_MACROS
void LogMsg_(const char *format, ...)       LOG_HELPER_BODY(NULL, MDNS_LOG_INFO)
void LogOperation_(const char *format, ...) LOG_HELPER_BODY(NULL, MDNS_LOG_INFO)
void LogSPS_(const char *format, ...)       LOG_HELPER_BODY(NULL, MDNS_LOG_INFO)
void LogInfo_(const char *format, ...)      LOG_HELPER_BODY(NULL, MDNS_LOG_INFO)
void LogDebug_(const char *format, ...)     LOG_HELPER_BODY(NULL, MDNS_LOG_DEBUG)
#endif

#if MDNS_DEBUGMSGS
void debugf_(const char *format, ...)       LOG_HELPER_BODY(MDNS_LOG_DEBUG)
#endif

// Log message with default "mDNSResponder" ident string at the start
mDNSexport void LogMsgWithLevel(mDNSLogCategory_t category, mDNSLogLevel_t level, const char *format, ...)
LOG_HELPER_BODY(category, level)

mDNSexport void LogToFD(int fd, const char *format, ...)
{
    va_list args;
    va_start(args, format);
#if APPLE_OSX_mDNSResponder
    char buffer[1024];
    buffer[mDNS_vsnprintf(buffer, (mDNSu32)sizeof(buffer), format, args)] = '\0';
    dprintf(fd, "%s\n", buffer);
#else
    (void)fd;
    LogMsgWithLevelv(NULL, MDNS_LOG_INFO, format, args);
#endif
    va_end(args);
}
/*
 * Copyright (c) 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.
 */

#ifndef __mDNSFeatures_h
#define __mDNSFeatures_h

#if MDNSRESPONDER_PLATFORM_APPLE
#include "ApplePlatformFeatures.h"
#endif

// Common Features

#undef MDNSRESPONDER_PLATFORM_COMMON
#define MDNSRESPONDER_PLATFORM_COMMON       1

// Feature: DNS Push
// Radar:   <rdar://problem/23226275>
// Enabled: Yes, for Apple.

#if !defined(MDNSRESPONDER_SUPPORTS_COMMON_DNS_PUSH)
    #if defined(MDNSRESPONDER_PLATFORM_APPLE) && MDNSRESPONDER_PLATFORM_APPLE
        #define MDNSRESPONDER_SUPPORTS_COMMON_DNS_PUSH      1
    #else
        #define MDNSRESPONDER_SUPPORTS_COMMON_DNS_PUSH      0
    #endif
#endif

#define HAS_FEATURE_CAT(A, B)       A ## B
#define HAS_FEATURE_CHECK_0         1
#define HAS_FEATURE_CHECK_1         1
#define HAS_FEATURE(X)              ((X) / HAS_FEATURE_CAT(HAS_FEATURE_CHECK_, X))

#define MDNSRESPONDER_SUPPORTS(PLATFORM, FEATURE) \
    (defined(MDNSRESPONDER_PLATFORM_ ## PLATFORM) && MDNSRESPONDER_PLATFORM_ ## PLATFORM && \
    HAS_FEATURE(MDNSRESPONDER_SUPPORTS_ ## PLATFORM ## _ ## FEATURE))

#endif  // __mDNSFeatures_h
/*
 * Copyright (c) 2003-2020 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.
 */

#if defined(_WIN32)
#include <process.h>
#define usleep(X) Sleep(((X)+999)/1000)
#else
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#endif

#include <stdlib.h>
#include <stdio.h>

#include "mDNSEmbeddedAPI.h"
#include "DNSCommon.h"
#include "uDNS.h"
#include "uds_daemon.h"
#include "dns_sd_internal.h"

// Apple-specific functionality, not required for other platforms
#if APPLE_OSX_mDNSResponder
#include <os/log.h>
#include <sys/ucred.h>
#ifndef PID_FILE
#define NO_PID_FILE // We need to signal that this platform has no PID file, and not just that we are taking the default
#endif
#endif

#ifdef LOCAL_PEEREPID
#include <sys/un.h>         // for LOCAL_PEEREPID
#include <sys/socket.h>     // for getsockopt
#include <sys/proc_info.h>  // for struct proc_bsdshortinfo
#include <libproc.h>        // for proc_pidinfo()
#endif //LOCAL_PEEREPID

#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
#include "D2D.h"
#endif

#if APPLE_OSX_mDNSResponder
#include "BLE.h"
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
#include "mDNSMacOSX.h"
#include <os/feature_private.h>
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
#include <bsm/libbsm.h>
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
#include "QuerierSupport.h"
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) && MDNSRESPONDER_SUPPORTS(APPLE, IPC_TLV)
#include "mdns_tlv.h"
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
#include "dnssec_v2.h"
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, DNSSD_XPC_SERVICE)
#include "dnssd_server.h"
#endif

// User IDs 0-500 are system-wide processes, not actual users in the usual sense
// User IDs for real user accounts start at 501 and count up from there
#define SystemUID(X) ((X) <= 500)

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - Globals
#endif

// globals
mDNSexport mDNS mDNSStorage;
mDNSexport const char ProgramName[] = "mDNSResponder";

#if defined(USE_TCP_LOOPBACK)
static char* boundPath = NULL;
#else
static char* boundPath = MDNS_UDS_SERVERPATH;
#endif
#if DEBUG
#define MDNS_UDS_SERVERPATH_DEBUG "/var/tmp/mDNSResponder"
#endif
static dnssd_sock_t listenfd = dnssd_InvalidSocket;
static request_state *all_requests = NULL;
#ifdef LOCAL_PEEREPID
struct proc_bsdshortinfo proc;
#endif //LOCAL_PEEREPID
mDNSlocal void set_peer_pid(request_state *request);
mDNSlocal void LogMcastClientInfo(request_state *req);
mDNSlocal void GetMcastClients(request_state *req);
static mDNSu32 mcount;     // tracks the current active mcast operations for McastLogging
static mDNSu32 i_mcount;   // sets mcount when McastLogging is enabled(PROF signal is sent)
static mDNSu32 n_mrecords; // tracks the current active mcast records for McastLogging
static mDNSu32 n_mquests;  // tracks the current active mcast questions for McastLogging


#if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
mDNSu32 curr_num_regservices = 0;
mDNSu32 max_num_regservices = 0;
#endif

// Note asymmetry here between registration and browsing.
// For service registrations we only automatically register in domains that explicitly appear in local configuration data
// (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
// For service browsing we also learn automatic browsing domains from the network, so for that case we have:
// 1. SCPrefBrowseDomains (local configuration data)
// 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
// 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
// By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.

mDNSexport DNameListElem *AutoRegistrationDomains;  // Domains where we automatically register for empty-string registrations

static DNameListElem *SCPrefBrowseDomains;          // List of automatic browsing domains read from SCPreferences for "empty string" browsing
static ARListElem    *LocalDomainEnumRecords;       // List of locally-generated PTR records to augment those we learn from the network
mDNSexport DNameListElem *AutoBrowseDomains;        // List created from those local-only PTR records plus records we get from the network

#define MSG_PAD_BYTES 5     // pad message buffer (read from client) with n zero'd bytes to guarantee
                            // n get_string() calls w/o buffer overrun
// initialization, setup/teardown functions

// If a platform specifies its own PID file name, we use that
#ifndef PID_FILE
#define PID_FILE "/var/run/mDNSResponder.pid"
#endif

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - General Utility Functions
#endif

mDNSlocal mDNSu32 GetNewRequestID(void)
{
#if MDNSRESPONDER_SUPPORTS(APPLE, DNSSD_XPC_SERVICE)
    return dnssd_server_get_new_request_id();
#else
    static mDNSu32 s_last_id = 0;
    return ++s_last_id;
#endif
}

mDNSlocal void FatalError(char *errmsg)
{
    LogMsg("%s: %s", errmsg, dnssd_strerror(dnssd_errno));
    abort();
}

mDNSlocal mDNSu32 dnssd_htonl(mDNSu32 l)
{
    mDNSu32 ret;
    char *data = (char*) &ret;
    put_uint32(l, &data);
    return ret;
}

// hack to search-replace perror's to LogMsg's
mDNSlocal void my_perror(char *errmsg)
{
    LogMsg("%s: %d (%s)", errmsg, dnssd_errno, dnssd_strerror(dnssd_errno));
}

// Throttled version of my_perror: Logs once every 250 msgs
mDNSlocal void my_throttled_perror(char *err_msg)
{
    static int uds_throttle_count = 0;
    if ((uds_throttle_count++ % 250) == 0)
        my_perror(err_msg);
}

// LogMcastQuestion/LogMcastQ should be called after the DNSQuestion struct is initialized(especially for q->TargetQID)
// Hence all calls are made after mDNS_StartQuery()/mDNS_StopQuery()/mDNS_StopBrowse() is called.
mDNSlocal void LogMcastQuestion(const DNSQuestion *const q, request_state *req, q_state status)
{
    if (mDNSOpaque16IsZero(q->TargetQID)) // Check for Mcast Query
    {
        mDNSBool mflag = mDNSfalse;
        if (status == q_start)
        {
            if (++mcount == 1)
                mflag = mDNStrue;
        }
        else
        {
            mcount--;
        }
        LogMcast("%s: %##s  (%s) (%s)  Client(%d)[%s]", status ? "+Question" : "-Question", q->qname.c, DNSTypeName(q->qtype),
                 q->InterfaceID == mDNSInterface_LocalOnly ? "lo" :
                 q->InterfaceID == mDNSInterface_P2P ? "p2p" :
                 q->InterfaceID == mDNSInterface_BLE ? "BLE" :
                 q->InterfaceID == mDNSInterface_Any ? "any" : InterfaceNameForID(&mDNSStorage, q->InterfaceID),
                 req->process_id, req->pid_name);
        LogMcastStateInfo(mflag, mDNSfalse, mDNSfalse);
    }
    return;
}

// LogMcastService/LogMcastS should be called after the AuthRecord struct is initialized
// Hence all calls are made after mDNS_Register()/ just before mDNS_Deregister()
mDNSlocal void LogMcastService(const AuthRecord *const ar, request_state *req, reg_state status)
{
    if (!AuthRecord_uDNS(ar)) // Check for Mcast Service
    {
        mDNSBool mflag = mDNSfalse;
        if (status == reg_start)
        {
            if (++mcount == 1)
                mflag = mDNStrue;
        }
        else
        {
            mcount--;
        }
        LogMcast("%s: %##s  (%s)  (%s)  Client(%d)[%s]", status ? "+Service" : "-Service", ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype),
                 ar->resrec.InterfaceID == mDNSInterface_LocalOnly ? "lo" :
                 ar->resrec.InterfaceID == mDNSInterface_P2P ? "p2p" :
                 ar->resrec.InterfaceID == mDNSInterface_BLE ? "BLE" :
                 ar->resrec.InterfaceID == mDNSInterface_Any ? "all" : InterfaceNameForID(&mDNSStorage, ar->resrec.InterfaceID),
                 req->process_id, req->pid_name);
        LogMcastStateInfo(mflag, mDNSfalse, mDNSfalse);
    }
    return;
}

// For complete Mcast State Log, pass mDNStrue to mstatelog in LogMcastStateInfo()
mDNSexport void LogMcastStateInfo(mDNSBool mflag, mDNSBool start, mDNSBool mstatelog)
{
    mDNS *const m = &mDNSStorage;
    if (!mstatelog)
    {
        if (!all_requests)
        {
            LogMcastNoIdent("<None>");
        }
        else
        {
            request_state *req, *r;
            for (req = all_requests; req; req=req->next)
            {
                if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
                {
                    for (r = all_requests; r && r != req; r=r->next)
                        if (r == req->primary)
                            goto foundpar;
                }
                // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
                GetMcastClients(req);
    foundpar:;
            }
            LogMcastNoIdent("--- MCAST RECORDS COUNT[%d] MCAST QUESTIONS COUNT[%d] ---", n_mrecords, n_mquests);
            n_mrecords = n_mquests = 0; // Reset the values
        }
    }
    else
    {
        static mDNSu32 i_mpktnum;
        i_mcount = 0;
        if (start)
            mcount = 0;
        // mcount is initialized to 0 when the PROF signal is sent since mcount could have
        // wrong value if MulticastLogging is disabled and then re-enabled
        LogMcastNoIdent("--- START MCAST STATE LOG ---");
        if (!all_requests)
        {
            mcount = 0;
            LogMcastNoIdent("<None>");
        }
        else
        {
            request_state *req, *r;
            for (req = all_requests; req; req=req->next)
            {
                if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
                {
                    for (r = all_requests; r && r != req; r=r->next)
                        if (r == req->primary)
                            goto foundparent;
                    LogMcastNoIdent("%3d: Orphan operation; parent not found in request list", req->sd);
                }
                // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
                LogMcastClientInfo(req);
    foundparent:;
            }
            if(!mcount) // To initially set mcount
                mcount = i_mcount;
        }
        if (mcount == 0)
        {
            i_mpktnum = m->MPktNum;
            LogMcastNoIdent("--- MCOUNT[%d]: IMPKTNUM[%d] ---", mcount, i_mpktnum);
        }
        if (mflag)
            LogMcastNoIdent("--- MCOUNT[%d]: CMPKTNUM[%d] - IMPKTNUM[%d] = [%d]PKTS ---", mcount, m->MPktNum, i_mpktnum, (m->MPktNum - i_mpktnum));
        LogMcastNoIdent("--- END MCAST STATE LOG ---");
    }
}

mDNSlocal void abort_request(request_state *req)
{
    if (req->terminate == (req_termination_fn) ~0)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
                  "[R%d] abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req->request_id, req, req->terminate);
        return;
    }

    // First stop whatever mDNSCore operation we were doing
    // If this is actually a shared connection operation, then its req->terminate function will scan
    // the all_requests list and terminate any subbordinate operations sharing this file descriptor
    if (req->terminate) req->terminate(req);
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    if (req->custom_service_id != 0)
    {
        Querier_DeregisterCustomDNSService(req->custom_service_id);
        req->custom_service_id = 0;
    }
#endif

    if (!dnssd_SocketValid(req->sd))
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
                  "[R%d] abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req->request_id, req, req->sd);
        return;
    }

    // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
    if (!req->primary)
    {
        if (req->errsd != req->sd)
        {
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
                      "[R%d] Removing FD %d and closing errsd %d", req->request_id, req->sd, req->errsd);
        }
        else
        {
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
                      "[R%d] Removing FD %d", req->request_id, req->sd);
        }
        udsSupportRemoveFDFromEventLoop(req->sd, req->platform_data);       // Note: This also closes file descriptor req->sd for us
        if (req->errsd != req->sd) { dnssd_close(req->errsd); req->errsd = req->sd; }

        while (req->replies)    // free pending replies
        {
            reply_state *ptr = req->replies;
            req->replies = req->replies->next;
            freeL("reply_state (abort)", ptr);
        }
    }

    // Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
#if MDNS_MALLOC_DEBUGGING
    // Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MDNS_MALLOC_DEBUGGING uses
    // for detecting when the memory for an object is inadvertently freed while the object is still on some list
#ifdef WIN32
#error This will not work on Windows, look at IsValidSocket in mDNSShared/CommonServices.h to see why
#endif
    req->sd = req->errsd = -2;
#else
    req->sd = req->errsd = dnssd_InvalidSocket;
#endif
    // We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
    req->terminate = (req_termination_fn) ~0;
}

#if DEBUG
mDNSexport void SetDebugBoundPath(void)
{
#if !defined(USE_TCP_LOOPBACK)
    boundPath = MDNS_UDS_SERVERPATH_DEBUG;
#endif
}

mDNSexport int IsDebugSocketInUse(void)
{
#if !defined(USE_TCP_LOOPBACK)
    return !strcmp(boundPath, MDNS_UDS_SERVERPATH_DEBUG);
#else
    return mDNSfalse;
#endif
}
#endif

mDNSlocal void AbortUnlinkAndFree(request_state *req)
{
    request_state **p = &all_requests;
    abort_request(req);
    while (*p && *p != req) p=&(*p)->next;
    if (*p)
    {
        *p = req->next;
#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
        if (req->trust)
        {
            void * context = mdns_trust_get_context(req->trust);
            mdns_trust_set_context(req->trust, NULL);
            if (context) freeL("context/AbortUnlinkAndFree", context);
            mdns_trust_forget(&req->trust);
        }
#endif
        freeL("request_state/AbortUnlinkAndFree", req);
    }
    else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req);
}

mDNSlocal reply_state *create_reply(const reply_op_t op, const size_t datalen, request_state *const request)
{
    reply_state *reply;

    if ((unsigned)datalen < sizeof(reply_hdr))
    {
        LogMsg("ERROR: create_reply - data length less than length of required fields");
        return NULL;
    }

    reply = (reply_state *) callocL("reply_state", sizeof(reply_state) + datalen - sizeof(reply_hdr));
    if (!reply) FatalError("ERROR: calloc");

    reply->next     = mDNSNULL;
    reply->totallen = (mDNSu32)datalen + sizeof(ipc_msg_hdr);
    reply->nwriten  = 0;

    reply->mhdr->version        = VERSION;
    reply->mhdr->datalen        = (mDNSu32)datalen;
    reply->mhdr->ipc_flags      = 0;
    reply->mhdr->op             = op;
    reply->mhdr->client_context = request->hdr.client_context;
    reply->mhdr->reg_index      = 0;

    return reply;
}

// Append a reply to the list in a request object
// If our request is sharing a connection, then we append our reply_state onto the primary's list
// If the request does not want asynchronous replies, then the reply is freed instead of being appended to any list.
mDNSlocal void append_reply(request_state *req, reply_state *rep)
{
    request_state *r;
    reply_state **ptr;

    if (req->no_reply)
    {
        freeL("reply_state/append_reply", rep);
        return;
    }

    r = req->primary ? req->primary : req;
    ptr = &r->replies;
    while (*ptr) ptr = &(*ptr)->next;
    *ptr = rep;
    rep->next = NULL;
}

// Generates a response message giving name, type, domain, plus interface index,
// suitable for a browse result or service registration result.
// On successful completion rep is set to point to a malloc'd reply_state struct
mDNSlocal mStatus GenerateNTDResponse(const domainname *const servicename, const mDNSInterfaceID id,
                                      request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
{
    domainlabel name;
    domainname type, dom;
    *rep = NULL;
    if (servicename && !DeconstructServiceName(servicename, &name, &type, &dom))
        return kDNSServiceErr_Invalid;
    else
    {
        char namestr[MAX_DOMAIN_LABEL+1];
        char typestr[MAX_ESCAPED_DOMAIN_NAME];
        char domstr [MAX_ESCAPED_DOMAIN_NAME];
        int len;
        char *data;

        if (servicename)
        {
            ConvertDomainLabelToCString_unescaped(&name, namestr);
            ConvertDomainNameToCString(&type, typestr);
            ConvertDomainNameToCString(&dom, domstr);
        }
        else
        {
            namestr[0] = 0;
            typestr[0] = 0;
            domstr[0] = 0;
        }

        // Calculate reply data length
        len = sizeof(DNSServiceFlags);
        len += sizeof(mDNSu32);  // if index
        len += sizeof(DNSServiceErrorType);
        len += (int) (strlen(namestr) + 1);
        len += (int) (strlen(typestr) + 1);
        len += (int) (strlen(domstr) + 1);

        // Build reply header
        *rep = create_reply(op, len, request);
        (*rep)->rhdr->flags = dnssd_htonl(flags);
        (*rep)->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
        (*rep)->rhdr->error = dnssd_htonl(err);

        // Build reply body
        data = (char *)&(*rep)->rhdr[1];
        put_string(namestr, &data);
        put_string(typestr, &data);
        put_string(domstr, &data);

        return mStatus_NoError;
    }
}

mDNSlocal void GenerateBrowseReply(const domainname *const servicename, const mDNSInterfaceID id,
                                              request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
{
    char namestr[MAX_DOMAIN_LABEL+1];
    char typestr[MAX_ESCAPED_DOMAIN_NAME];
    static const char domstr[] = ".";
    int len;
    char *data;

    *rep = NULL;

    if (servicename)
    {
        // 1. Put first label in namestr
        ConvertDomainLabelToCString_unescaped((const domainlabel *)servicename, namestr);

        // 2. Put second label and "local" into typestr
        mDNS_snprintf(typestr, sizeof(typestr), "%#s.local.", SecondLabel(servicename));
    }
    else
    {
        namestr[0] = 0;
        typestr[0] = 0;
    }

    // Calculate reply data length
    len = sizeof(DNSServiceFlags);
    len += sizeof(mDNSu32);  // if index
    len += sizeof(DNSServiceErrorType);
    len += (int) (strlen(namestr) + 1);
    len += (int) (strlen(typestr) + 1);
    len += (int) (strlen(domstr) + 1);

    // Build reply header
    *rep = create_reply(op, len, request);
    (*rep)->rhdr->flags = dnssd_htonl(flags);
    (*rep)->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
    (*rep)->rhdr->error = dnssd_htonl(err);

    // Build reply body
    data = (char *)&(*rep)->rhdr[1];
    put_string(namestr, &data);
    put_string(typestr, &data);
    put_string(domstr, &data);
}

// Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
// Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
// (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
mDNSlocal AuthRecord *read_rr_from_ipc_msg(request_state *request, int GetTTL, int validate_flags)
{
    DNSServiceFlags flags  = get_flags(&request->msgptr, request->msgend);
    mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
    char name[MAX_ESCAPED_DOMAIN_NAME];
    int str_err = get_string(&request->msgptr, request->msgend, name, sizeof(name));
    mDNSu16 type    = get_uint16(&request->msgptr, request->msgend);
    mDNSu16     class   = get_uint16(&request->msgptr, request->msgend);
    mDNSu16 rdlen   = get_uint16(&request->msgptr, request->msgend);
    const mDNSu8 *const rdata = (const mDNSu8 *)get_rdata (&request->msgptr, request->msgend, rdlen);
    mDNSu32 ttl   = GetTTL ? get_uint32(&request->msgptr, request->msgend) : 0;
    size_t rdcapacity;
    AuthRecord *rr;
    mDNSInterfaceID InterfaceID;
    AuthRecType artype;
    mDNSu8 recordType;

    request->flags = flags;
    request->interfaceIndex = interfaceIndex;

    if (str_err) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL; }

    if (!request->msgptr) { LogMsg("Error reading Resource Record from client"); return NULL; }

    if (validate_flags &&
        !((flags & kDNSServiceFlagsShared) == kDNSServiceFlagsShared) &&
        !((flags & kDNSServiceFlagsUnique) == kDNSServiceFlagsUnique) &&
        !((flags & kDNSServiceFlagsKnownUnique) == kDNSServiceFlagsKnownUnique))
    {
        LogMsg("ERROR: Bad resource record flags (must be one of either kDNSServiceFlagsShared, kDNSServiceFlagsUnique or kDNSServiceFlagsKnownUnique)");
        return NULL;
    }
    InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);

    // The registration is scoped to a specific interface index, but the interface is not currently on our list.
    if ((InterfaceID == mDNSInterface_Any) && (interfaceIndex != kDNSServiceInterfaceIndexAny))
    {
        // On Apple platforms, an interface's mDNSInterfaceID is equal to its index. Using an interface index that isn't
        // currently valid will cause the registration to take place as soon as it becomes valid. On other platforms,
        // mDNSInterfaceID is actually a pointer to a platform-specific interface object, but we don't know what the pointer
        // for the interface index will be ahead of time. For now, just return NULL to indicate an error condition since the
        // interface index is invalid. Otherwise, the registration would be performed on all interfaces.
#if APPLE_OSX_mDNSResponder
        InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
#else
        return NULL;
#endif
    }
    rdcapacity = (rdlen > sizeof(RDataBody2)) ? rdlen : sizeof(RDataBody2);
    rr = (AuthRecord *) callocL("AuthRecord/read_rr_from_ipc_msg", sizeof(*rr) - sizeof(RDataBody) + rdcapacity);
    if (!rr) FatalError("ERROR: calloc");

    if (InterfaceID == mDNSInterface_LocalOnly)
        artype = AuthRecordLocalOnly;
    else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
        artype = AuthRecordP2P;
    else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
            && (flags & kDNSServiceFlagsIncludeAWDL))
        artype = AuthRecordAnyIncludeAWDLandP2P;
    else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
        artype = AuthRecordAnyIncludeP2P;
    else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
        artype = AuthRecordAnyIncludeAWDL;
    else
        artype = AuthRecordAny;

    if (flags & kDNSServiceFlagsShared)
        recordType = (mDNSu8) kDNSRecordTypeShared;
    else if (flags & kDNSServiceFlagsKnownUnique)
        recordType = (mDNSu8) kDNSRecordTypeKnownUnique;
    else
        recordType = (mDNSu8) kDNSRecordTypeUnique;

    mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, type, 0, recordType, artype, mDNSNULL, mDNSNULL);

    if (!MakeDomainNameFromDNSNameString(&rr->namestorage, name))
    {
        LogMsg("ERROR: bad name: %s", name);
        freeL("AuthRecord/read_rr_from_ipc_msg", rr);
        return NULL;
    }

    if (flags & kDNSServiceFlagsAllowRemoteQuery) rr->AllowRemoteQuery = mDNStrue;
    rr->resrec.rrclass = class;
    rr->resrec.rdlength = rdlen;
    rr->resrec.rdata->MaxRDLength = (mDNSu16)rdcapacity;
    if (!SetRData(mDNSNULL, rdata, rdata + rdlen, &rr->resrec, rdlen))
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
            "[R%u] read_rr_from_ipc_msg: SetRData failed for " PRI_DM_NAME " (" PUB_S ")",
            request->request_id, DM_NAME_PARAM(rr->resrec.name), DNSTypeName(type));
        freeL("AuthRecord/read_rr_from_ipc_msg", rr);
        return NULL;
    }
    if (GetTTL) rr->resrec.rroriginalttl = ttl;
    rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
    SetNewRData(&rr->resrec, mDNSNULL, 0);  // Sets rr->rdatahash for us
    return rr;
}

mDNSlocal int build_domainname_from_strings(domainname *srv, char *name, char *regtype, char *domain)
{
    domainlabel n;
    domainname d, t;

    if (!MakeDomainLabelFromLiteralString(&n, name)) return -1;
    if (!MakeDomainNameFromDNSNameString(&t, regtype)) return -1;
    if (!MakeDomainNameFromDNSNameString(&d, domain)) return -1;
    if (!ConstructServiceName(srv, &n, &t, &d)) return -1;
    return 0;
}

mDNSlocal void send_all(dnssd_sock_t s, const char *ptr, int len)
{
    const ssize_t n = send(s, ptr, len, 0);
    // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
    // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
    // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
    if (n < len)
    {
        LogMsg("ERROR: send_all(%d) wrote %ld of %d errno %d (%s)",
            s, (long)n, len, dnssd_errno, dnssd_strerror(dnssd_errno));
    }
}

#if 0
mDNSlocal mDNSBool AuthorizedDomain(const request_state * const request, const domainname * const d, const DNameListElem * const doms)
{
    const DNameListElem   *delem = mDNSNULL;
    int bestDelta   = -1;                           // the delta of the best match, lower is better
    int dLabels     = 0;
    mDNSBool allow       = mDNSfalse;

    if (SystemUID(request->uid)) return mDNStrue;

    dLabels = CountLabels(d);
    for (delem = doms; delem; delem = delem->next)
    {
        if (delem->uid)
        {
            int delemLabels = CountLabels(&delem->name);
            int delta       = dLabels - delemLabels;
            if ((bestDelta == -1 || delta <= bestDelta) && SameDomainName(&delem->name, SkipLeadingLabels(d, delta)))
            {
                bestDelta = delta;
                allow = (allow || (delem->uid == request->uid));
            }
        }
    }

    return bestDelta == -1 ? mDNStrue : allow;
}
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
mDNSlocal void SetupAuditTokenForRequest(request_state *request)
{

    pid_t audit_pid = audit_token_to_pid(request->audit_token);
    if (audit_pid == 0)
    {
#if !defined(LOCAL_PEERTOKEN)
#define LOCAL_PEERTOKEN         0x006           /* retrieve peer audit token */
#endif
        socklen_t len = sizeof(audit_token_t);
        int ret = getsockopt(request->sd, SOL_LOCAL, LOCAL_PEERTOKEN, &request->audit_token, &len);
        if (ret != 0)
        {
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                      "SetupAuditTokenForRequest: No audit_token using LOCAL_PEERTOKEN (%s PID %d) for op %d ret(%d)",
                      request->pid_name, request->process_id, request->hdr.op, ret);
        }
    }
}
#endif

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - external helpers
#endif

#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
mDNSlocal void external_start_advertising_helper(service_instance *const instance)
{
    AuthRecord *st = instance->subtypes;
    ExtraResourceRecord *e;
    int i;
    const pid_t requestPID = instance->request->process_id;

    if (mDNSIPPortIsZero(instance->request->u.servicereg.port))
    {
        LogInfo("external_start_advertising_helper: Not registering service with port number zero");
        return;
    }

    if (instance->external_advertise) LogMsg("external_start_advertising_helper: external_advertise already set!");

    for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
        external_start_advertising_service(&st[i].resrec, instance->request->flags, requestPID);

    external_start_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags, requestPID);
    external_start_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags, requestPID);
    external_start_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags, requestPID);

    for (e = instance->srs.Extras; e; e = e->next)
        external_start_advertising_service(&e->r.resrec, instance->request->flags, requestPID);

    instance->external_advertise = mDNStrue;
}

mDNSlocal void external_stop_advertising_helper(service_instance *const instance)
{
    AuthRecord *st = instance->subtypes;
    ExtraResourceRecord *e;
    int i;

    if (!instance->external_advertise) return;

    LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");

    if (instance->request)
    {
        const pid_t requestPID = instance->request->process_id;
        for (i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
        {
            external_stop_advertising_service(&st[i].resrec, instance->request->flags, requestPID);
        }

        external_stop_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags, requestPID);
        external_stop_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags, requestPID);
        external_stop_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags, requestPID);

        for (e = instance->srs.Extras; e; e = e->next)
        {
            external_stop_advertising_service(&e->r.resrec, instance->request->flags, requestPID);
        }
    }

    instance->external_advertise = mDNSfalse;
}
#endif  // MDNSRESPONDER_SUPPORTS(APPLE, D2D)

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
mDNSlocal dispatch_queue_t _get_trust_results_dispatch_queue(void)
{
    static dispatch_once_t  once    = 0;
    static dispatch_queue_t queue   = NULL;

    dispatch_once(&once, ^{
        dispatch_queue_attr_t const attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0);
        queue = dispatch_queue_create("com.apple.mDNSResponder.trust_results-queue", attr);
    });
    return queue;
}
#endif

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceRegister
#endif

mDNSexport void FreeExtraRR(mDNS *const m, AuthRecord *const rr, mStatus result)
{
    ExtraResourceRecord *extra = (ExtraResourceRecord *)rr->RecordContext;
    (void)m;  // Unused

    if (result != mStatus_MemFree) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result); return; }

    LogInfo("     FreeExtraRR %s", RRDisplayString(m, &rr->resrec));

    if (rr->resrec.rdata != &rr->rdatastorage)
        freeL("Extra RData", rr->resrec.rdata);
    freeL("ExtraResourceRecord/FreeExtraRR", extra);
}

mDNSlocal void unlink_and_free_service_instance(service_instance *srv)
{
    ExtraResourceRecord *e = srv->srs.Extras, *tmp;

#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
    external_stop_advertising_helper(srv);
#endif

    // clear pointers from parent struct
    if (srv->request)
    {
        service_instance **p = &srv->request->u.servicereg.instances;
        while (*p)
        {
            if (*p == srv) { *p = (*p)->next; break; }
            p = &(*p)->next;
        }
    }

    while (e)
    {
        e->r.RecordContext = e;
        tmp = e;
        e = e->next;
        FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree);
    }

    if (srv->srs.RR_TXT.resrec.rdata != &srv->srs.RR_TXT.rdatastorage)
        freeL("TXT RData", srv->srs.RR_TXT.resrec.rdata);

    if (srv->subtypes)
    {
        freeL("ServiceSubTypes", srv->subtypes);
        srv->subtypes = NULL;
    }
    freeL("service_instance", srv);
}

// Count how many other service records we have locally with the same name, but different rdata.
// For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
// the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
mDNSexport int CountPeerRegistrations(ServiceRecordSet *const srs)
{
    int count = 0;
    ResourceRecord *r = &srs->RR_SRV.resrec;
    AuthRecord *rr;

    for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
        if (rr->resrec.rrtype == kDNSType_SRV && SameDomainName(rr->resrec.name, r->name) && !IdenticalSameNameRecord(&rr->resrec, r))
            count++;

    verbosedebugf("%d peer registrations for %##s", count, r->name->c);
    return(count);
}

mDNSexport int CountExistingRegistrations(domainname *srv, mDNSIPPort port)
{
    int count = 0;
    AuthRecord *rr;
    for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
        if (rr->resrec.rrtype == kDNSType_SRV &&
            mDNSSameIPPort(rr->resrec.rdata->u.srv.port, port) &&
            SameDomainName(rr->resrec.name, srv))
            count++;
    return(count);
}

mDNSlocal void SendServiceRemovalNotification(ServiceRecordSet *const srs)
{
    reply_state *rep;
    service_instance *instance = srs->ServiceContext;
    if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, 0, mStatus_NoError) != mStatus_NoError)
        LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
    else { append_reply(instance->request, rep); instance->clientnotified = mDNSfalse; }
}

// service registration callback performs three duties - frees memory for deregistered services,
// handles name conflicts, and delivers completed registration information to the client
mDNSlocal void regservice_callback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
{
    mStatus err;
    mDNSBool SuppressError = mDNSfalse;
    service_instance *instance;
    reply_state         *rep;
    (void)m; // Unused

    if (!srs)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "regservice_callback: srs is NULL %d", result);
        return;
    }

    instance = srs->ServiceContext;
    if (!instance)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "regservice_callback: srs->ServiceContext is NULL %d", result);
        return;
    }

    // don't send errors up to client for wide-area, empty-string registrations
    if (instance->request &&
        instance->request->u.servicereg.default_domain &&
        !instance->default_local)
        SuppressError = mDNStrue;

    if (mDNS_LoggingEnabled)
    {
        const char *result_description;
        char description[32]; // 32-byte is enough for holding "suppressed error -2147483648\0"
        mDNSu32 request_id = instance->request ? instance->request->request_id : 0;
        switch (result) {
            case mStatus_NoError:
                result_description = "REGISTERED";
                break;
            case mStatus_MemFree:
                result_description = "DEREGISTERED";
                break;
            case mStatus_NameConflict:
                result_description = "NAME CONFLICT";
                break;
            default:
                mDNS_snprintf(description, sizeof(description), "%s %d", SuppressError ? "suppressed error" : "CALLBACK", result);
                result_description = description;
                break;
        }
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[R%u] DNSServiceRegister(" PRI_DM_NAME ", %u) %s",
                  request_id, DM_NAME_PARAM(srs->RR_SRV.resrec.name), mDNSVal16(srs->RR_SRV.resrec.rdata->u.srv.port), result_description);
    }

    if (!instance->request && result != mStatus_MemFree)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "regservice_callback: instance->request is NULL %d", result);
        return;
    }

    if (result == mStatus_NoError)
    {
        if (instance->request->u.servicereg.allowremotequery)
        {
            ExtraResourceRecord *e;
            srs->RR_ADV.AllowRemoteQuery = mDNStrue;
            srs->RR_PTR.AllowRemoteQuery = mDNStrue;
            srs->RR_SRV.AllowRemoteQuery = mDNStrue;
            srs->RR_TXT.AllowRemoteQuery = mDNStrue;
            for (e = instance->srs.Extras; e; e = e->next) e->r.AllowRemoteQuery = mDNStrue;
        }

        if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u] regservice_callback: " PRI_DM_NAME " is not valid DNS-SD SRV name", instance->request->request_id, DM_NAME_PARAM(srs->RR_SRV.resrec.name));
        else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }

#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
        if (callExternalHelpers(instance->request->u.servicereg.InterfaceID, &instance->domain, instance->request->flags))
        {
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[R%u] regservice_callback: calling external_start_advertising_helper()", instance->request->request_id);
            external_start_advertising_helper(instance);
        }
#endif
        if (instance->request->u.servicereg.autoname && CountPeerRegistrations(srs) == 0)
            RecordUpdatedNiceLabel(0);   // Successfully got new name, tell user immediately
    }
    else if (result == mStatus_MemFree)
    {
#if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
        curr_num_regservices--;
#endif
        if (instance->request && instance->renameonmemfree)
        {
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
            external_stop_advertising_helper(instance);
#endif
            instance->renameonmemfree = 0;
            err = mDNS_RenameAndReregisterService(m, srs, &instance->request->u.servicereg.name);
            if (err)
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u] ERROR: regservice_callback - RenameAndReregisterService returned %d", instance->request->request_id, err);
            // error should never happen - safest to log and continue
        }
        else
            unlink_and_free_service_instance(instance);
    }
    else if (result == mStatus_NameConflict)
    {
        if (instance->request->u.servicereg.autorename)
        {
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
            external_stop_advertising_helper(instance);
#endif
            if (instance->request->u.servicereg.autoname && CountPeerRegistrations(srs) == 0)
            {
                // On conflict for an autoname service, rename and reregister *all* autoname services
                IncrementLabelSuffix(&m->nicelabel, mDNStrue);
                mDNS_ConfigChanged(m);  // Will call back into udsserver_handle_configchange()
            }
            else    // On conflict for a non-autoname service, rename and reregister just that one service
            {
                if (instance->clientnotified) SendServiceRemovalNotification(srs);
                mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
            }
        }
        else
        {
            if (!SuppressError)
            {
                if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
                    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u] regservice_callback: " PRI_DM_NAME " is not valid DNS-SD SRV name", instance->request->request_id, DM_NAME_PARAM(srs->RR_SRV.resrec.name));
                else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
            }
            unlink_and_free_service_instance(instance);
        }
    }
    else        // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
    {
        if (!SuppressError)
        {
            if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u] regservice_callback: " PRI_DM_NAME " is not valid DNS-SD SRV name", instance->request->request_id, DM_NAME_PARAM(srs->RR_SRV.resrec.name));
            else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
        }
    }
}

mDNSlocal void regrecord_callback(mDNS *const m, AuthRecord *rr, mStatus result)
{
    (void)m; // Unused
    if (!rr->RecordContext)     // parent struct already freed by termination callback
    {
        if (result == mStatus_NoError)
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "Error: regrecord_callback: successful registration of orphaned record " PRI_S, ARDisplayString(m, rr));
        else
        {
            if (result != mStatus_MemFree)
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "regrecord_callback: error %d received after parent termination", result);

            // We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
            // If the record has been updated, we need to free the rdata. Every time we call mDNS_Update, it calls update_callback
            // with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
            // to free the latest rdata for which the update_callback was never called with.
            if (rr->resrec.rdata != &rr->rdatastorage) freeL("RData/regrecord_callback", rr->resrec.rdata);
            freeL("AuthRecord/regrecord_callback", rr);
        }
    }
    else
    {
        registered_record_entry *re = rr->RecordContext;
        request_state *request = re->request;

        if (mDNS_LoggingEnabled)
        {
            const char *result_description;
            char description[16]; // 16-byte is enough for holding -2147483648\0
            switch (result) {
                case mStatus_NoError:
                    result_description = "REGISTERED";
                    break;
                case mStatus_MemFree:
                    result_description = "DEREGISTERED";
                    break;
                case mStatus_NameConflict:
                    result_description = "NAME CONFLICT";
                    break;
                default:
                    mDNS_snprintf(description, sizeof(description), "%d", result);
                    result_description = description;
                    break;
            }

            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[R%u] DNSServiceRegisterRecord(%u " PRI_S ")" PUB_S,
                      request->request_id, re->key, RRDisplayString(m, &rr->resrec), result_description);
        }

        if (result != mStatus_MemFree)
        {
            int len = sizeof(DNSServiceFlags) + sizeof(mDNSu32) + sizeof(DNSServiceErrorType);
            reply_state *reply = create_reply(reg_record_reply_op, len, request);
            reply->mhdr->client_context = re->regrec_client_context;
            reply->rhdr->flags = dnssd_htonl(0);
            reply->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, rr->resrec.InterfaceID, mDNSfalse));
            reply->rhdr->error = dnssd_htonl(result);
            append_reply(request, reply);
        }

        if (result)
        {
            // If this is a callback to a keepalive record, do not free it.
            if (result == mStatus_BadStateErr)
            {
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
                          "[R%u] regrecord_callback: Callback with error code mStatus_BadStateErr - not freeing the record.", request->request_id);
            }
            else
            {
                // unlink from list, free memory
                registered_record_entry **ptr = &request->u.reg_recs;
                while (*ptr && (*ptr) != re) ptr = &(*ptr)->next;
                if (!*ptr)
                {
                    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
                              "[R%u] regrecord_callback - record not in list!", request->request_id);
                    return;
                }
                *ptr = (*ptr)->next;
                freeL("registered_record_entry AuthRecord regrecord_callback", re->rr);
                freeL("registered_record_entry regrecord_callback", re);
             }
        }
        else
        {
            if (re->external_advertise)
            {
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
                          "[R%u] regrecord_callback: external_advertise already set!", request->request_id);
            }

#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
            if (callExternalHelpers(re->origInterfaceID, &rr->namestorage, request->flags))
            {
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
                          "[R%u] regrecord_callback: calling external_start_advertising_service", request->request_id);
                external_start_advertising_service(&rr->resrec, request->flags, request->process_id);
                re->external_advertise = mDNStrue;
            }
#endif
        }
    }
}

// set_peer_pid() is called after mem is allocated for each new request in NewRequest()
// This accounts for 2 places (connect_callback, request_callback)
mDNSlocal void set_peer_pid(request_state *request)
{
    request->pid_name[0] = '\0';
    request->process_id  = -1;
#ifdef LOCAL_PEEREPID
    pid_t           p    = (pid_t) -1;
    socklen_t       len  = sizeof(p);
    if (request->sd < 0)
        return;
    // to extract the effective pid value
    if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREPID, &p, &len) != 0)
        return;
    // to extract the process name from the pid value
    if (proc_pidinfo(p, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
        return;
    mDNSPlatformStrLCopy(request->pid_name, proc.pbsi_comm, sizeof(request->pid_name));
    request->process_id = p;
    debugf("set_peer_pid: Client PEEREPID is %d %s", p, request->pid_name);
#else   // !LOCAL_PEEREPID
    LogInfo("set_peer_pid: Not Supported on this version of OS");
    if (request->sd < 0)
        return;
#endif  // LOCAL_PEEREPID
}

mDNSlocal void connection_termination(request_state *request)
{
    // When terminating a shared connection, we need to scan the all_requests list
    // and terminate any subbordinate operations sharing this file descriptor
    request_state **req = &all_requests;

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] DNSServiceCreateConnection STOP PID[%d](" PUB_S ")",
           request->request_id, request->process_id, request->pid_name);

    while (*req)
    {
        if ((*req)->primary == request)
        {
            // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
            request_state *tmp = *req;
            if (tmp->primary == tmp) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d",                  tmp, tmp->sd);
            if (tmp->replies) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp, tmp->sd);
            abort_request(tmp);
            *req = tmp->next;
#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
            if (tmp->trust)
            {
                void * context = mdns_trust_get_context(tmp->trust);
                mdns_trust_set_context(tmp->trust, NULL);
                if (context) freeL("context/connection_termination", context);
                mdns_trust_forget(&tmp->trust);
            }
#endif
            freeL("request_state/connection_termination", tmp);
        }
        else
            req = &(*req)->next;
    }

    while (request->u.reg_recs)
    {
        registered_record_entry *ptr = request->u.reg_recs;
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
               "[R%d] DNSServiceRegisterRecord(0x%X, %d, " PRI_S ") STOP PID[%d](" PUB_S ")",
               request->request_id, request->flags, request->interfaceIndex, RRDisplayString(&mDNSStorage, &ptr->rr->resrec), request->process_id,
               request->pid_name);
        request->u.reg_recs = request->u.reg_recs->next;
        ptr->rr->RecordContext = NULL;
        if (ptr->external_advertise)
        {
            ptr->external_advertise = mDNSfalse;
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
            external_stop_advertising_service(&ptr->rr->resrec, request->flags, request->process_id);
#endif
        }
        LogMcastS(ptr->rr, request, reg_stop);
        mDNS_Deregister(&mDNSStorage, ptr->rr);     // Will free ptr->rr for us
        freeL("registered_record_entry/connection_termination", ptr);
    }
}

mDNSlocal void handle_cancel_request(request_state *request)
{
    request_state **req = &all_requests;
    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "[R%d] Cancel %08X %08X",
           request->request_id, request->hdr.client_context.u32[1], request->hdr.client_context.u32[0]);
    while (*req)
    {
        if ((*req)->primary == request &&
            (*req)->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
            (*req)->hdr.client_context.u32[1] == request->hdr.client_context.u32[1])
        {
            // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
            request_state *tmp = *req;
            abort_request(tmp);
            *req = tmp->next;
#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
            if (tmp->trust)
            {
                void * context = mdns_trust_get_context(tmp->trust);
                mdns_trust_set_context(tmp->trust, NULL);
                if (context) freeL("context/handle_cancel_request", context);
                mdns_trust_forget(&tmp->trust);
            }
#endif
            freeL("request_state/handle_cancel_request", tmp);
        }
        else
            req = &(*req)->next;
    }
}

mDNSlocal mStatus _handle_regrecord_request_start(request_state *request, AuthRecord * rr)
{
    mStatus err;
    registered_record_entry *re;
    // Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
    // clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
    if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly && !IsLocalDomain(rr->resrec.name) &&
        rr->resrec.rrclass == kDNSClass_IN && (rr->resrec.rrtype == kDNSType_A || rr->resrec.rrtype == kDNSType_AAAA ||
                                               rr->resrec.rrtype == kDNSType_CNAME))
    {
        freeL("AuthRecord/handle_regrecord_request", rr);
        return (mStatus_BadParamErr);
    }
    // allocate registration entry, link into list
    re = (registered_record_entry *) callocL("registered_record_entry", sizeof(*re));
    if (!re) FatalError("ERROR: calloc");
    re->key                   = request->hdr.reg_index;
    re->rr                    = rr;
    re->regrec_client_context = request->hdr.client_context;
    re->request               = request;
    re->external_advertise    = mDNSfalse;
    rr->RecordContext         = re;
    rr->RecordCallback        = regrecord_callback;

    re->origInterfaceID = rr->resrec.InterfaceID;
    if (rr->resrec.InterfaceID == mDNSInterface_P2P)
        rr->resrec.InterfaceID = mDNSInterface_Any;
#if 0
    if (!AuthorizedDomain(request, rr->resrec.name, AutoRegistrationDomains)) return (mStatus_NoError);
#endif
    if (rr->resrec.rroriginalttl == 0)
        rr->resrec.rroriginalttl = DefaultTTLforRRType(rr->resrec.rrtype);

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] DNSServiceRegisterRecord(0x%X, %d, " PRI_S ") START PID[%d](" PUB_S ")",
           request->request_id, request->flags, request->interfaceIndex, RRDisplayString(&mDNSStorage, &rr->resrec), request->process_id,
           request->pid_name);

    err = mDNS_Register(&mDNSStorage, rr);
    if (err)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
               "[R%d] DNSServiceRegisterRecord(0x%X, %d," PRI_S ") ERROR (%d)",
               request->request_id, request->flags, request->interfaceIndex, RRDisplayString(&mDNSStorage, &rr->resrec), err);
        freeL("registered_record_entry", re);
        freeL("registered_record_entry/AuthRecord", rr);
    }
    else
    {
        LogMcastS(rr, request, reg_start);
        re->next = request->u.reg_recs;
        request->u.reg_recs = re;
    }
    return err;
}

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)

mDNSlocal void _return_regrecord_request_error(request_state *request, mStatus error)
{
    reply_state *rep;
    if (GenerateNTDResponse(NULL, 0, request, &rep, reg_record_reply_op, 0, error) != mStatus_NoError)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u] DNSServiceRegisterRecord _return_regrecord_request_error: error(%d)", request->request_id, error);
    }
    else
    {
        append_reply(request, rep);
    }
}

mDNSlocal mStatus _handle_regrecord_request_with_trust(request_state *request, AuthRecord * rr)
{
    mStatus err;
    if (audit_token_to_pid(request->audit_token) == 0)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_WARNING, "[R%u] _handle_regrecord_request_with_trust: no audit token for pid(%s %d)", request->request_id, request->pid_name, request->process_id);
        err = _handle_regrecord_request_start(request, rr);
    }
    else
    {
        const char *service_ptr = NULL;
        char type_str[MAX_ESCAPED_DOMAIN_NAME] = "";
        domainlabel name;
        domainname type, domain;
        bool good = DeconstructServiceName(rr->resrec.name, &name, &type, &domain);
        if (good)
        {
            ConvertDomainNameToCString(&type, type_str);
            service_ptr = type_str;
        }

        mdns_trust_flags_t flags = mdns_trust_flags_none;
        mdns_trust_status_t status = mdns_trust_check_bonjour(request->audit_token, service_ptr, &flags);
        switch (status)
        {
            case mdns_trust_status_denied:
            case mdns_trust_status_pending:
            {
                mdns_trust_t trust = mdns_trust_create(request->audit_token, service_ptr, flags);
                if (!trust)
                {
                    freeL("AuthRecord/_handle_regrecord_request_with_trust", rr);
                    err = mStatus_NoMemoryErr;
                    goto exit;
                }
                mdns_trust_set_context(trust, rr);
                mdns_trust_set_queue(trust, _get_trust_results_dispatch_queue());
                mdns_trust_set_event_handler(trust, ^(mdns_trust_event_t event, mdns_trust_status_t update)
                {
                    if (event == mdns_trust_event_result)
                    {
                        mStatus error = (update != mdns_trust_status_granted) ? mStatus_PolicyDenied : mStatus_NoError;
                        KQueueLock();
                        AuthRecord * _rr =  mdns_trust_get_context(trust);
                        if (_rr)
                        {
                            if (!error)
                            {
                                mdns_trust_set_context(trust, NULL); // _handle_regrecord_request_start handles free
                                error = _handle_regrecord_request_start(request, _rr);
                                // No context means the request was canceled before we got here
                            }
                            if (error) // (not else if) Always check for error result
                            {
                                _return_regrecord_request_error(request, error);
                            }
                        }
                        KQueueUnlock("_handle_regrecord_request_with_trust");
                    }
                });
                request->trust = trust;
                mdns_trust_activate(trust);
                err = mStatus_NoError;
                break;
            }

            case mdns_trust_status_no_entitlement:
                err = mStatus_NoAuth;
                break;

            case mdns_trust_status_granted:
                err = _handle_regrecord_request_start(request, rr);
                break;

            default:
                err = mStatus_UnknownErr;
                break;
        }
     }
exit:
    return err;
}
#endif // TRUST_ENFORCEMENT

mDNSlocal mStatus handle_regrecord_request(request_state *request)
{
    mStatus err = mStatus_BadParamErr;
    AuthRecord *rr;

    if (request->terminate != connection_termination)
    { LogMsg("%3d: DNSServiceRegisterRecord(not a shared connection ref)", request->sd); return(err); }

    rr = read_rr_from_ipc_msg(request, 1, 1);
    if (rr)
    {
#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
        if (os_feature_enabled(mDNSResponder, bonjour_privacy) &&
            IsLocalDomain(rr->resrec.name))
        {
            err = _handle_regrecord_request_with_trust(request, rr);
        }
        else
        {
            err = _handle_regrecord_request_start(request, rr);
        }
#else
        err = _handle_regrecord_request_start(request, rr);
#endif
    }
    return(err);
}

mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m);

mDNSlocal void regservice_termination_callback(request_state *request)
{
    if (!request)
    {
        LogMsg("regservice_termination_callback context is NULL");
        return;
    }
    while (request->u.servicereg.instances)
    {
        service_instance *p = request->u.servicereg.instances;
        request->u.servicereg.instances = request->u.servicereg.instances->next;
        // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[R%d] DNSServiceRegister(" PRI_DM_NAME ", %u) STOP PID[%d](" PUB_S ")",
               request->request_id, DM_NAME_PARAM(p->srs.RR_SRV.resrec.name),
               mDNSVal16(p->srs.RR_SRV.resrec.rdata->u.srv.port), request->process_id, request->pid_name);

#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
        external_stop_advertising_helper(p);
#endif

        // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
        // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
        // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
        // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
        // because by then we might have already freed p
        p->request = NULL;
        LogMcastS(&p->srs.RR_SRV, request, reg_stop);
        if (mDNS_DeregisterService(&mDNSStorage, &p->srs))
        {
            unlink_and_free_service_instance(p);
            // Don't touch service_instance *p after this -- it's likely to have been freed already
        }
    }
    if (request->u.servicereg.txtdata)
    {
        freeL("service_info txtdata", request->u.servicereg.txtdata);
        request->u.servicereg.txtdata = NULL;
    }
    if (request->u.servicereg.autoname)
    {
        // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
        request->u.servicereg.autoname = mDNSfalse;
        UpdateDeviceInfoRecord(&mDNSStorage);
    }
}

mDNSlocal request_state *LocateSubordinateRequest(request_state *request)
{
    request_state *req;
    for (req = all_requests; req; req = req->next)
        if (req->primary == request &&
            req->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
            req->hdr.client_context.u32[1] == request->hdr.client_context.u32[1]) return(req);
    return(request);
}

mDNSlocal mStatus add_record_to_service(request_state *request, service_instance *instance, mDNSu16 rrtype, mDNSu16 rdlen,
    const mDNSu8 *const rdata, mDNSu32 ttl)
{
    ServiceRecordSet *srs = &instance->srs;
    mStatus result;
    const size_t rdcapacity = (rdlen > sizeof(RDataBody2)) ? rdlen : sizeof(RDataBody2);
    ExtraResourceRecord *extra = (ExtraResourceRecord *)callocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + rdcapacity);
    if (!extra) { my_perror("ERROR: calloc"); return mStatus_NoMemoryErr; }

    extra->r.resrec.rrtype = rrtype;
    extra->r.resrec.rdata = &extra->r.rdatastorage;
    extra->r.resrec.rdata->MaxRDLength = (mDNSu16)rdcapacity;
    extra->r.resrec.rdlength = rdlen;
    if (!SetRData(mDNSNULL, rdata, rdata + rdlen, &extra->r.resrec, rdlen))
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
            "[R%u] read_rr_from_ipc_msg: SetRData failed for " PRI_DM_NAME " (" PUB_S ")",
            request->request_id, DM_NAME_PARAM(request->u.servicereg.instances ?
            request->u.servicereg.instances->srs.RR_SRV.resrec.name : mDNSNULL), DNSTypeName(rrtype));
        freeL("ExtraResourceRecord/add_record_to_service", extra);
        return mStatus_BadParamErr;
    }
    SetNewRData(&extra->r.resrec, mDNSNULL, 0);  // Sets rr->rdatahash for us
    // use InterfaceID value from DNSServiceRegister() call that created the original service
    extra->r.resrec.InterfaceID = request->u.servicereg.InterfaceID;

    result = mDNS_AddRecordToService(&mDNSStorage, srs, extra, &extra->r.rdatastorage, ttl, request->flags);
    if (result)
    {
        freeL("ExtraResourceRecord/add_record_to_service", extra);
        return result;
    }
    LogMcastS(&srs->RR_PTR, request, reg_start);

    extra->ClientID = request->hdr.reg_index;
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
    if (   instance->external_advertise
           && callExternalHelpers(request->u.servicereg.InterfaceID, &instance->domain, request->flags))
    {
        LogInfo("add_record_to_service: calling external_start_advertising_service");
        external_start_advertising_service(&extra->r.resrec, request->flags, request->process_id);
    }
#endif
    return result;
}

mDNSlocal mStatus handle_add_request(request_state *request)
{
    service_instance *i;
    mStatus result = mStatus_UnknownErr;
    DNSServiceFlags flags  = get_flags (&request->msgptr, request->msgend);
    mDNSu16 rrtype = get_uint16(&request->msgptr, request->msgend);
    mDNSu16 rdlen  = get_uint16(&request->msgptr, request->msgend);
    const mDNSu8 *const rdata = (const mDNSu8 *)get_rdata(&request->msgptr, request->msgend, rdlen);
    mDNSu32 ttl    = get_uint32(&request->msgptr, request->msgend);
    if (!ttl) ttl = DefaultTTLforRRType(rrtype);
    (void)flags; // Unused

    if (!request->msgptr)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%d] DNSServiceAddRecord(unreadable parameters)", request->request_id);
        return(mStatus_BadParamErr);
    }

    // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
    if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);

    if (request->terminate != regservice_termination_callback)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%d] DNSServiceAddRecord(not a registered service ref)", request->request_id);
        return(mStatus_BadParamErr);
    }

    // For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
    // in the application. See radar://9165807.
    if (mDNSIPPortIsZero(request->u.servicereg.port))
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%d] DNSServiceAddRecord: adding record to a service registered with zero port", request->request_id);
        return(mStatus_BadParamErr);
    }
    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] DNSServiceAddRecord(%X, " PRI_DM_NAME ", " PUB_S ", %d) PID[%d](" PUB_S ")",
           request->request_id, flags,
           DM_NAME_PARAM((request->u.servicereg.instances) ? (request->u.servicereg.instances->srs.RR_SRV.resrec.name) : mDNSNULL),
           DNSTypeName(rrtype), rdlen, request->process_id, request->pid_name);

    for (i = request->u.servicereg.instances; i; i = i->next)
    {
        result = add_record_to_service(request, i, rrtype, rdlen, rdata, ttl);
        if (result && i->default_local) break;
        else result = mStatus_NoError;  // suppress non-local default errors
    }

    return(result);
}

mDNSlocal void update_callback(mDNS *const m, AuthRecord *const rr, RData *oldrd, mDNSu16 oldrdlen)
{
    mDNSBool external_advertise = (rr->UpdateContext) ? *((mDNSBool *)rr->UpdateContext) : mDNSfalse;
    (void)m; // Unused

    // There are three cases.
    //
    // 1. We have updated the primary TXT record of the service
    // 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
    // 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
    //
    // external_advertise is set if we have advertised at least once during the initial addition
    // of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
    // checks during the first time and hence we don't do any checks here
    if (external_advertise)
    {
        ResourceRecord ext = rr->resrec;
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
        DNSServiceFlags flags = deriveD2DFlagsFromAuthRecType(rr->ARType);
#endif

        if (ext.rdlength == oldrdlen && mDNSPlatformMemSame(&ext.rdata->u, &oldrd->u, oldrdlen)) goto exit;
        SetNewRData(&ext, oldrd, oldrdlen);
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
        external_stop_advertising_service(&ext, flags, 0);
        LogInfo("update_callback: calling external_start_advertising_service");
        external_start_advertising_service(&rr->resrec, flags, 0);
#endif
    }
exit:
    if (oldrd != &rr->rdatastorage) freeL("RData/update_callback", oldrd);
}

mDNSlocal mStatus update_record(AuthRecord *ar, mDNSu16 rdlen, const mDNSu8 *const rdata, mDNSu32 ttl,
    const mDNSBool *const external_advertise, const mDNSu32 request_id)
{
    ResourceRecord rr;
    mStatus result;
    const size_t rdcapacity = (rdlen > sizeof(RDataBody2)) ? rdlen : sizeof(RDataBody2);
    RData *newrd = (RData *) callocL("RData/update_record", sizeof(*newrd) - sizeof(RDataBody) + rdcapacity);
    if (!newrd) FatalError("ERROR: calloc");
    mDNSPlatformMemZero(&rr, (mDNSu32)sizeof(rr));
    rr.name     = ar->resrec.name;
    rr.rrtype   = ar->resrec.rrtype;
    rr.rrclass  = ar->resrec.rrclass;
    rr.rdata    = newrd;
    rr.rdata->MaxRDLength = (mDNSu16)rdcapacity;
    rr.rdlength = rdlen;
    if (!SetRData(mDNSNULL, rdata, rdata + rdlen, &rr, rdlen))
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
            "[R%u] update_record: SetRData failed for " PRI_DM_NAME " (" PUB_S ")",
            request_id, DM_NAME_PARAM(rr.name), DNSTypeName(rr.rrtype));
        freeL("RData/update_record", newrd);
        return mStatus_BadParamErr;
    }
    rdlen = GetRDLength(&rr, mDNSfalse);
    // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
    // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
    // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
    if (ar->resrec.rrtype == kDNSType_TXT && rdlen == 0) { rdlen = 1; newrd->u.txt.c[0] = 0; }

    if (external_advertise) ar->UpdateContext = (void *)external_advertise;

    result = mDNS_Update(&mDNSStorage, ar, ttl, rdlen, newrd, update_callback);
    if (result) { LogMsg("update_record: Error %d for %s", (int)result, ARDisplayString(&mDNSStorage, ar)); freeL("RData/update_record", newrd); }
    return result;
}

mDNSlocal mStatus handle_update_request(request_state *request)
{
    const ipc_msg_hdr *const hdr = &request->hdr;
    mStatus result = mStatus_BadReferenceErr;
    service_instance *i;
    AuthRecord *rr = NULL;

    // get the message data
    DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend);  // flags unused
    mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
    const mDNSu8 *const rdata = (const mDNSu8 *)get_rdata(&request->msgptr, request->msgend, rdlen);
    mDNSu32 ttl   = get_uint32(&request->msgptr, request->msgend);
    (void)flags; // Unused

    if (!request->msgptr)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%d] DNSServiceUpdateRecord(unreadable parameters)", request->request_id);
        return(mStatus_BadParamErr);
    }

    // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
    if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);

    if (request->terminate == connection_termination)
    {
        // update an individually registered record
        registered_record_entry *reptr;
        for (reptr = request->u.reg_recs; reptr; reptr = reptr->next)
        {
            if (reptr->key == hdr->reg_index)
            {
                result = update_record(reptr->rr, rdlen, rdata, ttl, &reptr->external_advertise, request->request_id);
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
                       "[R%d] DNSServiceUpdateRecord(" PRI_DM_NAME ", " PUB_S ") PID[%d](" PUB_S ")",
                       request->request_id, DM_NAME_PARAM(reptr->rr->resrec.name),
                       reptr->rr ? DNSTypeName(reptr->rr->resrec.rrtype) : "<NONE>",
                       request->process_id, request->pid_name);
                goto end;
            }
        }
        result = mStatus_BadReferenceErr;
        goto end;
    }

    if (request->terminate != regservice_termination_callback)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%d] DNSServiceUpdateRecord(not a registered service ref)", request->request_id);
        return(mStatus_BadParamErr);
    }

    // For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
    if (mDNSIPPortIsZero(request->u.servicereg.port))
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%d] DNSServiceUpdateRecord: updating the record of a service registered with zero port", request->request_id);
        return(mStatus_BadParamErr);
    }

    // update the saved off TXT data for the service
    if (hdr->reg_index == TXT_RECORD_INDEX)
    {
        if (request->u.servicereg.txtdata)
        { freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; }
        if (rdlen > 0)
        {
            request->u.servicereg.txtdata = mallocL("service_info txtdata", rdlen);
            if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_update_request - malloc");
            mDNSPlatformMemCopy(request->u.servicereg.txtdata, rdata, rdlen);
        }
        request->u.servicereg.txtlen = rdlen;
    }

    // update a record from a service record set
    for (i = request->u.servicereg.instances; i; i = i->next)
    {
        if (hdr->reg_index == TXT_RECORD_INDEX) rr = &i->srs.RR_TXT;
        else
        {
            ExtraResourceRecord *e;
            for (e = i->srs.Extras; e; e = e->next)
                if (e->ClientID == hdr->reg_index) { rr = &e->r; break; }
        }

        if (!rr) { result = mStatus_BadReferenceErr; goto end; }
        result = update_record(rr, rdlen, rdata, ttl, &i->external_advertise, request->request_id);
        if (result && i->default_local) goto end;
        else result = mStatus_NoError;  // suppress non-local default errors
    }

end:
    if (request->terminate == regservice_termination_callback)
        LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)  PID[%d](%s)", request->sd,
                     (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
                     rr ? DNSTypeName(rr->resrec.rrtype) : "<NONE>",
                     request->process_id, request->pid_name);

    return(result);
}

// remove a resource record registered via DNSServiceRegisterRecord()
mDNSlocal mStatus remove_record(request_state *request)
{
    mStatus err = mStatus_UnknownErr;
    registered_record_entry *e, **ptr = &request->u.reg_recs;

    while (*ptr && (*ptr)->key != request->hdr.reg_index) ptr = &(*ptr)->next;
    if (!*ptr) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request->sd, request->hdr.reg_index); return mStatus_BadReferenceErr; }
    e = *ptr;
    *ptr = e->next; // unlink

    LogOperation("%3d: DNSServiceRemoveRecord(%u %s)  PID[%d](%s)",
                request->sd, e->key, RRDisplayString(&mDNSStorage, &e->rr->resrec), request->process_id, request->pid_name);
    e->rr->RecordContext = NULL;
    if (e->external_advertise)
    {
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
        external_stop_advertising_service(&e->rr->resrec, request->flags, request->process_id);
#endif
        e->external_advertise = mDNSfalse;
    }
    LogMcastS(e->rr, request, reg_stop);
    err = mDNS_Deregister(&mDNSStorage, e->rr);     // Will free e->rr for us; we're responsible for freeing e
    if (err)
    {
        LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err);
        freeL("registered_record_entry AuthRecord remove_record", e->rr);
    }
    freeL("registered_record_entry remove_record", e);
    return err;
}

mDNSlocal mStatus remove_extra(const request_state *const request, service_instance *const serv, mDNSu16 *const rrtype)
{
    mStatus err = mStatus_BadReferenceErr;
    ExtraResourceRecord *ptr;

    for (ptr = serv->srs.Extras; ptr; ptr = ptr->next)
    {
        if (ptr->ClientID == request->hdr.reg_index) // found match
        {
            *rrtype = ptr->r.resrec.rrtype;
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
            if (serv->external_advertise)
            {
                external_stop_advertising_service(&ptr->r.resrec, request->flags, request->process_id);
            }
#endif
            err = mDNS_RemoveRecordFromService(&mDNSStorage, &serv->srs, ptr, FreeExtraRR, ptr);
            break;
        }
    }
    return err;
}

mDNSlocal mStatus handle_removerecord_request(request_state *request)
{
    mStatus err = mStatus_BadReferenceErr;
    get_flags(&request->msgptr, request->msgend);   // flags unused

    if (!request->msgptr)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%d] DNSServiceRemoveRecord(unreadable parameters)", request->request_id);
        return(mStatus_BadParamErr);
    }

    // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
    if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);

    if (request->terminate == connection_termination)
        err = remove_record(request);  // remove individually registered record
    else if (request->terminate != regservice_termination_callback)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%d] DNSServiceRemoveRecord(not a registered service ref)", request->request_id);
        return(mStatus_BadParamErr);
    }
    else
    {
        service_instance *i;
        mDNSu16 rrtype = 0;
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[R%d] DNSServiceRemoveRecord(" PRI_DM_NAME ", " PUB_S ") PID[%d](" PUB_S ")",
               request->request_id,
               DM_NAME_PARAM((request->u.servicereg.instances) ? (request->u.servicereg.instances->srs.RR_SRV.resrec.name) : mDNSNULL),
               rrtype ? DNSTypeName(rrtype) : "<NONE>", request->process_id, request->pid_name);
        for (i = request->u.servicereg.instances; i; i = i->next)
        {
            err = remove_extra(request, i, &rrtype);
            if (err && i->default_local) break;
            else err = mStatus_NoError;  // suppress non-local default errors
        }
    }

    return(err);
}

// If there's a comma followed by another character,
// FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
// Otherwise, it returns a pointer to the final nul at the end of the string
mDNSlocal char *FindFirstSubType(char *p)
{
    while (*p)
    {
        if (p[0] == '\\' && p[1])
        {
             p += 2;
        }
        else if (p[0] == ',' && p[1])
        {
            *p++ = 0;
            return(p);
        }
        else
        {
            p++;
        }
    }
    return(p);
}

// If there's a comma followed by another character,
// FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
// If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
// Otherwise, it returns a pointer to the final nul at the end of the string
mDNSlocal char *FindNextSubType(char *p)
{
    while (*p)
    {
        if (p[0] == '\\' && p[1])       // If escape character
            p += 2;                     // ignore following character
        else if (p[0] == ',')           // If we found a comma
        {
            if (p[1]) *p++ = 0;
            return(p);
        }
        else if (p[0] == '.')
            return(mDNSNULL);
        else p++;
    }
    return(p);
}

// Returns -1 if illegal subtype found
mDNSlocal mDNSs32 ChopSubTypes(char *regtype)
{
    mDNSs32 NumSubTypes = 0;
    char *stp = FindFirstSubType(regtype);
    while (stp && *stp)                 // If we found a comma...
    {
        if (*stp == ',') return(-1);
        NumSubTypes++;
        stp = FindNextSubType(stp);
    }
    if (!stp) return(-1);
    return(NumSubTypes);
}

mDNSlocal AuthRecord *AllocateSubTypes(mDNSs32 NumSubTypes, char *p)
{
    AuthRecord *st = mDNSNULL;
    if (NumSubTypes)
    {
        mDNSs32 i;
        st = (AuthRecord *) callocL("ServiceSubTypes", NumSubTypes * sizeof(AuthRecord));
        if (!st) return(mDNSNULL);
        for (i = 0; i < NumSubTypes; i++)
        {
            mDNS_SetupResourceRecord(&st[i], mDNSNULL, mDNSInterface_Any, kDNSQType_ANY, kStandardTTL, 0, AuthRecordAny, mDNSNULL, mDNSNULL);
            while (*p) p++;
            p++;
            if (!MakeDomainNameFromDNSNameString(&st[i].namestorage, p))
            {
                freeL("ServiceSubTypes", st);
                return(mDNSNULL);
            }
        }
    }
    return(st);
}

mDNSlocal mStatus register_service_instance(request_state *request, const domainname *domain)
{
    service_instance **ptr, *instance;
    size_t extra_size = (request->u.servicereg.txtlen > sizeof(RDataBody)) ? (request->u.servicereg.txtlen - sizeof(RDataBody)) : 0;
    const mDNSBool DomainIsLocal = SameDomainName(domain, &localdomain);
    mStatus result;
    mDNSInterfaceID interfaceID = request->u.servicereg.InterfaceID;

    // If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
    // registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
    // registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
    // (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
    // currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
    if (request->u.servicereg.default_domain && !DomainIsLocal) interfaceID = mDNSInterface_Any;

    for (ptr = &request->u.servicereg.instances; *ptr; ptr = &(*ptr)->next)
    {
        if (SameDomainName(&(*ptr)->domain, domain))
        {
            LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
                   domain->c, &request->u.servicereg.name, &request->u.servicereg.type);
            return mStatus_AlreadyRegistered;
        }
    }

    instance = (service_instance *) callocL("service_instance", sizeof(*instance) + extra_size);
    if (!instance) { my_perror("ERROR: calloc"); return mStatus_NoMemoryErr; }

    instance->next                          = mDNSNULL;
    instance->request                       = request;
    instance->renameonmemfree               = 0;
    instance->clientnotified                = mDNSfalse;
    instance->default_local                 = (request->u.servicereg.default_domain && DomainIsLocal);
    instance->external_advertise            = mDNSfalse;
    AssignDomainName(&instance->domain, domain);

    instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string);

    if (request->u.servicereg.num_subtypes && !instance->subtypes)
    {
        unlink_and_free_service_instance(instance);
        instance = NULL;
        FatalError("ERROR: malloc");
    }

    result = mDNS_RegisterService(&mDNSStorage, &instance->srs,
                                  &request->u.servicereg.name, &request->u.servicereg.type, domain,
                                  request->u.servicereg.host.c[0] ? &request->u.servicereg.host : NULL,
                                  request->u.servicereg.port,
                                  mDNSNULL, request->u.servicereg.txtdata, request->u.servicereg.txtlen,
                                  instance->subtypes, request->u.servicereg.num_subtypes,
                                  interfaceID, regservice_callback, instance, request->flags);

    if (!result)
    {
        *ptr = instance;        // Append this to the end of our request->u.servicereg.instances list
        LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED", instance->request->sd,
                     instance->srs.RR_SRV.resrec.name->c, mDNSVal16(request->u.servicereg.port));
        LogMcastS(&instance->srs.RR_SRV, request, reg_start);
    }
    else
    {
        LogMsg("register_service_instance %#s.%##s%##s error %d",
               &request->u.servicereg.name, &request->u.servicereg.type, domain->c, result);
        unlink_and_free_service_instance(instance);
    }

    return result;
}

mDNSlocal void udsserver_default_reg_domain_changed(const DNameListElem *const d, const mDNSBool add)
{
    request_state *request;

    LogMsg("%s registration domain %##s", add ? "Adding" : "Removing", d->name.c);
    for (request = all_requests; request; request = request->next)
    {
        if (request->terminate != regservice_termination_callback) continue;
        if (!request->u.servicereg.default_domain) continue;
        if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
        {
            service_instance **ptr = &request->u.servicereg.instances;
            while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
            if (add)
            {
                // If we don't already have this domain in our list for this registration, add it now
                if (!*ptr) register_service_instance(request, &d->name);
                else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d->name);
            }
            else
            {
                // Normally we should not fail to find the specified instance
                // One case where this can happen is if a uDNS update fails for some reason,
                // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
                if (!*ptr)
                    LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
                           &d->name, request->u.servicereg.name.c, request->u.servicereg.type_as_string);
                else
                {
                    DNameListElem *p;
                    for (p = AutoRegistrationDomains; p; p=p->next)
                        if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
                            if (SameDomainName(&d->name, &p->name)) break;
                    if (p) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d->name);
                    else
                    {
                        mStatus err;
                        service_instance *si = *ptr;
                        *ptr = si->next;
                        if (si->clientnotified) SendServiceRemovalNotification(&si->srs); // Do this *before* clearing si->request backpointer
                        // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
                        // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
                        // process of completing asynchronously, the client cancels the entire operation, so
                        // regservice_termination_callback then runs through the whole list deregistering each
                        // instance, clearing the backpointers, and then disposing the parent request_state object.
                        // However, because this service_instance isn't in the list any more, regservice_termination_callback
                        // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
                        // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
                        // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
                        si->request = NULL;
                        err = mDNS_DeregisterService(&mDNSStorage, &si->srs);
                        if (err) { LogMsg("udsserver_default_reg_domain_changed err %d", err); unlink_and_free_service_instance(si); }
                    }
                }
            }
        }
    }
}

// Returns true if the interfaceIndex value matches one of the pre-defined
// special values listed in the switch statement below.
mDNSlocal mDNSBool PreDefinedInterfaceIndex(mDNSu32 interfaceIndex)
{
    switch(interfaceIndex)
    {
        case kDNSServiceInterfaceIndexAny:
        case kDNSServiceInterfaceIndexLocalOnly:
        case kDNSServiceInterfaceIndexUnicast:
        case kDNSServiceInterfaceIndexP2P:
        case kDNSServiceInterfaceIndexBLE:
            return mDNStrue;
        default:
            return mDNSfalse;
    }
}

mDNSlocal mStatus _handle_regservice_request_start(request_state *request, const domainname * const d)
{
    mStatus err;

    request->terminate = regservice_termination_callback;
    err = register_service_instance(request, d);

#if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
    ++curr_num_regservices;
    if (curr_num_regservices > max_num_regservices)
        max_num_regservices = curr_num_regservices;
#endif

#if 0
    err = AuthorizedDomain(request, d, AutoRegistrationDomains) ? register_service_instance(request, d) : mStatus_NoError;
#endif
    if (!err)
    {
        if (request->u.servicereg.autoname) UpdateDeviceInfoRecord(&mDNSStorage);

        if (request->u.servicereg.default_domain)
        {
            DNameListElem *ptr;
            // Note that we don't report errors for non-local, non-explicit domains
            for (ptr = AutoRegistrationDomains; ptr; ptr = ptr->next)
                if (!ptr->uid || SystemUID(request->uid) || request->uid == ptr->uid)
                    register_service_instance(request, &ptr->name);
        }
    }
    return err;
}

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)

mDNSlocal void _return_regservice_request_error(request_state *request, mStatus error)
{
    if (request->u.servicereg.txtdata)
    {
        freeL("service_info txtdata", request->u.servicereg.txtdata);
        request->u.servicereg.txtdata = NULL;
    }

    reply_state *rep;
    if (GenerateNTDResponse(NULL, 0, request, &rep, reg_service_reply_op, 0, error) != mStatus_NoError)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u] DNSServiceRegister _return_regservice_request_error: error(%d)", request->request_id, error);
    }
    else
    {
        append_reply(request, rep);
    }
}

mDNSlocal mStatus _handle_regservice_request_with_trust(request_state *request, const domainname * const d)
{
    mStatus err;
    if (audit_token_to_pid(request->audit_token) == 0)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_WARNING, "[R%u] _handle_regservice_request_with_trust: no audit token for pid(%s %d)", request->request_id, request->pid_name, request->process_id);
        err = _handle_regservice_request_start(request, d);
    }
    else
    {
        mdns_trust_flags_t flags = mdns_trust_flags_none;
        mdns_trust_status_t status = mdns_trust_check_register_service(request->audit_token, request->u.servicereg.type_as_string, &flags);
        switch (status) {
            case mdns_trust_status_denied:
            case mdns_trust_status_pending:
            {
                mdns_trust_t trust = mdns_trust_create(request->audit_token, request->u.servicereg.type_as_string, flags);
                if (!trust)
                {
                    err = mStatus_NoMemoryErr;
                    goto exit;
                }
                void * context = mallocL("context/_handle_regservice_request_with_trust", sizeof(domainname));
                if (!context)
                {
                    my_perror("ERROR: mallocL context/_handle_regservice_request_with_trust");
                    mdns_release(trust);
                    err = mStatus_NoMemoryErr;
                    goto exit;
                }
                memcpy(context, d, sizeof(domainname));
                mdns_trust_set_context(trust, context);

                mdns_trust_set_queue(trust, _get_trust_results_dispatch_queue());
                mdns_trust_set_event_handler(trust, ^(mdns_trust_event_t event, mdns_trust_status_t update)
                {
                    if (event == mdns_trust_event_result)
                    {
                        mStatus error = (update != mdns_trust_status_granted) ? mStatus_PolicyDenied : mStatus_NoError;
                        KQueueLock();
                        const domainname * _d = mdns_trust_get_context(trust);
                        if (_d)
                        {
                            if (!error)
                            {
                                error = _handle_regservice_request_start(request, _d);
                                // No context means the request was canceled before we got here
                            }
                            if (error) // (not else if) Always check for error result
                            {
                                _return_regservice_request_error(request, error);
                            }
                        }
                        KQueueUnlock("_register_service_instance_with_trust");
                    }
                });
                request->trust = trust;
                mdns_trust_activate(trust);
                err = mStatus_NoError;
                break;
            }

            case mdns_trust_status_no_entitlement:
                err = mStatus_NoAuth;
                break;

            case mdns_trust_status_granted:
                err = _handle_regservice_request_start(request, d);
                break;

            default:
                err = mStatus_UnknownErr;
                break;
        }
    }
exit:
    return err;
}
#endif // TRUST_ENFORCEMENT

mDNSlocal mStatus handle_regservice_request(request_state *request)
{
    char name[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
    char domain[MAX_ESCAPED_DOMAIN_NAME], host[MAX_ESCAPED_DOMAIN_NAME];
    char type_as_string[MAX_ESCAPED_DOMAIN_NAME];  // Note that this service type may include a trailing list of subtypes
    domainname d, srv;
    mStatus err;
    const char *msgTXTData;

    DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
    mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
    mDNSInterfaceID InterfaceID;

    // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the
    // kDNSServiceFlagsIncludeP2P flag set.
    if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
    {
        LogOperation("handle_regservice_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
        flags |= kDNSServiceFlagsIncludeP2P;
        interfaceIndex = kDNSServiceInterfaceIndexAny;
    }

    InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);

    // The registration is scoped to a specific interface index, but the
    // interface is not currently in our list.
    if (interfaceIndex && !InterfaceID)
    {
        // If it's one of the specially defined inteface index values, just return an error.
        if (PreDefinedInterfaceIndex(interfaceIndex))
        {
            LogInfo("handle_regservice_request: bad interfaceIndex %d", interfaceIndex);
            return(mStatus_BadParamErr);
        }

        // Otherwise, use the specified interface index value and the registration will
        // be applied to that interface when it comes up.
        InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
        LogInfo("handle_regservice_request: registration pending for interface index %d", interfaceIndex);
    }

    if (get_string(&request->msgptr, request->msgend, name,           sizeof(name          )) < 0 ||
        get_string(&request->msgptr, request->msgend, type_as_string, sizeof(type_as_string)) < 0 ||
        get_string(&request->msgptr, request->msgend, domain,         sizeof(domain        )) < 0 ||
        get_string(&request->msgptr, request->msgend, host,           sizeof(host          )) < 0)
    { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }

    request->flags = flags;
    request->interfaceIndex = interfaceIndex;
    request->u.servicereg.InterfaceID = InterfaceID;
    request->u.servicereg.instances = NULL;
    request->u.servicereg.txtlen  = 0;
    request->u.servicereg.txtdata = NULL;
    mDNSPlatformStrLCopy(request->u.servicereg.type_as_string, type_as_string, sizeof(request->u.servicereg.type_as_string));

    if (request->msgptr + 2 > request->msgend) request->msgptr = NULL;
    else
    {
        request->u.servicereg.port.b[0] = *request->msgptr++;
        request->u.servicereg.port.b[1] = *request->msgptr++;
    }

    request->u.servicereg.txtlen = get_uint16(&request->msgptr, request->msgend);
    msgTXTData = get_rdata(&request->msgptr, request->msgend, request->u.servicereg.txtlen);

    if (!request->msgptr) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }

    if (request->u.servicereg.txtlen)
    {
        request->u.servicereg.txtdata = mallocL("service_info txtdata", request->u.servicereg.txtlen);
        if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_regservice_request - malloc");
        mDNSPlatformMemCopy(request->u.servicereg.txtdata, msgTXTData, request->u.servicereg.txtlen);
    }

    // Check for sub-types after the service type
    request->u.servicereg.num_subtypes = ChopSubTypes(request->u.servicereg.type_as_string);    // Note: Modifies regtype string to remove trailing subtypes
    if (request->u.servicereg.num_subtypes < 0)
    {
        LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request->u.servicereg.type_as_string);
        goto bad_param;
    }

    // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
    if (!*request->u.servicereg.type_as_string || !MakeDomainNameFromDNSNameString(&request->u.servicereg.type, request->u.servicereg.type_as_string))
    { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request->u.servicereg.type_as_string); goto bad_param; }

    if (!name[0])
    {
        request->u.servicereg.name = mDNSStorage.nicelabel;
        request->u.servicereg.autoname = mDNStrue;
    }
    else
    {
        // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
        if ((flags & kDNSServiceFlagsNoAutoRename) == 0)
        {
            int newlen = TruncateUTF8ToLength((mDNSu8*)name, mDNSPlatformStrLen(name), MAX_DOMAIN_LABEL);
            name[newlen] = 0;
        }
        if (!MakeDomainLabelFromLiteralString(&request->u.servicereg.name, name))
        { LogMsg("ERROR: handle_regservice_request - name bad %s", name); goto bad_param; }
        request->u.servicereg.autoname = mDNSfalse;
    }

    if (*domain)
    {
        request->u.servicereg.default_domain = mDNSfalse;
        if (!MakeDomainNameFromDNSNameString(&d, domain))
        { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain); goto bad_param; }
    }
    else
    {
        request->u.servicereg.default_domain = mDNStrue;
        MakeDomainNameFromDNSNameString(&d, "local.");
    }

    if (!ConstructServiceName(&srv, &request->u.servicereg.name, &request->u.servicereg.type, &d))
    {
        LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
               request->u.servicereg.name.c, request->u.servicereg.type.c, d.c); goto bad_param;
    }

    if (!MakeDomainNameFromDNSNameString(&request->u.servicereg.host, host))
    { LogMsg("ERROR: handle_regservice_request - host bad %s", host); goto bad_param; }
    request->u.servicereg.autorename       = (flags & kDNSServiceFlagsNoAutoRename    ) == 0;
    request->u.servicereg.allowremotequery = (flags & kDNSServiceFlagsAllowRemoteQuery) != 0;

    // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
    // a port number of zero. When two instances of the protected client are allowed to run on one
    // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
    if (!mDNSIPPortIsZero(request->u.servicereg.port))
    {
        int count = CountExistingRegistrations(&srv, request->u.servicereg.port);
        if (count)
            LogMsg("Client application[%d](%s) registered %d identical instances of service %##s port %u.", request->process_id,
                   request->pid_name, count+1, srv.c, mDNSVal16(request->u.servicereg.port));
    }

#if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
    // Determine if this request should be promoted to use BLE triggered feature.
    if (shouldUseBLE(InterfaceID, 0, &request->u.servicereg.type, &d))
    {
        request->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
        LogInfo("handle_regservice_request: registration promoted to use kDNSServiceFlagsAutoTrigger");
    }
#endif  // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] DNSServiceRegister(%X, %d, \"" PRI_S "\", \"" PRI_S "\", \"" PRI_S "\", \"" PRI_S "\", %u) START PID[%d](" PUB_S ")",
           request->request_id, request->flags, interfaceIndex, name, request->u.servicereg.type_as_string, domain, host,
           mDNSVal16(request->u.servicereg.port), request->process_id, request->pid_name);

    // We need to unconditionally set request->terminate, because even if we didn't successfully
    // start any registrations right now, subsequent configuration changes may cause successful
    // registrations to be added, and we'll need to cancel them before freeing this memory.
    // We also need to set request->terminate first, before adding additional service instances,
    // because the udsserver_validatelists uses the request->terminate function pointer to determine
    // what kind of request this is, and therefore what kind of list validation is required.
    request->terminate = NULL;

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
    if (os_feature_enabled(mDNSResponder, bonjour_privacy) &&
        (request->u.servicereg.default_domain || IsLocalDomain(&d)))
    {
        err = _handle_regservice_request_with_trust(request, &d);
        if (err == mStatus_NoAuth && request->u.servicereg.txtdata)
        {
            freeL("service_info txtdata", request->u.servicereg.txtdata);
            request->u.servicereg.txtdata = NULL;
        }
    }
    else
    {
        err = _handle_regservice_request_start(request, &d);
    }
#else
    err = _handle_regservice_request_start(request, &d);
#endif

    return(err);

bad_param:
    freeL("handle_regservice_request (txtdata)", request->u.servicereg.txtdata);
    request->u.servicereg.txtdata = NULL;
    return mStatus_BadParamErr;
}

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceBrowse
#endif

mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
{
    DNSServiceFlags flags = AddRecord ? kDNSServiceFlagsAdd : 0;
    request_state *req = question->QuestionContext;
    reply_state *rep;
    (void)m; // Unused

    if (answer->rrtype != kDNSType_PTR)
    { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req->sd, answer->rrtype); return; }

    if (mDNSOpaque16IsZero(question->TargetQID) && (question->BrowseThreshold > 0) && (question->CurrentAnswers >= question->BrowseThreshold))
    {
        flags |= kDNSServiceFlagsThresholdReached;
    }

    // if returning a negative answer, then use question's name in reply
    if (answer->RecordType == kDNSRecordTypePacketNegative)
    {
        GenerateBrowseReply(&question->qname, answer->InterfaceID, req, &rep, browse_reply_op, flags, kDNSServiceErr_NoSuchRecord);
        goto validReply;
    }

    if (GenerateNTDResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError) != mStatus_NoError)
    {
        if (SameDomainName(&req->u.browser.regtype, (const domainname*)"\x09_services\x07_dns-sd\x04_udp"))
        {
            // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
            // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
            GenerateBrowseReply(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError);
            goto validReply;
        }

        LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
               req->sd, answer->name->c, answer->rdata->u.name.c);
        return;
    }

validReply:

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d->Q%d] DNSServiceBrowse(" PRI_DM_NAME ", " PUB_S ") RESULT " PUB_S " interface %d: " PRI_S,
           req->request_id, mDNSVal16(question->TargetQID), DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype),
           AddRecord ? "ADD" : "RMV", mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse),
           RRDisplayString(m, answer));

    append_reply(req, rep);
}

mDNSlocal void SetQuestionPolicy(DNSQuestion *q, request_state *req)
{
    q->euid = req->uid;
    // The policy is either based on pid or UUID. Pass a zero pid
    // to the "core" if the UUID is valid. If we always pass the pid,
    // then the "core" needs to determine whether the uuid is valid
    // by examining all the 16 bytes at the time of the policy
    // check and also when setting the delegate socket option. Also, it
    // requires that we zero out the uuid wherever the question is
    // initialized to make sure that it is not interpreted as valid.
    // To prevent these intrusive changes, just pass a zero pid to indicate
    // that pid is not valid when uuid is valid. In future if we need the
    // pid in the question, we will reevaluate this strategy.
    if (req->validUUID)
    {
        mDNSPlatformMemCopy(q->uuid, req->uuid, UUID_SIZE);
        q->pid = 0;
    }
    else
    {
        q->pid = req->process_id;
    }

    //debugf("SetQuestionPolicy: q->euid[%d] q->pid[%d] uuid is valid : %s", q->euid, q->pid, req->validUUID ? "true" : "false");
}

mDNSlocal mStatus add_domain_to_browser(request_state *info, const domainname *d)
{
    browser_t *b, *p;
    mStatus err;

    for (p = info->u.browser.browsers; p; p = p->next)
    {
        if (SameDomainName(&p->domain, d))
        { debugf("add_domain_to_browser %##s already in list", d->c); return mStatus_AlreadyRegistered; }
    }

    b = (browser_t *) callocL("browser_t", sizeof(*b));
    if (!b) return mStatus_NoMemoryErr;
    AssignDomainName(&b->domain, d);
    SetQuestionPolicy(&b->q, info);
    err = mDNS_StartBrowse(&mDNSStorage, &b->q, &info->u.browser.regtype, d, info->u.browser.interface_id, info->flags,
                            info->u.browser.ForceMCast, (info->flags & kDNSServiceFlagsBackgroundTrafficClass) != 0, FoundInstance, info);
    if (err)
    {
        LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err, info->u.browser.regtype.c, d->c);
        freeL("browser_t/add_domain_to_browser", b);
    }
    else
    {
        b->next = info->u.browser.browsers;
        info->u.browser.browsers = b;

#if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
        // Determine if this request should be promoted to use BLE triggered discovery.
        if (shouldUseBLE(info->u.browser.interface_id, 0, &info->u.browser.regtype, (domainname *) d))
        {
            info->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
            b->q.flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
            LogInfo("add_domain_to_browser: request promoted to use kDNSServiceFlagsAutoTrigger");
        }
#endif  // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR

        LogMcastQ(&b->q, info, q_start);
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
        if (callExternalHelpers(info->u.browser.interface_id, &b->domain, info->flags))
        {
            domainname tmp;
            ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &b->domain);
            LogDebug("add_domain_to_browser: calling external_start_browsing_for_service()");
            external_start_browsing_for_service(info->u.browser.interface_id, &tmp, kDNSType_PTR, info->flags, info->process_id);
        }
#endif
    }
    return err;
}

mDNSlocal void browse_termination_callback(request_state *info)
{
    if (info->u.browser.default_domain)
    {
        // Stop the domain enumeration queries to discover the WAB legacy browse domains
        LogInfo("%3d: DNSServiceBrowse Cancel WAB PID[%d](%s)", info->sd, info->process_id, info->pid_name);
        uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
    }
    while (info->u.browser.browsers)
    {
        browser_t *ptr = info->u.browser.browsers;

#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
        if (callExternalHelpers(ptr->q.InterfaceID, &ptr->domain, ptr->q.flags))
        {
            domainname tmp;
            ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &ptr->domain);
            LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
            external_stop_browsing_for_service(ptr->q.InterfaceID, &tmp, kDNSType_PTR, ptr->q.flags, info->process_id);
        }
#endif
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
               "[R%d] DNSServiceBrowse(%X, %d, \"" PRI_DM_NAME "\") STOP PID[%d](" PUB_S ")",
               info->request_id, info->flags, info->interfaceIndex, DM_NAME_PARAM(&ptr->q.qname),
               info->process_id, info->pid_name);

        info->u.browser.browsers = ptr->next;
        mDNS_StopBrowse(&mDNSStorage, &ptr->q);  // no need to error-check result
        LogMcastQ(&ptr->q, info, q_stop);
        freeL("browser_t/browse_termination_callback", ptr);
    }
}

mDNSlocal void udsserver_automatic_browse_domain_changed(const DNameListElem *const d, const mDNSBool add)
{
    request_state *request;
    debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add ? "Adding" : "Removing", d->name.c);

    for (request = all_requests; request; request = request->next)
    {
        if (request->terminate != browse_termination_callback) continue;    // Not a browse operation
        if (!request->u.browser.default_domain) continue;                   // Not an auto-browse operation
        if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
        {
            browser_t **ptr = &request->u.browser.browsers;
            while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
            if (add)
            {
                // If we don't already have this domain in our list for this browse operation, add it now
                if (!*ptr) add_domain_to_browser(request, &d->name);
                else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d->name);
            }
            else
            {
                if (!*ptr) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d->name);
                else
                {
                    DNameListElem *p;
                    for (p = AutoBrowseDomains; p; p=p->next)
                        if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
                            if (SameDomainName(&d->name, &p->name)) break;
                    if (p) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d->name);
                    else
                    {
                        browser_t *rem = *ptr;
                        *ptr = (*ptr)->next;
                        mDNS_StopQueryWithRemoves(&mDNSStorage, &rem->q);
                        freeL("browser_t/udsserver_automatic_browse_domain_changed", rem);
                    }
                }
            }
        }
    }
}

mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
{
    (void)m;  // unused
    if (result == mStatus_MemFree)
    {
        // On shutdown, mDNS_Close automatically deregisters all records
        // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
        // from the LocalDomainEnumRecords list, we do this here before we free the memory.
        // (This should actually no longer be necessary, now that we do the proper cleanup in
        // udsserver_exit. To confirm this, we'll log an error message if we do find a record that
        // hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
        ARListElem **ptr = &LocalDomainEnumRecords;
        while (*ptr && &(*ptr)->ar != rr) ptr = &(*ptr)->next;
        if (*ptr) { *ptr = (*ptr)->next; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m, rr)); }
        mDNSPlatformMemFree(rr->RecordContext);
    }
}

// RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
// "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
// We may want to turn the common code into a subroutine.

mDNSlocal void RegisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
{
    // allocate/register legacy and non-legacy _browse PTR record
    mStatus err;
    ARListElem *ptr = (ARListElem *) mDNSPlatformMemAllocateClear(sizeof(*ptr));

    debugf("Incrementing %s refcount for %##s",
           (type == mDNS_DomainTypeBrowse         ) ? "browse domain   " :
           (type == mDNS_DomainTypeRegistration   ) ? "registration dom" :
           (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);

    mDNS_SetupResourceRecord(&ptr->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, AuthRecordLocalOnly, FreeARElemCallback, ptr);
    MakeDomainNameFromDNSNameString(&ptr->ar.namestorage, mDNS_DomainTypeNames[type]);
    AppendDNSNameString            (&ptr->ar.namestorage, "local");
    AssignDomainName(&ptr->ar.resrec.rdata->u.name, d);
    err = mDNS_Register(m, &ptr->ar);
    if (err)
    {
        LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err);
        mDNSPlatformMemFree(ptr);
    }
    else
    {
        ptr->next = LocalDomainEnumRecords;
        LocalDomainEnumRecords = ptr;
    }
}

mDNSlocal void DeregisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
{
    ARListElem **ptr = &LocalDomainEnumRecords;
    domainname lhs; // left-hand side of PTR, for comparison

    debugf("Decrementing %s refcount for %##s",
           (type == mDNS_DomainTypeBrowse         ) ? "browse domain   " :
           (type == mDNS_DomainTypeRegistration   ) ? "registration dom" :
           (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);

    MakeDomainNameFromDNSNameString(&lhs, mDNS_DomainTypeNames[type]);
    AppendDNSNameString            (&lhs, "local");

    while (*ptr)
    {
        if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, d) && SameDomainName((*ptr)->ar.resrec.name, &lhs))
        {
            ARListElem *rem = *ptr;
            *ptr = (*ptr)->next;
            mDNS_Deregister(m, &rem->ar);
            return;
        }
        else ptr = &(*ptr)->next;
    }
}

mDNSlocal void AddAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
{
    DNameListElem *new = (DNameListElem *) mDNSPlatformMemAllocateClear(sizeof(*new));
    if (!new) { LogMsg("ERROR: malloc"); return; }
    AssignDomainName(&new->name, name);
    new->uid = uid;
    new->next = AutoBrowseDomains;
    AutoBrowseDomains = new;
    udsserver_automatic_browse_domain_changed(new, mDNStrue);
}

mDNSlocal void RmvAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
{
    DNameListElem **p = &AutoBrowseDomains;
    while (*p && (!SameDomainName(&(*p)->name, name) || (*p)->uid != uid)) p = &(*p)->next;
    if (!*p) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name->c);
    else
    {
        DNameListElem *ptr = *p;
        *p = ptr->next;
        udsserver_automatic_browse_domain_changed(ptr, mDNSfalse);
        mDNSPlatformMemFree(ptr);
    }
}

mDNSlocal void SetPrefsBrowseDomains(mDNS *m, DNameListElem *browseDomains, mDNSBool add)
{
    DNameListElem *d;
    for (d = browseDomains; d; d = d->next)
    {
        if (add)
        {
            RegisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
            AddAutoBrowseDomain(d->uid, &d->name);
        }
        else
        {
            DeregisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
            RmvAutoBrowseDomain(d->uid, &d->name);
        }
    }
}

#if APPLE_OSX_mDNSResponder

mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
{
    int num_autoname = 0;
    request_state *req;

    // Don't need to register the device info record for kDNSServiceInterfaceIndexLocalOnly registrations.
    for (req = all_requests; req; req = req->next)
    {
        if (req->terminate == regservice_termination_callback && req->u.servicereg.autoname && req->interfaceIndex != kDNSServiceInterfaceIndexLocalOnly)
            num_autoname++;
    }

    // If DeviceInfo record is currently registered, see if we need to deregister it
    if (m->DeviceInfo.resrec.RecordType != kDNSRecordTypeUnregistered)
        if (num_autoname == 0 || !SameDomainLabelCS(m->DeviceInfo.resrec.name->c, m->nicelabel.c))
        {
            LogOperation("UpdateDeviceInfoRecord Deregister %##s", m->DeviceInfo.resrec.name);
            mDNS_Deregister(m, &m->DeviceInfo);
        }

    // If DeviceInfo record is not currently registered, see if we need to register it
    if (m->DeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered)
        if (num_autoname > 0)
        {
            mDNS_SetupResourceRecord(&m->DeviceInfo, mDNSNULL, mDNSNULL, kDNSType_TXT, kStandardTTL, kDNSRecordTypeAdvisory, AuthRecordAny, mDNSNULL, mDNSNULL);
            ConstructServiceName(&m->DeviceInfo.namestorage, &m->nicelabel, &DeviceInfoName, &localdomain);
            m->DeviceInfo.resrec.rdlength = initializeDeviceInfoTXT(m, m->DeviceInfo.resrec.rdata->u.data);
            LogOperation("UpdateDeviceInfoRecord   Register %##s", m->DeviceInfo.resrec.name);
            mDNS_Register(m, &m->DeviceInfo);
        }
}
#else   // APPLE_OSX_mDNSResponder
mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
{
    (void)m; // unused
}
#endif  // APPLE_OSX_mDNSResponder

mDNSexport void udsserver_handle_configchange(mDNS *const m)
{
    request_state *req;
    service_instance *ptr;
    DNameListElem *RegDomains = NULL;
    DNameListElem *BrowseDomains = NULL;
    DNameListElem *p;

    UpdateDeviceInfoRecord(m);

    // For autoname services, see if the default service name has changed, necessitating an automatic update
    for (req = all_requests; req; req = req->next)
        if (req->terminate == regservice_termination_callback)
            if (req->u.servicereg.autoname && !SameDomainLabelCS(req->u.servicereg.name.c, m->nicelabel.c))
            {
                req->u.servicereg.name = m->nicelabel;
                for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
                {
                    ptr->renameonmemfree = 1;
                    if (ptr->clientnotified) SendServiceRemovalNotification(&ptr->srs);
                    LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr->srs.RR_PTR.resrec.name->c);
                    if (mDNS_DeregisterService_drt(m, &ptr->srs, mDNS_Dereg_rapid))
                        regservice_callback(m, &ptr->srs, mStatus_MemFree); // If service deregistered already, we can re-register immediately
                }
            }

    // Let the platform layer get the current DNS information
    mDNS_Lock(m);
    mDNSPlatformSetDNSConfig(mDNSfalse, mDNSfalse, mDNSNULL, &RegDomains, &BrowseDomains, mDNSfalse);
    mDNS_Unlock(m);

    // Any automatic registration domains are also implicitly automatic browsing domains
    if (RegDomains) SetPrefsBrowseDomains(m, RegDomains, mDNStrue);                             // Add the new list first
    if (AutoRegistrationDomains) SetPrefsBrowseDomains(m, AutoRegistrationDomains, mDNSfalse);  // Then clear the old list

    // Add any new domains not already in our AutoRegistrationDomains list
    for (p=RegDomains; p; p=p->next)
    {
        DNameListElem **pp = &AutoRegistrationDomains;
        while (*pp && ((*pp)->uid != p->uid || !SameDomainName(&(*pp)->name, &p->name))) pp = &(*pp)->next;
        if (!*pp)       // If not found in our existing list, this is a new default registration domain
        {
            RegisterLocalOnlyDomainEnumPTR(m, &p->name, mDNS_DomainTypeRegistration);
            udsserver_default_reg_domain_changed(p, mDNStrue);
        }
        else            // else found same domainname in both old and new lists, so no change, just delete old copy
        {
            DNameListElem *del = *pp;
            *pp = (*pp)->next;
            mDNSPlatformMemFree(del);
        }
    }

    // Delete any domains in our old AutoRegistrationDomains list that are now gone
    while (AutoRegistrationDomains)
    {
        DNameListElem *del = AutoRegistrationDomains;
        AutoRegistrationDomains = AutoRegistrationDomains->next;        // Cut record from list FIRST,
        DeregisterLocalOnlyDomainEnumPTR(m, &del->name, mDNS_DomainTypeRegistration);
        udsserver_default_reg_domain_changed(del, mDNSfalse);           // before calling udsserver_default_reg_domain_changed()
        mDNSPlatformMemFree(del);
    }

    // Now we have our new updated automatic registration domain list
    AutoRegistrationDomains = RegDomains;

    // Add new browse domains to internal list
    if (BrowseDomains) SetPrefsBrowseDomains(m, BrowseDomains, mDNStrue);

    // Remove old browse domains from internal list
    if (SCPrefBrowseDomains)
    {
        SetPrefsBrowseDomains(m, SCPrefBrowseDomains, mDNSfalse);
        while (SCPrefBrowseDomains)
        {
            DNameListElem *fptr = SCPrefBrowseDomains;
            SCPrefBrowseDomains = SCPrefBrowseDomains->next;
            mDNSPlatformMemFree(fptr);
        }
    }

    // Replace the old browse domains array with the new array
    SCPrefBrowseDomains = BrowseDomains;
}

mDNSlocal void AutomaticBrowseDomainChange(mDNS *const m, DNSQuestion *q, const ResourceRecord *const answer, QC_result AddRecord)
{
    (void)m; // unused;
    (void)q; // unused

    LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
                 AddRecord ? "Adding" : "Removing", answer->rdata->u.name.c);

    if (AddRecord) AddAutoBrowseDomain(0, &answer->rdata->u.name);
    else RmvAutoBrowseDomain(0, &answer->rdata->u.name);
}

mDNSlocal mStatus _handle_browse_request_start(request_state *request, const char * domain)
{
    domainname d;
    mStatus err = mStatus_NoError;

    request->terminate = browse_termination_callback;

    if (domain[0])
    {
        if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr);
        err = add_domain_to_browser(request, &d);
    }
    else
    {
        DNameListElem *sdom;
        for (sdom = AutoBrowseDomains; sdom; sdom = sdom->next)
            if (!sdom->uid || SystemUID(request->uid) || request->uid == sdom->uid)
            {
                err = add_domain_to_browser(request, &sdom->name);
                if (err)
                {
                    if (SameDomainName(&sdom->name, &localdomain)) break;
                    else err = mStatus_NoError;  // suppress errors for non-local "default" domains
                }
            }
    }

    return(err);
}

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)

mDNSlocal void _return_browse_request_error(request_state *request, mStatus error)
{
    reply_state *rep;

    GenerateBrowseReply(NULL, 0, request, &rep, browse_reply_op, 0, error);

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] DNSServiceBrowse _return_browse_request_error: error (%d)", request->request_id, error);

    append_reply(request, rep);
}

mDNSlocal mStatus _handle_browse_request_with_trust(request_state *request, const char * domain)
{
    mStatus err;
    if (audit_token_to_pid(request->audit_token) == 0)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_WARNING, "[R%u] _handle_browse_request_with_trust: no audit token for pid(%s %d)", request->request_id, request->pid_name, request->process_id);
        err = _handle_browse_request_start(request, domain);
    }
    else
    {
        char typestr[MAX_ESCAPED_DOMAIN_NAME];
        typestr[0] = 0;
        (void)ConvertDomainNameToCString(&request->u.browser.regtype, typestr);
        mdns_trust_flags_t flags = mdns_trust_flags_none;
        mdns_trust_status_t status = mdns_trust_check_bonjour(request->audit_token, typestr, &flags);
        switch (status)
        {
            case mdns_trust_status_denied:
            case mdns_trust_status_pending:
            {
                mdns_trust_t trust = mdns_trust_create(request->audit_token, typestr, flags);
                if (!trust )
                {
                    err = mStatus_NoMemoryErr;
                    goto exit;
                }

                size_t len = strlen(domain) + 1;
                void * context = mallocL("context/_handle_browse_request_with_trust", len);
                if (!context)
                {
                    my_perror("ERROR: mallocL context/_handle_browse_request_with_trust");
                    mdns_release(trust);
                    err = mStatus_NoMemoryErr;
                    goto exit;
                }
                memcpy(context, domain, len);
                mdns_trust_set_context(trust, context);

                mdns_trust_set_queue(trust, _get_trust_results_dispatch_queue());
                mdns_trust_set_event_handler(trust, ^(mdns_trust_event_t event, mdns_trust_status_t update)
                {
                    if (event == mdns_trust_event_result)
                    {
                        mStatus error = (update != mdns_trust_status_granted) ? mStatus_PolicyDenied : mStatus_NoError;
                        KQueueLock();
                        const char * _domain = mdns_trust_get_context(trust);
                        if (_domain)
                        {
                            if (!error)
                            {
                                error = _handle_browse_request_start(request, _domain);
                                // No context means the request was canceled before we got here
                            }
                            if (error) // (not else if) Always check for error result
                            {
                                _return_browse_request_error(request, error);
                            }
                        }
                        KQueueUnlock("_handle_browse_request_with_trust");
                    }
                });
                request->trust = trust;
                mdns_trust_activate(trust);
                err = mStatus_NoError;
                break;
            }

            case mdns_trust_status_no_entitlement:
                err = mStatus_NoAuth;
                break;

            case mdns_trust_status_granted:
                err = _handle_browse_request_start(request, domain);
                break;

            default:
                err = mStatus_UnknownErr;
                break;
        }
    }
exit:
    return err;
}
#endif // TRUST_ENFORCEMENT

mDNSlocal mStatus handle_browse_request(request_state *request)
{
    // Note that regtype may include a trailing subtype
    char regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
    domainname typedn, temp;
    mDNSs32 NumSubTypes;
    mStatus err = mStatus_NoError;

    DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
    mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
    mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);

    // The browse is scoped to a specific interface index, but the
    // interface is not currently in our list.
    if (interfaceIndex && !InterfaceID)
    {
        // If it's one of the specially defined inteface index values, just return an error.
        if (PreDefinedInterfaceIndex(interfaceIndex))
        {
            LogInfo("handle_browse_request: bad interfaceIndex %d", interfaceIndex);
            return(mStatus_BadParamErr);
        }

        // Otherwise, use the specified interface index value and the browse will
        // be applied to that interface when it comes up.
        InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
        LogInfo("handle_browse_request: browse pending for interface index %d", interfaceIndex);
    }

    if (get_string(&request->msgptr, request->msgend, regtype, sizeof(regtype)) < 0 ||
        get_string(&request->msgptr, request->msgend, domain,  sizeof(domain )) < 0) return(mStatus_BadParamErr);

    if (!request->msgptr) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }

    request->flags = flags;
    request->interfaceIndex = interfaceIndex;
    typedn.c[0] = 0;
    NumSubTypes = ChopSubTypes(regtype);    // Note: Modifies regtype string to remove trailing subtypes
    if (NumSubTypes < 0 || NumSubTypes > 1)
        return(mStatus_BadParamErr);
    if (NumSubTypes == 1)
    {
        if (!AppendDNSNameString(&typedn, regtype + strlen(regtype) + 1))
            return(mStatus_BadParamErr);
    }

    if (!regtype[0] || !AppendDNSNameString(&typedn, regtype)) return(mStatus_BadParamErr);

    if (!MakeDomainNameFromDNSNameString(&temp, regtype)) return(mStatus_BadParamErr);
    // For over-long service types, we only allow domain "local"
    if (temp.c[0] > 15 && domain[0] == 0) mDNSPlatformStrLCopy(domain, "local.", sizeof(domain));

    // Set up browser info
    request->u.browser.ForceMCast = (flags & kDNSServiceFlagsForceMulticast) != 0;
    request->u.browser.interface_id = InterfaceID;
    AssignDomainName(&request->u.browser.regtype, &typedn);
    request->u.browser.default_domain = !domain[0];
    request->u.browser.browsers = NULL;

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[R%d] DNSServiceBrowse(%X, %d, \"" PRI_DM_NAME "\", \"" PRI_S "\") START PID[%d](" PUB_S ")",
           request->request_id, request->flags, interfaceIndex, DM_NAME_PARAM(&request->u.browser.regtype), domain,
           request->process_id, request->pid_name);

    if (request->u.browser.default_domain)
    {
        // Start the domain enumeration queries to discover the WAB browse domains
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
               "[R%d] DNSServiceBrowse Start WAB PID[%d](" PUB_S ")",
               request->request_id, request->process_id, request->pid_name);
        uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
    }
    // We need to unconditionally set request->terminate, because even if we didn't successfully
    // start any browses right now, subsequent configuration changes may cause successful
    // browses to be added, and we'll need to cancel them before freeing this memory.
    request->terminate = NULL;

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
    domainname d;
    if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr);

    if (os_feature_enabled(mDNSResponder, bonjour_privacy) &&
        (request->u.browser.default_domain || IsLocalDomain(&d) || request->u.browser.ForceMCast))
    {
        err = _handle_browse_request_with_trust(request, domain);
    }
    else
    {
        err = _handle_browse_request_start(request, domain);
    }
#else
    err = _handle_browse_request_start(request, domain);
#endif

    return(err);
}

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceResolve
#endif

mDNSlocal void resolve_termination_callback(request_state *request)
{
    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] DNSServiceResolve(%X, %d, \"" PRI_DM_NAME "\") STOP PID[%d](" PUB_S ")",
           request->request_id, request->flags, request->interfaceIndex, DM_NAME_PARAM(&request->u.resolve.qtxt.qname),
           request->process_id, request->pid_name);
    mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qtxt);
    mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
    LogMcastQ(&request->u.resolve.qsrv, request, q_stop);
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
    if (request->u.resolve.external_advertise)
    {
        external_stop_resolving_service(request->u.resolve.qsrv.InterfaceID, &request->u.resolve.qsrv.qname, request->flags, request->process_id);
    }
#endif
}

typedef struct {
    char            regtype[MAX_ESCAPED_DOMAIN_NAME];
    domainname      fqdn;
    mDNSInterfaceID InterfaceID;
} _resolve_start_params_t;

mDNSlocal mStatus _handle_resolve_request_start(request_state *request, const _resolve_start_params_t * const params)
{
    mStatus err;

    err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qsrv);

    if (!err)
    {
        err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qtxt);
        if (err)
        {
            mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
        }
        else
        {
            request->terminate = resolve_termination_callback;
            LogMcastQ(&request->u.resolve.qsrv, request, q_start);
#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
            if (callExternalHelpers(params->InterfaceID, &params->fqdn, request->flags))
            {
                request->u.resolve.external_advertise    = mDNStrue;
                LogInfo("handle_resolve_request: calling external_start_resolving_service()");
                external_start_resolving_service(params->InterfaceID, &params->fqdn, request->flags, request->process_id);
            }
#else
            (void)params;
#endif
        }
    }
    return err;
}

mDNSlocal void resolve_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
{
    size_t len = 0;
    char fullname[MAX_ESCAPED_DOMAIN_NAME], target[MAX_ESCAPED_DOMAIN_NAME] = "0";
    char *data;
    reply_state *rep;
    request_state *req = question->QuestionContext;
    const DNSServiceErrorType error =
        (answer->RecordType == kDNSRecordTypePacketNegative) ? kDNSServiceErr_NoSuchRecord : kDNSServiceErr_NoError;
    (void)m; // Unused

    LogOperation("%3d: DNSServiceResolve(%##s) %s interface %d: %s",
        req->sd, question->qname.c, AddRecord ? "ADD" : "RMV",
        mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));

    if (!AddRecord)
    {
        if (req->u.resolve.srv == answer) req->u.resolve.srv = mDNSNULL;
        if (req->u.resolve.txt == answer) req->u.resolve.txt = mDNSNULL;
        return;
    }

    if (answer->rrtype == kDNSType_SRV) req->u.resolve.srv = answer;
    if (answer->rrtype == kDNSType_TXT) req->u.resolve.txt = answer;

    if (!req->u.resolve.txt || !req->u.resolve.srv) return;     // only deliver result to client if we have both answers

    ConvertDomainNameToCString(answer->name, fullname);

    if (answer->RecordType != kDNSRecordTypePacketNegative)
        ConvertDomainNameToCString(&req->u.resolve.srv->rdata->u.srv.target, target);

    // calculate reply length
    len += sizeof(DNSServiceFlags);
    len += sizeof(mDNSu32);  // interface index
    len += sizeof(DNSServiceErrorType);
    len += strlen(fullname) + 1;
    len += strlen(target) + 1;
    len += 2 * sizeof(mDNSu16);  // port, txtLen
    len += req->u.resolve.txt->rdlength;

    // allocate/init reply header
    rep = create_reply(resolve_reply_op, len, req);
    rep->rhdr->flags = dnssd_htonl(0);
    rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse));
    rep->rhdr->error = dnssd_htonl(error);

    data = (char *)&rep->rhdr[1];

    // write reply data to message
    put_string(fullname, &data);
    put_string(target, &data);
    *data++ =  req->u.resolve.srv->rdata->u.srv.port.b[0];
    *data++ =  req->u.resolve.srv->rdata->u.srv.port.b[1];
    put_uint16(req->u.resolve.txt->rdlength, &data);
    put_rdata (req->u.resolve.txt->rdlength, req->u.resolve.txt->rdata->u.data, &data);

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[R%d->Q%d] DNSServiceResolve(" PRI_S ") RESULT   " PRI_S ":%d",
           req->request_id, mDNSVal16(question->TargetQID), fullname, target,
           mDNSVal16(req->u.resolve.srv->rdata->u.srv.port));
    append_reply(req, rep);
}

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)

mDNSlocal void _return_resolve_request_error(request_state * request, mStatus error)
{
    size_t len;
    char * emptystr = "\0";
    char * data;
    reply_state *rep;

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
       "[R%u] DNSServiceResolve _return_resolve_request_error: error(%d)", request->request_id, error);

    // calculate reply length
    len = sizeof(DNSServiceFlags);
    len += sizeof(mDNSu32);  // interface index
    len += sizeof(DNSServiceErrorType);
    len += 2; // name, target
    len += 2 * sizeof(mDNSu16);  // port, txtLen
    len += 0; //req->u.resolve.txt->rdlength;

    rep = create_reply(resolve_reply_op, len, request);

    rep->rhdr->flags = 0;
    rep->rhdr->ifi   = 0;
    rep->rhdr->error = dnssd_htonl(error);

    data = (char *)&rep->rhdr[1];

    // write reply data to message
    put_string(emptystr, &data); // name
    put_string(emptystr, &data); // target
    put_uint16(0,        &data); // port
    put_uint16(0,        &data); // txtLen

    append_reply(request, rep);
}

mDNSlocal mStatus _handle_resolve_request_with_trust(request_state *request, const _resolve_start_params_t * const params)
{
    mStatus err;
    if (audit_token_to_pid(request->audit_token) == 0)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_WARNING, "[R%u] _handle_resolve_request_with_trust: no audit token for pid(%s %d)", request->request_id, request->pid_name, request->process_id);
        err = _handle_resolve_request_start(request, params);
    }
    else
    {
        mdns_trust_flags_t flags = mdns_trust_flags_none;
        mdns_trust_status_t status = mdns_trust_check_bonjour(request->audit_token, params->regtype, &flags);
        switch (status)
        {
            case mdns_trust_status_denied:
            case mdns_trust_status_pending:
            {
                mdns_trust_t trust = mdns_trust_create(request->audit_token, params->regtype, flags);
                if (!trust )
                {
                    err = mStatus_NoMemoryErr;
                    goto exit;
                }

                void * context = mallocL("context/_handle_resolve_request_with_trust", sizeof(_resolve_start_params_t));
                if (!context)
                {
                    my_perror("ERROR: mallocL context/_handle_resolve_request_with_trust");
                    mdns_release(trust);
                    err = mStatus_NoMemoryErr;
                    goto exit;
                }
                memcpy(context, params, sizeof(_resolve_start_params_t));
                mdns_trust_set_context(trust, context);
                mdns_trust_set_queue(trust, _get_trust_results_dispatch_queue());
                mdns_trust_set_event_handler(trust, ^(mdns_trust_event_t event, mdns_trust_status_t update)
                {
                    if (event == mdns_trust_event_result)
                    {
                        mStatus error = (update != mdns_trust_status_granted) ? mStatus_PolicyDenied : mStatus_NoError;
                        KQueueLock();
                        _resolve_start_params_t * _params =  mdns_trust_get_context(trust);
                        if (_params)
                        {
                            if (!error)
                            {
                                error = _handle_resolve_request_start(request, _params);
                                // No context means the request was canceled before we got here
                            }
                            if (error) // (not else if) Always check for error result
                            {
                                _return_resolve_request_error(request, error);
                            }
                        }
                        KQueueUnlock("_handle_resolve_request_with_trust");
                    }
                });
                request->trust = trust;
                mdns_trust_activate(trust);
                err = mStatus_NoError;
                break;
            }

            case mdns_trust_status_no_entitlement:
                err = mStatus_NoAuth;
                break;

            case mdns_trust_status_granted:
                err = _handle_resolve_request_start(request, params);
                break;

            default:
                err = mStatus_UnknownErr;
                break;
        }
    }
exit:
    return err;
}
#endif // TRUST_ENFORCEMENT

mDNSlocal mStatus handle_resolve_request(request_state *request)
{
    char name[256], domain[MAX_ESCAPED_DOMAIN_NAME];
    _resolve_start_params_t params;
    mStatus err;

    // extract the data from the message
    DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
    mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);

    // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the kDNSServiceFlagsIncludeP2P
    // flag set so that the resolve will run over P2P interfaces that are not yet created.
    if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
    {
        LogOperation("handle_resolve_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
        flags |= kDNSServiceFlagsIncludeP2P;
        interfaceIndex = kDNSServiceInterfaceIndexAny;
    }

    params.InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);

    // The operation is scoped to a specific interface index, but the
    // interface is not currently in our list.
    if (interfaceIndex && !params.InterfaceID)
    {
        // If it's one of the specially defined inteface index values, just return an error.
        if (PreDefinedInterfaceIndex(interfaceIndex))
        {
            LogInfo("handle_resolve_request: bad interfaceIndex %d", interfaceIndex);
            return(mStatus_BadParamErr);
        }

        // Otherwise, use the specified interface index value and the operation will
        // be applied to that interface when it comes up.
        params.InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
        LogInfo("handle_resolve_request: resolve pending for interface index %d", interfaceIndex);
    }

    if (get_string(&request->msgptr, request->msgend, name,           sizeof(name   )) < 0 ||
        get_string(&request->msgptr, request->msgend, params.regtype, sizeof(params.regtype)) < 0 ||
        get_string(&request->msgptr, request->msgend, domain,         sizeof(domain )) < 0)
    { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }

    if (!request->msgptr) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }

    if (build_domainname_from_strings(&params.fqdn, name, params.regtype, domain) < 0)
    { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name, params.regtype, domain); return(mStatus_BadParamErr); }

    mDNSPlatformMemZero(&request->u.resolve, sizeof(request->u.resolve));

#if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
    // Determine if this request should be promoted to use BLE triggered discovery.
    if (shouldUseBLE(InterfaceID, 0, (domainname *)SkipLeadingLabels(&fqdn, 1), &fqdn))
    {
        flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
        LogInfo("handle_resolve_request: request promoted to use kDNSServiceFlagsAutoTrigger");
    }
#endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR

    request->flags = flags;
    request->interfaceIndex = interfaceIndex;

    // format questions
    request->u.resolve.qsrv.InterfaceID      = params.InterfaceID;
    request->u.resolve.qsrv.flags            = flags;
    AssignDomainName(&request->u.resolve.qsrv.qname, &params.fqdn);
    request->u.resolve.qsrv.qtype            = kDNSType_SRV;
    request->u.resolve.qsrv.qclass           = kDNSClass_IN;
    request->u.resolve.qsrv.LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
    request->u.resolve.qsrv.ExpectUnique     = mDNStrue;
    request->u.resolve.qsrv.ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
    request->u.resolve.qsrv.ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
    request->u.resolve.qsrv.SuppressUnusable = mDNSfalse;
    request->u.resolve.qsrv.AppendSearchDomains = 0;
    request->u.resolve.qsrv.TimeoutQuestion  = 0;
    request->u.resolve.qsrv.WakeOnResolve    = (flags & kDNSServiceFlagsWakeOnResolve) != 0;
    request->u.resolve.qsrv.UseBackgroundTraffic = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
    request->u.resolve.qsrv.ProxyQuestion    = 0;
    request->u.resolve.qsrv.pid              = request->process_id;
    request->u.resolve.qsrv.euid             = request->uid;
    request->u.resolve.qsrv.QuestionCallback = resolve_result_callback;
    request->u.resolve.qsrv.QuestionContext  = request;

    request->u.resolve.qtxt.InterfaceID      = params.InterfaceID;
    request->u.resolve.qtxt.flags            = flags;
    AssignDomainName(&request->u.resolve.qtxt.qname, &params.fqdn);
    request->u.resolve.qtxt.qtype            = kDNSType_TXT;
    request->u.resolve.qtxt.qclass           = kDNSClass_IN;
    request->u.resolve.qtxt.LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
    request->u.resolve.qtxt.ExpectUnique     = mDNStrue;
    request->u.resolve.qtxt.ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
    request->u.resolve.qtxt.ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
    request->u.resolve.qtxt.SuppressUnusable = mDNSfalse;
    request->u.resolve.qtxt.AppendSearchDomains = 0;
    request->u.resolve.qtxt.TimeoutQuestion  = 0;
    request->u.resolve.qtxt.WakeOnResolve    = 0;
    request->u.resolve.qtxt.UseBackgroundTraffic = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
    request->u.resolve.qtxt.ProxyQuestion    = 0;
    request->u.resolve.qtxt.pid              = request->process_id;
    request->u.resolve.qtxt.euid             = request->uid;
    request->u.resolve.qtxt.QuestionCallback = resolve_result_callback;
    request->u.resolve.qtxt.QuestionContext  = request;

    request->u.resolve.ReportTime            = NonZeroTime(mDNS_TimeNow(&mDNSStorage) + 130 * mDNSPlatformOneSecond);

    request->u.resolve.external_advertise    = mDNSfalse;

#if 0
    if (!AuthorizedDomain(request, &fqdn, AutoBrowseDomains)) return(mStatus_NoError);
#endif

    // ask the questions
    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] DNSServiceResolve(%X, %d, \"" PRI_DM_NAME "\") START PID[%d](" PUB_S ")",
           request->request_id, flags, interfaceIndex, DM_NAME_PARAM(&request->u.resolve.qsrv.qname),
           request->process_id, request->pid_name);

    request->terminate = NULL;
#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
    domainname d;
    if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr);

    if (os_feature_enabled(mDNSResponder, bonjour_privacy) &&
        (IsLocalDomain(&d) || request->u.resolve.qsrv.ForceMCast))
    {
        err = _handle_resolve_request_with_trust(request, &params);
    }
    else
    {
        err = _handle_resolve_request_start(request, &params);
    }
#else
    err = _handle_resolve_request_start(request, &params);
#endif

    return(err);
}

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceQueryRecord
#endif

mDNSlocal void queryrecord_result_reply(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord, DNSServiceErrorType error, void *context)
{
    char name[MAX_ESCAPED_DOMAIN_NAME];
    size_t len;
    DNSServiceFlags flags = 0;
    reply_state *rep;
    char *data;
    request_state *req = (request_state *)context;
    const char *dnssec_result_description = "";

    ConvertDomainNameToCString(answer->name, name);

#if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
    if (question->DNSSECStatus.enable_dnssec) {
        if (answer->dnssec_result == dnssec_secure)
        {
            flags |= kDNSServiceFlagsSecure;
            dnssec_result_description = ", DNSSEC_Secure";
        }
        else if (answer->dnssec_result == dnssec_insecure)
        {
            flags |= kDNSServiceFlagsInsecure;
            dnssec_result_description = ", DNSSEC_Insecure";
        }
        else if (answer->dnssec_result == dnssec_bogus)
        {
            flags |= kDNSServiceFlagsBogus;
            dnssec_result_description = ", DNSSEC_Bogus";
        }
        else if (answer->dnssec_result == dnssec_indeterminate)
        {
            flags |= kDNSServiceFlagsIndeterminate;
            dnssec_result_description = ", DNSSEC_Indeterminate";
        }
    } else if (question->DNSSECStatus.tried_dnssec_but_unsigned) {
        // handle the case where we restart the question without the DNSSEC while the user requires DNSSEC result, for
        // some reason we failed to get DNSSEC records. In which case, even if we go back to normal query, we should pass
        // the DNSSEC result
        flags |= kDNSServiceFlagsInsecure;
        dnssec_result_description = ", DNSSEC_Insecure";
    }
#endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
       "[R%u->Q%u] DNSService" PUB_S "(" PRI_DM_NAME ", " PUB_S ") RESULT " PUB_S " interface %d: (" PUB_S PUB_S ")" PRI_S,
       req->request_id, mDNSVal16(question->TargetQID), req->hdr.op == query_request ? "QueryRecord" : "GetAddrInfo",
       DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV",
       mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse),
       MortalityDisplayString(answer->mortality), dnssec_result_description, RRDisplayString(m, answer));

    len = sizeof(DNSServiceFlags);  // calculate reply data length
    len += sizeof(mDNSu32);     // interface index
    len += sizeof(DNSServiceErrorType);
    len += strlen(name) + 1;
    len += 3 * sizeof(mDNSu16); // type, class, rdlen
    len += answer->rdlength;
    len += sizeof(mDNSu32);     // TTL

    rep = create_reply(req->hdr.op == query_request ? query_reply_op : addrinfo_reply_op, len, req);

    if (AddRecord)
        flags |= kDNSServiceFlagsAdd;
    if (answer->mortality == Mortality_Ghost)
        flags |= kDNSServiceFlagsExpiredAnswer;
    if (!question->InitialCacheMiss)
        flags |= kDNSServiceFlagAnsweredFromCache;

    rep->rhdr->flags = dnssd_htonl(flags);
    // Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
    // InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
    // to be stopped and started including  *this* one. Normally the InterfaceID is valid. But when we
    // are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
    // mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
    // mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
    // should not have existed to answer this question if the corresponding interface is not valid.
    rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNStrue));
    rep->rhdr->error = dnssd_htonl(error);

    data = (char *)&rep->rhdr[1];

    put_string(name,             &data);
    put_uint16(answer->rrtype,   &data);
    put_uint16(answer->rrclass,  &data);
    put_uint16(answer->rdlength, &data);
    // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
    // function just does a blind memory copy without regard to structures that may have holes in them.
    if (answer->rdlength)
        if (!putRData(mDNSNULL, (mDNSu8 *)data, (mDNSu8 *)rep->rhdr + len, answer))
            LogMsg("queryrecord_result_reply putRData failed %d", (mDNSu8 *)rep->rhdr + len - (mDNSu8 *)data);
    data += answer->rdlength;
    put_uint32(AddRecord ? answer->rroriginalttl : 0, &data);

    append_reply(req, rep);
}

mDNSlocal void queryrecord_termination_callback(request_state *request)
{
    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%u] DNSServiceQueryRecord(%X, %d, " PRI_DM_NAME ", " PUB_S ") STOP PID[%d](" PUB_S ")",
           request->request_id, request->flags, request->interfaceIndex,
           DM_NAME_PARAM(QueryRecordClientRequestGetQName(&request->u.queryrecord)),
           DNSTypeName(QueryRecordClientRequestGetType(&request->u.queryrecord)), request->process_id, request->pid_name);

    QueryRecordClientRequestStop(&request->u.queryrecord);
}

typedef struct {
    char            qname[MAX_ESCAPED_DOMAIN_NAME];
    mDNSu32         interfaceIndex;
    DNSServiceFlags flags;
    mDNSu16         qtype;
    mDNSu16         qclass;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    mDNSBool        require_privacy;
#endif
} _queryrecord_start_params_t;

#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) && MDNSRESPONDER_SUPPORTS(APPLE, IPC_TLV)
mDNSlocal const mDNSu8 * ipc_tlv_get_resolver_config_plist_data(const mDNSu8 *const start, const mDNSu8 *const end,
    size_t *outLen)
{
    size_t len = 0;
    const mDNSu8 *value = NULL;
    mdns_tlv16_get_value(start, end, IPC_TLV_TYPE_RESOLVER_CONFIG_PLIST_DATA, &len, &value, NULL);
    if (outLen)
    {
        *outLen = len;
    }
    return value;
}

mDNSlocal mDNSBool ipc_tlv_get_require_privacy(const mDNSu8 *const start, const mDNSu8 *const end)
{
    size_t len = 0;
    const mDNSu8 *value = NULL;
    mdns_tlv16_get_value(start, end, IPC_TLV_TYPE_REQUIRE_PRIVACY, &len, &value, NULL);
    return ((len == 1) && (*value != 0)) ? mDNStrue : mDNSfalse;
}
#endif

mDNSlocal mStatus _handle_queryrecord_request_start(request_state *request, const _queryrecord_start_params_t * const params)
{
    mStatus err;

    request->terminate = queryrecord_termination_callback;

    QueryRecordClientRequestParams queryParams;
    QueryRecordClientRequestParamsInit(&queryParams);
    queryParams.requestID      = request->request_id;
    queryParams.qnameStr       = params->qname;
    queryParams.interfaceIndex = params->interfaceIndex;
    queryParams.flags          = params->flags;
    queryParams.qtype          = params->qtype;
    queryParams.qclass         = params->qclass;
    queryParams.effectivePID   = request->validUUID ? 0 : request->process_id;
    queryParams.effectiveUUID  = request->validUUID ? request->uuid : mDNSNULL;
    queryParams.peerUID        = request->uid;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    queryParams.needEncryption = params->require_privacy ? mDNStrue : mDNSfalse;
    queryParams.customID       = request->custom_service_id;
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    queryParams.peerAuditToken = &request->audit_token;
#endif
    err = QueryRecordClientRequestStart(&request->u.queryrecord, &queryParams, queryrecord_result_reply, request);
    return err;
}

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)

mDNSlocal void _return_queryrecord_request_error(request_state * request, mStatus error)
{
    size_t len;
    char * emptystr = "\0";
    char * data;
    reply_state *rep;

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
       "[R%u] DNSService" PUB_S " _return_queryrecord_request_error: error(%d)",
       request->request_id, request->hdr.op == query_request ? "QueryRecord" : "GetAddrInfo", error);

    len = sizeof(DNSServiceFlags);  // calculate reply data length
    len += sizeof(mDNSu32);     // interface index
    len += sizeof(DNSServiceErrorType);
    len += strlen(emptystr) + 1;
    len += 3 * sizeof(mDNSu16); // type, class, rdlen
    len += 0;//answer->rdlength;
    len += sizeof(mDNSu32);     // TTL

    rep = create_reply(request->hdr.op == query_request ? query_reply_op : addrinfo_reply_op, len, request);

    rep->rhdr->flags = 0;
    rep->rhdr->ifi   = 0;
    rep->rhdr->error = dnssd_htonl(error);

    data = (char *)&rep->rhdr[1];

    put_string(emptystr,    &data);
    put_uint16(0,           &data);
    put_uint16(0,           &data);
    put_uint16(0,           &data);
    data += 0;
    put_uint32(0,           &data);

    append_reply(request, rep);
}

mDNSlocal mStatus _handle_queryrecord_request_with_trust(request_state *request, const _queryrecord_start_params_t * const params)
{
    mStatus err;
    if (audit_token_to_pid(request->audit_token) == 0)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_WARNING, "[R%u] _handle_queryrecord_request_with_trust: no audit token for pid(%s %d)", request->request_id, request->pid_name, request->process_id);
        err = _handle_queryrecord_request_start(request, params);
    }
    else
    {
        const char *service_ptr = NULL;
        char type_str[MAX_ESCAPED_DOMAIN_NAME] = "";
        domainname query_name;
        if (MakeDomainNameFromDNSNameString(&query_name, params->qname))
        {
            domainlabel name;
            domainname type, domain;
            bool good = DeconstructServiceName(&query_name, &name, &type, &domain);
            if (good)
            {
                ConvertDomainNameToCString(&type, type_str);
                service_ptr = type_str;
            }
        }

        mdns_trust_flags_t flags = mdns_trust_flags_none;
        mdns_trust_status_t status = mdns_trust_check_query(request->audit_token, params->qname, service_ptr, params->qtype, (params->flags & kDNSServiceFlagsForceMulticast) != 0, &flags);
        switch (status)
        {
            case mdns_trust_status_denied:
            case mdns_trust_status_pending:
            {
                mdns_trust_t trust = mdns_trust_create(request->audit_token, service_ptr, flags);
                if (!trust )
                {
                    err = mStatus_NoMemoryErr;
                    goto exit;
                }

                void * context = mallocL("context/_handle_queryrecord_request_with_trust", sizeof(_queryrecord_start_params_t));
                if (!context)
                {
                    my_perror("ERROR: mallocL context/_handle_queryrecord_request_with_trust");
                    mdns_release(trust);
                    err = mStatus_NoMemoryErr;
                    goto exit;
                }
                memcpy(context, params, sizeof(_queryrecord_start_params_t));
                mdns_trust_set_context(trust, context);
                mdns_trust_set_queue(trust, _get_trust_results_dispatch_queue());
                mdns_trust_set_event_handler(trust, ^(mdns_trust_event_t event, mdns_trust_status_t update)
                {
                    if (event == mdns_trust_event_result)
                    {
                        mStatus error = (update != mdns_trust_status_granted) ? mStatus_PolicyDenied : mStatus_NoError;
                        KQueueLock();
                        _queryrecord_start_params_t * _params =  mdns_trust_get_context(trust);
                        if (_params)
                        {
                            if (!error)
                            {
                                error = _handle_queryrecord_request_start(request, _params);
                                // No context means the request was canceled before we got here
                            }
                            if (error) // (not else if) Always check for error result
                            {
                                _return_queryrecord_request_error(request, error);
                            }
                        }
                        KQueueUnlock("_handle_queryrecord_request_with_trust");
                    }
                });
                request->trust = trust;
                mdns_trust_activate(trust);
                err = mStatus_NoError;
                break;
            }

            case mdns_trust_status_no_entitlement:
                err = mStatus_NoAuth;
                break;

            case mdns_trust_status_granted:
                err = _handle_queryrecord_request_start(request, params);
                break;

            default:
                err = mStatus_UnknownErr;
                break;
        }
    }
exit:
    return err;
}
#endif // TRUST_ENFORCEMENT

mDNSlocal mStatus handle_queryrecord_request(request_state *request)
{
    mStatus err;
    _queryrecord_start_params_t params;

    params.flags           = get_flags(&request->msgptr, request->msgend);
    params.interfaceIndex  = get_uint32(&request->msgptr, request->msgend);
    if (get_string(&request->msgptr, request->msgend, params.qname, sizeof(params.qname)) < 0)
    {
        err = mStatus_BadParamErr;
        goto exit;
    }
    params.qtype           = get_uint16(&request->msgptr, request->msgend);
    params.qclass          = get_uint16(&request->msgptr, request->msgend);

    if (!request->msgptr)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%d] DNSServiceQueryRecord(unreadable parameters)", request->request_id);
        err = mStatus_BadParamErr;
        goto exit;
    }
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    params.require_privacy = mDNSfalse;
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) && MDNSRESPONDER_SUPPORTS(APPLE, IPC_TLV)
    if (request->msgptr && (request->hdr.ipc_flags & IPC_FLAGS_TRAILING_TLVS))
    {
        size_t len;
        const mDNSu8 *const start = (const mDNSu8 *)request->msgptr;
        const mDNSu8 *const end = (const mDNSu8 *)request->msgend;
        const mDNSu8 *const data = ipc_tlv_get_resolver_config_plist_data(start, end, &len);
        if (data)
        {
            request->custom_service_id = Querier_RegisterCustomDNSServiceWithPListData(data, len);
        }
        params.require_privacy = ipc_tlv_get_require_privacy(start, end);
    }
#endif
    request->flags          = params.flags;
    request->interfaceIndex = params.interfaceIndex;

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] DNSServiceQueryRecord(%X, %d, " PRI_S ", " PUB_S ") START PID[%d](" PUB_S ")",
           request->request_id, request->flags, request->interfaceIndex, params.qname, DNSTypeName(params.qtype), request->process_id,
           request->pid_name);

    mDNSPlatformMemZero(&request->u.queryrecord, (mDNSu32)sizeof(request->u.queryrecord));
    request->terminate = NULL;

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
    if (os_feature_enabled(mDNSResponder, bonjour_privacy))
    {
        err = _handle_queryrecord_request_with_trust(request, &params);
    }
    else
    {
        err = _handle_queryrecord_request_start(request, &params);
    }
#else
    err = _handle_queryrecord_request_start(request, &params);
#endif

exit:
    return(err);
}

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceEnumerateDomains
#endif

mDNSlocal reply_state *format_enumeration_reply(request_state *request,
                                                const char *domain, DNSServiceFlags flags, mDNSu32 ifi, DNSServiceErrorType err)
{
    size_t len;
    reply_state *reply;
    char *data;

    len = sizeof(DNSServiceFlags);
    len += sizeof(mDNSu32);
    len += sizeof(DNSServiceErrorType);
    len += strlen(domain) + 1;

    reply = create_reply(enumeration_reply_op, len, request);
    reply->rhdr->flags = dnssd_htonl(flags);
    reply->rhdr->ifi   = dnssd_htonl(ifi);
    reply->rhdr->error = dnssd_htonl(err);
    data = (char *)&reply->rhdr[1];
    put_string(domain, &data);
    return reply;
}

mDNSlocal void enum_termination_callback(request_state *request)
{
    // Stop the domain enumeration queries to discover the WAB Browse/Registration domains
    if (request->u.enumeration.flags & kDNSServiceFlagsRegistrationDomains)
    {
        LogInfo("%3d: DNSServiceEnumeration Cancel WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
        uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
    }
    else
    {
        LogInfo("%3d: DNSServiceEnumeration Cancel WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
        uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY | UDNS_WAB_LBROWSE_QUERY);
        mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_autoall);
    }
    mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
    mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
}

mDNSlocal void enum_result_callback(mDNS *const m,
                                    DNSQuestion *const question, const ResourceRecord *const answer, QC_result AddRecord)
{
    char domain[MAX_ESCAPED_DOMAIN_NAME];
    request_state *request = question->QuestionContext;
    DNSServiceFlags flags = 0;
    reply_state *reply;
    (void)m; // Unused

    if (answer->rrtype != kDNSType_PTR) return;

#if 0
    if (!AuthorizedDomain(request, &answer->rdata->u.name, request->u.enumeration.flags ? AutoRegistrationDomains : AutoBrowseDomains)) return;
#endif

    // We only return add/remove events for the browse and registration lists
    // For the default browse and registration answers, we only give an "ADD" event
    if (question == &request->u.enumeration.q_default && !AddRecord) return;

    if (AddRecord)
    {
        flags |= kDNSServiceFlagsAdd;
        if (question == &request->u.enumeration.q_default) flags |= kDNSServiceFlagsDefault;
    }

    ConvertDomainNameToCString(&answer->rdata->u.name, domain);
    // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
    // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
    // network, so we just pass kDNSServiceInterfaceIndexAny
    reply = format_enumeration_reply(request, domain, flags, kDNSServiceInterfaceIndexAny, kDNSServiceErr_NoError);
    if (!reply) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d->Q%d] DNSServiceEnumerateDomains(%2.*s) RESULT " PUB_S ": " PRI_S,
           request->request_id, mDNSVal16(question->TargetQID), question->qname.c[0], &question->qname.c[1],
           AddRecord ? "ADD" : "RMV", domain);

    append_reply(request, reply);
}

mDNSlocal mStatus handle_enum_request(request_state *request)
{
    mStatus err;
    DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
    DNSServiceFlags reg = flags & kDNSServiceFlagsRegistrationDomains;
    mDNS_DomainType t_all     = reg ? mDNS_DomainTypeRegistration        : mDNS_DomainTypeBrowse;
    mDNS_DomainType t_default = reg ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
    mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
    mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
    if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);

    if (!request->msgptr)
    { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }

    request->flags = flags;
    request->interfaceIndex = interfaceIndex;

    // mark which kind of enumeration we're doing so that we know what domain enumeration queries to stop
    request->u.enumeration.flags = reg;

    // enumeration requires multiple questions, so we must link all the context pointers so that
    // necessary context can be reached from the callbacks
    request->u.enumeration.q_all.QuestionContext = request;
    request->u.enumeration.q_default.QuestionContext = request;
    if (!reg) request->u.enumeration.q_autoall.QuestionContext = request;

    // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
    if (!InterfaceID) InterfaceID = mDNSInterface_LocalOnly;

    // make the calls
    LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request->sd, flags,
                 (flags & kDNSServiceFlagsBrowseDomains      ) ? "kDNSServiceFlagsBrowseDomains" :
                 (flags & kDNSServiceFlagsRegistrationDomains) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
    err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_all, t_all, NULL, InterfaceID, enum_result_callback, request);
    if (!err)
    {
        err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_default, t_default, NULL, InterfaceID, enum_result_callback, request);
        if (err) mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
        else if (!reg)
        {
            err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_autoall, mDNS_DomainTypeBrowseAutomatic, NULL, InterfaceID, enum_result_callback, request);
            if (err)
            {
                mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
                mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
            }
        }
        if (!err) request->terminate = enum_termination_callback;
    }
    if (!err)
    {
        // Start the domain enumeration queries to discover the WAB Browse/Registration domains
        if (reg)
        {
            LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
            uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
        }
        else
        {
            LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
            uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY | UDNS_WAB_LBROWSE_QUERY);
        }
    }

    return(err);
}

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceReconfirmRecord & Misc
#endif

mDNSlocal mStatus handle_reconfirm_request(request_state *request)
{
    mStatus status = mStatus_BadParamErr;
    AuthRecord *rr = read_rr_from_ipc_msg(request, 0, 0);
    if (rr)
    {
        status = mDNS_ReconfirmByValue(&mDNSStorage, &rr->resrec);
        LogOperation(
            (status == mStatus_NoError) ?
            "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated PID[%d](%s)" :
            "%3d: DNSServiceReconfirmRecord(%s) interface %d failed PID[%d](%s) status %d",
            request->sd, RRDisplayString(&mDNSStorage, &rr->resrec),
            mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, rr->resrec.InterfaceID, mDNSfalse),
            request->process_id, request->pid_name, status);
        freeL("AuthRecord/handle_reconfirm_request", rr);
    }
    return(status);
}

#if APPLE_OSX_mDNSResponder

mDNSlocal mStatus handle_release_request(request_state *request)
{
    mStatus err = 0;
    char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
    domainname instance;

    // extract the data from the message
    DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);

    if (get_string(&request->msgptr, request->msgend, name,    sizeof(name   )) < 0 ||
        get_string(&request->msgptr, request->msgend, regtype, sizeof(regtype)) < 0 ||
        get_string(&request->msgptr, request->msgend, domain,  sizeof(domain )) < 0)
    {
        LogMsg("ERROR: handle_release_request - Couldn't read name/regtype/domain");
        return(mStatus_BadParamErr);
    }

    if (!request->msgptr)
    {
        LogMsg("%3d: PeerConnectionRelease(unreadable parameters)", request->sd);
        return(mStatus_BadParamErr);
    }

    if (build_domainname_from_strings(&instance, name, regtype, domain) < 0)
    {
        LogMsg("ERROR: handle_release_request bad “%s” “%s” “%s”", name, regtype, domain);
        return(mStatus_BadParamErr);
    }

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] PeerConnectionRelease(%X " PRI_DM_NAME ") START PID[%d](" PUB_S ")",
           request->request_id, flags, DM_NAME_PARAM(&instance), request->process_id, request->pid_name);

#if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
    external_connection_release(&instance);
#endif
    return(err);
}

#else   // APPLE_OSX_mDNSResponder

mDNSlocal mStatus handle_release_request(request_state *request)
{
    (void) request;
    return mStatus_UnsupportedErr;
}

#endif  // APPLE_OSX_mDNSResponder

mDNSlocal mStatus handle_setdomain_request(request_state *request)
{
    char domainstr[MAX_ESCAPED_DOMAIN_NAME];
    domainname domain;
    DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
    (void)flags; // Unused
    if (get_string(&request->msgptr, request->msgend, domainstr, sizeof(domainstr)) < 0 ||
        !MakeDomainNameFromDNSNameString(&domain, domainstr))
    { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }

    LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request->sd, domain.c);
    return(mStatus_NoError);
}

typedef packedstruct
{
    mStatus err;
    mDNSu32 len;
    mDNSu32 vers;
} DaemonVersionReply;

mDNSlocal void handle_getproperty_request(request_state *request)
{
    const mStatus BadParamErr = dnssd_htonl((mDNSu32)mStatus_BadParamErr);
    char prop[256];
    if (get_string(&request->msgptr, request->msgend, prop, sizeof(prop)) >= 0)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
               "[R%d] DNSServiceGetProperty(" PUB_S ")", request->request_id, prop);
        if (!strcmp(prop, kDNSServiceProperty_DaemonVersion))
        {
            DaemonVersionReply x = { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H) };
            send_all(request->sd, (const char *)&x, sizeof(x));
            return;
        }
    }

    // If we didn't recogize the requested property name, return BadParamErr
    send_all(request->sd, (const char *)&BadParamErr, sizeof(BadParamErr));
}

#ifdef APPLE_OSX_mDNSResponder
// The caller can specify either the pid or the uuid. If the pid is not specified,
// update the effective uuid. Don't overwrite the pid which is used for debugging
// purposes and initialized when the socket is opened.
mDNSlocal void handle_connection_delegate_request(request_state *request)
{
    mDNSs32 pid;
    socklen_t len;

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] DNSServiceCreateDelegateConnection START PID[%d](" PUB_S  ")",
           request->request_id, request->process_id, request->pid_name);
    request->terminate = connection_termination;

    len = 0;
    pid = get_uint32(&request->msgptr, request->msgend);
#ifdef LOCAL_PEEREPID
    if (pid)
    {
        len = sizeof(pid);
        if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREPID, &request->process_id, &len) != 0)
        {
            LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREPID failed errno:%d / %s", errno, strerror(errno));
            return;
        }
        // to extract the process name from the pid value
        if (proc_pidinfo(request->process_id, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
            return;
        mDNSPlatformStrLCopy(request->pid_name, proc.pbsi_comm, sizeof(request->pid_name));
        debugf("handle_connection_delegate_request: process id %d, name %s", request->process_id, request->pid_name);
    }
#endif
#ifdef LOCAL_PEEREUUID
    if (!pid)
    {
        len = UUID_SIZE;
        if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREUUID, request->uuid, &len) != 0)
        {
            LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREUUID failed errno:%d / %s", errno, strerror(errno));
            return;
        }
        request->validUUID = mDNStrue;
    }
#endif
}
#else
mDNSlocal void handle_connection_delegate_request(request_state *request)
{
    (void) request;
}
#endif

typedef packedstruct
{
    mStatus err;
    mDNSs32 pid;
} PIDInfo;

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceNATPortMappingCreate
#endif

#define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)

mDNSlocal void port_mapping_termination_callback(request_state *request)
{
    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[R%d] DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP PID[%d](" PUB_S ")",
           request->request_id, DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
           mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
           request->process_id, request->pid_name);

    mDNS_StopNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
}

// Called via function pointer when we get a NAT Traversal (address request or port mapping) response
mDNSlocal void port_mapping_create_request_callback(mDNS *m, NATTraversalInfo *n)
{
    request_state *request = (request_state *)n->clientContext;
    reply_state *rep;
    int replyLen;
    char *data;

    if (!request) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }

    // calculate reply data length
    replyLen = sizeof(DNSServiceFlags);
    replyLen += 3 * sizeof(mDNSu32);  // if index + addr + ttl
    replyLen += sizeof(DNSServiceErrorType);
    replyLen += 2 * sizeof(mDNSu16);  // Internal Port + External Port
    replyLen += sizeof(mDNSu8);       // protocol

    rep = create_reply(port_mapping_reply_op, replyLen, request);

    rep->rhdr->flags = dnssd_htonl(0);
    rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, n->InterfaceID, mDNSfalse));
    rep->rhdr->error = dnssd_htonl(n->Result);

    data = (char *)&rep->rhdr[1];

    *data++ = request->u.pm.NATinfo.ExternalAddress.b[0];
    *data++ = request->u.pm.NATinfo.ExternalAddress.b[1];
    *data++ = request->u.pm.NATinfo.ExternalAddress.b[2];
    *data++ = request->u.pm.NATinfo.ExternalAddress.b[3];
    *data++ = DNSServiceProtocol(request->u.pm.NATinfo.Protocol);
    *data++ = request->u.pm.NATinfo.IntPort.b[0];
    *data++ = request->u.pm.NATinfo.IntPort.b[1];
    *data++ = request->u.pm.NATinfo.ExternalPort.b[0];
    *data++ = request->u.pm.NATinfo.ExternalPort.b[1];
    put_uint32(request->u.pm.NATinfo.Lifetime, &data);

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT " PRI_IPv4_ADDR ":%u TTL %u",
           request->request_id, DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
           mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
           &request->u.pm.NATinfo.ExternalAddress, mDNSVal16(request->u.pm.NATinfo.ExternalPort),
           request->u.pm.NATinfo.Lifetime);

    append_reply(request, rep);
}

mDNSlocal mStatus handle_port_mapping_request(request_state *request)
{
    mDNSu32 ttl = 0;
    mStatus err = mStatus_NoError;

    DNSServiceFlags flags          = get_flags(&request->msgptr, request->msgend);
    mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
    mDNSInterfaceID InterfaceID    = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
    mDNSu8 protocol       = (mDNSu8)get_uint32(&request->msgptr, request->msgend);
    (void)flags; // Unused
    if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
    if (request->msgptr + 8 > request->msgend) request->msgptr = NULL;
    else
    {
        request->u.pm.NATinfo.IntPort.b[0] = *request->msgptr++;
        request->u.pm.NATinfo.IntPort.b[1] = *request->msgptr++;
        request->u.pm.ReqExt.b[0]          = *request->msgptr++;
        request->u.pm.ReqExt.b[1]          = *request->msgptr++;
        ttl = get_uint32(&request->msgptr, request->msgend);
    }

    if (!request->msgptr)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
               "[R%d] DNSServiceNATPortMappingCreate(unreadable parameters)", request->request_id);
        return(mStatus_BadParamErr);
    }

    if (protocol == 0)  // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
    {
        if (!mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort) || !mDNSIPPortIsZero(request->u.pm.ReqExt) || ttl) return(mStatus_BadParamErr);
    }
    else
    {
        if (mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort)) return(mStatus_BadParamErr);
        if (!(protocol & (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP))) return(mStatus_BadParamErr);
    }

    request->flags                       = flags;
    request->interfaceIndex              = interfaceIndex;
    request->u.pm.NATinfo.Protocol       = !protocol ? NATOp_AddrRequest : (protocol == kDNSServiceProtocol_UDP) ? NATOp_MapUDP : NATOp_MapTCP;
    //       u.pm.NATinfo.IntPort        = already set above
    request->u.pm.NATinfo.RequestedPort  = request->u.pm.ReqExt;
    request->u.pm.NATinfo.NATLease       = ttl;
    request->u.pm.NATinfo.clientCallback = port_mapping_create_request_callback;
    request->u.pm.NATinfo.clientContext  = request;

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%d] DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START PID[%d](" PUB_S ")",
           request->request_id, protocol, mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt),
           request->u.pm.NATinfo.NATLease, request->process_id, request->pid_name);
    err = mDNS_StartNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
    if (err) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err);
    else request->terminate = port_mapping_termination_callback;

    return(err);
}

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceGetAddrInfo
#endif

mDNSlocal void addrinfo_termination_callback(request_state *request)
{
    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%u] DNSServiceGetAddrInfo(" PRI_DM_NAME ") STOP PID[%d](" PUB_S ")",
           request->request_id, DM_NAME_PARAM(GetAddrInfoClientRequestGetQName(&request->u.addrinfo)),
           request->process_id, request->pid_name);

    GetAddrInfoClientRequestStop(&request->u.addrinfo);
}

typedef struct {
    mDNSu32     protocols;
    char        hostname[MAX_ESCAPED_DOMAIN_NAME];
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    mDNSBool    require_privacy;
#endif
} _addrinfo_start_params_t;

mDNSlocal mStatus _handle_addrinfo_request_start(request_state *request, const _addrinfo_start_params_t * const params)
{
    mStatus err;

    request->terminate = addrinfo_termination_callback;

    GetAddrInfoClientRequestParams gaiParams;
    GetAddrInfoClientRequestParamsInit(&gaiParams);
    gaiParams.requestID      = request->request_id;
    gaiParams.hostnameStr    = params->hostname;
    gaiParams.interfaceIndex = request->interfaceIndex;
    gaiParams.flags          = request->flags;
    gaiParams.protocols      = params->protocols;
    gaiParams.effectivePID   = request->validUUID ? 0 : request->process_id;
    gaiParams.effectiveUUID  = request->validUUID ? request->uuid : mDNSNULL;
    gaiParams.peerUID        = request->uid;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    gaiParams.needEncryption = params->require_privacy ? mDNStrue : mDNSfalse;
    gaiParams.customID       = request->custom_service_id;
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    gaiParams.peerAuditToken = &request->audit_token;
#endif
    err = GetAddrInfoClientRequestStart(&request->u.addrinfo, &gaiParams, queryrecord_result_reply, request);

    return err;
}

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)

mDNSlocal void _return_addrinfo_request_error(request_state * request, mStatus error)
{
    _return_queryrecord_request_error(request, error);
}

mDNSlocal mStatus _handle_addrinfo_request_with_trust(request_state *request, const _addrinfo_start_params_t * const params)
{
    mStatus err;
    if (audit_token_to_pid(request->audit_token) == 0)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_WARNING, "[R%u] _handle_addrinfo_request_with_trust: no audit token for pid(%s %d)", request->request_id, request->pid_name, request->process_id);
        err = _handle_addrinfo_request_start(request, params);
    }
    else
    {
        mdns_trust_flags_t flags = mdns_trust_flags_none;
        mdns_trust_status_t status = mdns_trust_check_getaddrinfo(request->audit_token, params->hostname, &flags);
        switch (status)
        {
            case mdns_trust_status_denied:
            case mdns_trust_status_pending:
            {
                mdns_trust_t trust = mdns_trust_create(request->audit_token, NULL, flags);
                if (!trust )
                {
                    err = mStatus_NoMemoryErr;
                    goto exit;
                }

                void * context = mallocL("context/_handle_addrinfo_request_with_trust", sizeof(_addrinfo_start_params_t));
                if (!context)
                {
                    my_perror("ERROR: mallocL context/_handle_addrinfo_request_with_trust");
                    mdns_release(trust);
                    err = mStatus_NoMemoryErr;
                    goto exit;
                }
                memcpy(context, params, sizeof(_addrinfo_start_params_t));
                mdns_trust_set_context(trust, context);
                mdns_trust_set_queue(trust, _get_trust_results_dispatch_queue());
                mdns_trust_set_event_handler(trust, ^(mdns_trust_event_t event, mdns_trust_status_t update)
                {
                    if (event == mdns_trust_event_result)
                    {
                        mStatus error = (update != mdns_trust_status_granted) ? mStatus_PolicyDenied : mStatus_NoError;
                        KQueueLock();
                        _addrinfo_start_params_t * _params =  mdns_trust_get_context(trust);
                        if (_params)
                        {
                            if (!error)
                            {
                                error = _handle_addrinfo_request_start(request, _params);
                                // No context means the request was canceled before we got here
                            }
                            if (error) // (not else if) Always check for error result
                            {
                                _return_addrinfo_request_error(request, error);
                            }
                        }
                        KQueueUnlock("_handle_addrinfo_request_with_trust");
                    }
                });
                request->trust = trust;
                mdns_trust_activate(trust);
                err = mStatus_NoError;
                break;
            }

            case mdns_trust_status_no_entitlement:
                err = mStatus_NoAuth;
                break;

            case mdns_trust_status_granted:
                err = _handle_addrinfo_request_start(request, params);
                break;

            default:
                err = mStatus_UnknownErr;
                break;
        }
    }
exit:
    return err;
}
#endif // TRUST_ENFORCEMENT

mDNSlocal mStatus handle_addrinfo_request(request_state *request)
{
    mStatus             err;
    DNSServiceFlags     flags;
    mDNSu32             interfaceIndex;
    _addrinfo_start_params_t params;

    flags               = get_flags(&request->msgptr, request->msgend);
    interfaceIndex      = get_uint32(&request->msgptr, request->msgend);
    params.protocols    = get_uint32(&request->msgptr, request->msgend);
    if (get_string(&request->msgptr, request->msgend, params.hostname, sizeof(params.hostname)) < 0)
    {
        err = mStatus_BadParamErr;
        goto exit;
    }
    if (!request->msgptr)
    {
        LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request->sd);
        err = mStatus_BadParamErr;
        goto exit;
    }
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    params.require_privacy = mDNSfalse;
#endif
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) && MDNSRESPONDER_SUPPORTS(APPLE, IPC_TLV)
    if (request->msgptr && (request->hdr.ipc_flags & IPC_FLAGS_TRAILING_TLVS))
    {
        size_t len;
        const mDNSu8 *const start = (const mDNSu8 *)request->msgptr;
        const mDNSu8 *const end = (const mDNSu8 *)request->msgend;
        const mDNSu8 *const data = ipc_tlv_get_resolver_config_plist_data(start, end, &len);
        if (data)
        {
            request->custom_service_id = Querier_RegisterCustomDNSServiceWithPListData(data, len);
        }
        params.require_privacy = ipc_tlv_get_require_privacy(start, end);
    }
#endif
    request->flags          = flags;
    request->interfaceIndex = interfaceIndex;

    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
           "[R%u] DNSServiceGetAddrInfo(%X, %d, %u, " PRI_S ") START PID[%d](" PUB_S ")",
           request->request_id, request->flags, request->interfaceIndex, params.protocols, params.hostname, request->process_id,
           request->pid_name);

    mDNSPlatformMemZero(&request->u.addrinfo, (mDNSu32)sizeof(request->u.addrinfo));
    request->terminate = NULL;

#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
    if (os_feature_enabled(mDNSResponder, bonjour_privacy))
    {
        err = _handle_addrinfo_request_with_trust(request, &params);
    }
    else
    {
        err = _handle_addrinfo_request_start(request, &params);
    }
#else
    err = _handle_addrinfo_request_start(request, &params);
#endif

exit:
    return(err);
}

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - Main Request Handler etc.
#endif

mDNSlocal request_state *NewRequest(void)
{
    request_state *request;
    request_state **p = &all_requests;
    request = (request_state *) callocL("request_state", sizeof(*request));
    if (!request) FatalError("ERROR: calloc");
    while (*p) p = &(*p)->next;
    *p = request;
    return(request);
}

// read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
// if there is no data on the socket, the socket will be closed and t_terminated will be returned
mDNSlocal void read_msg(request_state *req)
{
    if (req->ts == t_terminated || req->ts == t_error)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                  "[R%u] ERROR: read_msg called with transfer state terminated or error", req->request_id);
        req->ts = t_error;
        return;
    }

    if (req->ts == t_complete)  // this must be death or something is wrong
    {
        char buf[4];    // dummy for death notification
        int nread = udsSupportReadFD(req->sd, buf, 4, 0, req->platform_data);
        if (!nread) { req->ts = t_terminated; return; }
        if (nread < 0) goto rerror;
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                  "[R%u] ERROR: read data from a completed request", req->request_id);
        req->ts = t_error;
        return;
    }

    if (req->ts != t_morecoming)
    {
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                  "[R%u] ERROR: read_msg called with invalid transfer state (%d)", req->request_id, req->ts);
        req->ts = t_error;
        return;
    }

    if (req->hdr_bytes < sizeof(ipc_msg_hdr))
    {
        mDNSu32 nleft = sizeof(ipc_msg_hdr) - req->hdr_bytes;
        int nread = udsSupportReadFD(req->sd, (char *)&req->hdr + req->hdr_bytes, nleft, 0, req->platform_data);
        if (nread == 0) { req->ts = t_terminated; return; }
        if (nread < 0) goto rerror;
        req->hdr_bytes += nread;
        if (req->hdr_bytes > sizeof(ipc_msg_hdr))
        {
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                      "[R%u] ERROR: read_msg - read too many header bytes", req->request_id);
            req->ts = t_error;
            return;
        }

        // only read data if header is complete
        if (req->hdr_bytes == sizeof(ipc_msg_hdr))
        {
            ConvertHeaderBytes(&req->hdr);
            if (req->hdr.version != VERSION)
            {
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                          "[R%u] ERROR: client version 0x%08X daemon version 0x%08X", req->request_id, req->hdr.version, VERSION);
                req->ts = t_error;
                return;
            }

            // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
            // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
            // for other overhead, this means any message above 70kB is definitely bogus.
            if (req->hdr.datalen > 70000)
            {
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                          "[R%u] ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req->request_id, req->hdr.datalen, req->hdr.datalen);
                req->ts = t_error;
                return;
            }
            req->msgbuf = (char *) callocL("request_state msgbuf", req->hdr.datalen + MSG_PAD_BYTES);
            if (!req->msgbuf) { my_perror("ERROR: calloc"); req->ts = t_error; return; }
            req->msgptr = req->msgbuf;
            req->msgend = req->msgbuf + req->hdr.datalen;
        }
    }

    // If our header is complete, but we're still needing more body data, then try to read it now
    // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
    // Any time we need to get the error return socket we know we'll have at least one data byte
    // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
    if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes < req->hdr.datalen)
    {
        mDNSu32 nleft = req->hdr.datalen - req->data_bytes;
        ssize_t nread;
#if !defined(_WIN32)
        struct iovec vec = { req->msgbuf + req->data_bytes, nleft };    // Tell recvmsg where we want the bytes put
        struct msghdr msg;
        struct cmsghdr *cmsg;
        char cbuf[CMSG_SPACE(4 * sizeof(dnssd_sock_t))];
        msg.msg_name       = 0;
        msg.msg_namelen    = 0;
        msg.msg_iov        = &vec;
        msg.msg_iovlen     = 1;
        msg.msg_control    = cbuf;
        msg.msg_controllen = sizeof(cbuf);
        msg.msg_flags      = 0;
        nread = recvmsg(req->sd, &msg, 0);
#else
        nread = udsSupportReadFD(req->sd, (char *)req->msgbuf + req->data_bytes, nleft, 0, req->platform_data);
#endif
        if (nread == 0) { req->ts = t_terminated; return; }
        if (nread < 0) goto rerror;
        req->data_bytes += nread;
        if (req->data_bytes > req->hdr.datalen)
        {
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                      "[R%u] ERROR: read_msg - read too many data bytes", req->request_id);
            req->ts = t_error;
            return;
        }
#if !defined(_WIN32)
        cmsg = CMSG_FIRSTHDR(&msg);
#if DEBUG_64BIT_SCM_RIGHTS
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
                  "[R%u] Expecting %d %d %d %d", req->request_id, sizeof(cbuf), sizeof(cbuf), SOL_SOCKET, SCM_RIGHTS);
        LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
                  "[R%u] Got       %d %d %d %d", req->request_id, msg.msg_controllen, cmsg ? cmsg->cmsg_len : -1, cmsg ? cmsg->cmsg_level : -1, cmsg ? cmsg->cmsg_type : -1);
#endif // DEBUG_64BIT_SCM_RIGHTS
        if (cmsg && cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
        {
#if APPLE_OSX_mDNSResponder
            // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
            // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
            // and it's convenient to repurpose the existing fd-passing code here for that task
            if (req->hdr.op == send_bpf)
            {
                dnssd_sock_t x = *(dnssd_sock_t *)CMSG_DATA(cmsg);
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
                          "[R%u] Got len %d, BPF %d", req->request_id, cmsg->cmsg_len, x);
                mDNSPlatformReceiveBPF_fd(x);
            }
            else
#endif // APPLE_OSX_mDNSResponder
            req->errsd = *(dnssd_sock_t *)CMSG_DATA(cmsg);
#if DEBUG_64BIT_SCM_RIGHTS
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
                      "[R%u] read req->errsd %d", req->request_id, req->errsd);
#endif // DEBUG_64BIT_SCM_RIGHTS
            if (req->data_bytes < req->hdr.datalen)
            {
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
                          "[R%u] Client(PID [%d](" PUB_S ")) sent result code socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
                          req->request_id, req->process_id, req->pid_name, req->errsd, req->data_bytes, req->hdr.datalen);
                req->ts = t_error;
                return;
            }
        }
#endif
    }

    // If our header and data are both complete, see if we need to make our separate error return socket
    if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes == req->hdr.datalen)
    {
        if (req->terminate && req->hdr.op != cancel_request)
        {
            dnssd_sockaddr_t cliaddr;
#if defined(USE_TCP_LOOPBACK)
            mDNSOpaque16 port;
            u_long opt = 1;
            port.b[0] = req->msgptr[0];
            port.b[1] = req->msgptr[1];
            req->msgptr += 2;
            cliaddr.sin_family      = AF_INET;
            cliaddr.sin_port        = port.NotAnInteger;
            cliaddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
#else
            char ctrl_path[MAX_CTLPATH];
            get_string(&req->msgptr, req->msgend, ctrl_path, MAX_CTLPATH);  // path is first element in message buffer
            mDNSPlatformMemZero(&cliaddr, sizeof(cliaddr));
            cliaddr.sun_family = AF_LOCAL;
            mDNSPlatformStrLCopy(cliaddr.sun_path, ctrl_path, sizeof(cliaddr.sun_path));
            // If the error return path UDS name is empty string, that tells us
            // that this is a new version of the library that's going to pass us
            // the error return path socket via sendmsg/recvmsg
            if (ctrl_path[0] == 0)
            {
                if (req->errsd == req->sd)
                {
                    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                              "[R%u] read_msg: ERROR failed to get errsd via SCM_RIGHTS", req->request_id);
                    req->ts = t_error;
                    return;
                }
                goto got_errfd;
            }
#endif

            req->errsd = socket(AF_DNSSD, SOCK_STREAM, 0);
            if (!dnssd_SocketValid(req->errsd))
            {
                my_throttled_perror("ERROR: socket");
                req->ts = t_error;
                return;
            }

            if (connect(req->errsd, (struct sockaddr *)&cliaddr, sizeof(cliaddr)) < 0)
            {
#if !defined(USE_TCP_LOOPBACK)
                struct stat sb;
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                          "[R%u] read_msg: Couldn't connect to error return path socket " PUB_S " errno %d (" PUB_S ")",
                          req->request_id, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
                if (stat(cliaddr.sun_path, &sb) < 0)
                {
                    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                              "[R%u] read_msg: stat failed " PUB_S " errno %d (" PUB_S ")",
                              req->request_id, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
                }
                else
                {
                    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                              "[R%u] read_msg: file " PUB_S " mode %o (octal) uid %d gid %d",
                              req->request_id, cliaddr.sun_path, sb.st_mode, sb.st_uid, sb.st_gid);
                }
#endif
                req->ts = t_error;
                return;
            }

#if !defined(USE_TCP_LOOPBACK)
got_errfd:
#endif

#if defined(_WIN32)
            if (ioctlsocket(req->errsd, FIONBIO, &opt) != 0)
#else
            if (fcntl(req->errsd, F_SETFL, fcntl(req->errsd, F_GETFL, 0) | O_NONBLOCK) != 0)
#endif
            {
                LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
                          "[R%u] ERROR: could not set control socket to non-blocking mode errno %d (" PUB_S ")",
                          req->request_id, dnssd_errno, dnssd_strerror(dnssd_errno));
                req->ts = t_error;
                return;
            }
        }

        req->ts = t_complete;
    }

    return;

rerror:
    if (dnssd_errno == dnssd_EWOULDBLOCK || dnssd_errno == dnssd_EINTR) return;
    LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR,
              "[R%u] ERROR: read_msg errno %d (" PUB_S ")", req->request_id, dnssd_errno, dnssd_strerror(dnssd_errno));
    req->ts = t_error;
}

mDNSlocal mStatus handle_client_request(request_state *req)
{
    mStatus err = mStatus_NoError;
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    SetupAuditTokenForRequest(req);
#endif
    switch(req->hdr.op)
    {
            // These are all operations that have their own first-class request_state object
        case connection_request:
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
                   "[R%d] DNSServiceCreateConnection START PID[%d](" PUB_S ")",
                   req->request_id, req->process_id, req->pid_name);
            req->terminate = connection_termination;
            break;
        case connection_delegate_request:
            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
                   "[R%d] DNSServiceCreateDelegateConnection START PID[%d](" PRI_S ")",
                   req->request_id, req->process_id, req->pid_name);
            req->terminate = connection_termination;
            handle_connection_delegate_request(req);
            break;
        case resolve_request:              err = handle_resolve_request     (req);  break;
        case query_request:                err = handle_queryrecord_request (req);  break;
        case browse_request:               err = handle_browse_request      (req);  break;
        case reg_service_request:          err = handle_regservice_request  (req);  break;
        case enumeration_request:          err = handle_enum_request        (req);  break;
        case reconfirm_record_request:     err = handle_reconfirm_request   (req);  break;
        case setdomain_request:            err = handle_setdomain_request   (req);  break;
        case getproperty_request:                handle_getproperty_request (req);  break;
        case port_mapping_request:         err = handle_port_mapping_request(req);  break;
        case addrinfo_request:             err = handle_addrinfo_request    (req);  break;
        case send_bpf:                     /* Do nothing for send_bpf */            break;

            // These are all operations that work with an existing request_state object
        case reg_record_request:           err = handle_regrecord_request   (req);  break;
        case add_record_request:           err = handle_add_request         (req);  break;
        case update_record_request:        err = handle_update_request      (req);  break;
        case remove_record_request:        err = handle_removerecord_request(req);  break;
        case cancel_request:                     handle_cancel_request      (req);  break;
        case release_request:              err = handle_release_request     (req);  break;
        default: LogMsg("request_callback: %3d:ERROR: Unsupported UDS req:%d PID[%d][%s]",
                        req->sd, req->hdr.op, req->process_id, req->pid_name);
            err = mStatus_BadParamErr;
            break;
    }

    return err;
}

#define RecordOrientedOp(X) \
    ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)

// The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
#define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)

mDNSlocal void request_callback(int fd, void *info)
{
    mStatus err = 0;
    request_state *req = info;
    mDNSs32 min_size = sizeof(DNSServiceFlags);
    (void)fd; // Unused

    for (;;)
    {
        read_msg(req);
        if (req->ts == t_morecoming)
            return;
        if (req->ts == t_terminated || req->ts == t_error)
        {
            AbortUnlinkAndFree(req);
            return;
        }
        if (req->ts != t_complete)
        {
            LogMsg("request_callback: req->ts %d != t_complete PID[%d][%s]", req->ts, req->process_id, req->pid_name);
            AbortUnlinkAndFree(req);
            return;
        }

        switch(req->hdr.op)            //          Interface       + other data
        {
            case connection_request:       min_size = 0;                                                                           break;
            case connection_delegate_request: min_size = 4; /* pid */                                                              break;
            case reg_service_request:      min_size += sizeof(mDNSu32) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
            case add_record_request:       min_size +=                   4 /* type, rdlen */              + 4 /* ttl */;           break;
            case update_record_request:    min_size +=                   2 /* rdlen */                    + 4 /* ttl */;           break;
            case remove_record_request:                                                                                            break;
            case browse_request:           min_size += sizeof(mDNSu32) + 2 /* type, domain */;                                     break;
            case resolve_request:          min_size += sizeof(mDNSu32) + 3 /* type, type, domain */;                               break;
            case query_request:            min_size += sizeof(mDNSu32) + 1 /* name */                     + 4 /* type, class*/;    break;
            case enumeration_request:      min_size += sizeof(mDNSu32);                                                            break;
            case reg_record_request:       min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */;  break;
            case reconfirm_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */;                break;
            case setdomain_request:        min_size +=                   1 /* domain */;                                           break;
            case getproperty_request:      min_size = 2;                                                                           break;
            case port_mapping_request:     min_size += sizeof(mDNSu32) + 4 /* udp/tcp */ + 4 /* int/ext port */    + 4 /* ttl */;  break;
            case addrinfo_request:         min_size += sizeof(mDNSu32) + 4 /* v4/v6 */   + 1 /* hostname */;                       break;
            case send_bpf:                 // Same as cancel_request below
            case cancel_request:           min_size = 0;                                                                           break;
            case release_request:          min_size += sizeof(mDNSu32) + 3 /* type, type, domain */;                               break;
            default: LogMsg("request_callback: ERROR: validate_message - unsupported req type: %d PID[%d][%s]",
                            req->hdr.op, req->process_id, req->pid_name);
                     min_size = -1;                                                                                                break;
        }

        if ((mDNSs32)req->data_bytes < min_size)
        {
            LogMsg("request_callback: Invalid message %d bytes; min for %d is %d PID[%d][%s]",
                    req->data_bytes, req->hdr.op, min_size, req->process_id, req->pid_name);
            AbortUnlinkAndFree(req);
            return;
        }
        if (LightweightOp(req->hdr.op) && !req->terminate)
        {
            LogMsg("request_callback: Reg/Add/Update/Remove %d require existing connection PID[%d][%s]",
                    req->hdr.op, req->process_id, req->pid_name);
            AbortUnlinkAndFree(req);
            return;
        }

        // If req->terminate is already set, this means this operation is sharing an existing connection
        if (req->terminate && !LightweightOp(req->hdr.op))
        {
            request_state *newreq = NewRequest();
            newreq->primary = req;
            newreq->sd      = req->sd;
            newreq->errsd   = req->errsd;
            newreq->uid     = req->uid;
            newreq->hdr     = req->hdr;
            newreq->msgbuf  = req->msgbuf;
            newreq->msgptr  = req->msgptr;
            newreq->msgend  = req->msgend;
            newreq->request_id = GetNewRequestID();
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
            newreq->audit_token = req->audit_token;
#endif
            // if the parent request is a delegate connection, copy the
            // relevant bits
            if (req->validUUID)
            {
                newreq->validUUID = mDNStrue;
                mDNSPlatformMemCopy(newreq->uuid, req->uuid, UUID_SIZE);
            }
            else
            {
                if (req->process_id)
                {
                    newreq->process_id = req->process_id;
                    mDNSPlatformStrLCopy(newreq->pid_name, req->pid_name, (mDNSu32)sizeof(newreq->pid_name));
                }
                else
                {
                    set_peer_pid(newreq);
                }
            }
            req = newreq;
        }

        // Check if the request wants no asynchronous replies.
        if (req->hdr.ipc_flags & IPC_FLAGS_NOREPLY) req->no_reply = 1;

        // If we're shutting down, don't allow new client requests
        // We do allow "cancel" and "getproperty" during shutdown
        if (mDNSStorage.ShutdownTime && req->hdr.op != cancel_request && req->hdr.op != getproperty_request)
            err = mStatus_ServiceNotRunning;
        else
            err = handle_client_request(req);

        // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
        if (req->msgbuf) freeL("request_state msgbuf", req->msgbuf);

        // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
        // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
        if (req->hdr.op != cancel_request && req->hdr.op != getproperty_request && req->hdr.op != send_bpf && req->hdr.op != getpid_request)
        {
            const mStatus err_netorder = dnssd_htonl(err);
            send_all(req->errsd, (const char *)&err_netorder, sizeof(err_netorder));
            if (req->errsd != req->sd)
            {
                dnssd_close(req->errsd);
                req->errsd = req->sd;
                // Also need to reset the parent's errsd, if this is a subordinate operation
                if (req->primary) req->primary->errsd = req->primary->sd;
            }
        }

        // Reset ready to accept the next req on this pipe
        if (req->primary) req = req->primary;
        req->ts         = t_morecoming;
        req->hdr_bytes  = 0;
        req->data_bytes = 0;
        req->msgbuf     = mDNSNULL;
        req->msgptr     = mDNSNULL;
        req->msgend     = 0;
    }
}

mDNSlocal void connect_callback(int fd, void *info)
{
    dnssd_sockaddr_t cliaddr;
    dnssd_socklen_t len = (dnssd_socklen_t) sizeof(cliaddr);
    dnssd_sock_t sd = accept(fd, (struct sockaddr*) &cliaddr, &len);
#if defined(SO_NOSIGPIPE) || defined(_WIN32)
    unsigned long optval = 1;
#endif

    (void)info; // Unused

    if (!dnssd_SocketValid(sd))
    {
        if (dnssd_errno != dnssd_EWOULDBLOCK)
            my_throttled_perror("ERROR: accept");
        return;
    }

#ifdef SO_NOSIGPIPE
    // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
    if (setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
        LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd, dnssd_errno, dnssd_strerror(dnssd_errno));
#endif

#if defined(_WIN32)
    if (ioctlsocket(sd, FIONBIO, &optval) != 0)
#else
    if (fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) | O_NONBLOCK) != 0)
#endif
    {
        my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
        dnssd_close(sd);
        return;
    }
    else
    {
        request_state *request = NewRequest();
        request->ts    = t_morecoming;
        request->sd    = sd;
        request->errsd = sd;
        request->request_id = GetNewRequestID();
        set_peer_pid(request);
#if APPLE_OSX_mDNSResponder
        struct xucred x;
        socklen_t xucredlen = sizeof(x);
        if (getsockopt(sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 && x.cr_version == XUCRED_VERSION)
            request->uid = x.cr_uid; // save the effective userid of the client
        else
            my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
        debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen, x.cr_version, x.cr_uid, x.cr_ngroups);
#endif // APPLE_OSX_mDNSResponder
        LogDebug("%3d: connect_callback: Adding FD for uid %u", request->sd, request->uid);
        udsSupportAddFDToEventLoop(sd, request_callback, request, &request->platform_data);
    }
}

mDNSlocal mDNSBool uds_socket_setup(dnssd_sock_t skt)
{
#if defined(SO_NP_EXTENSIONS)
    struct      so_np_extensions sonpx;
    socklen_t optlen = sizeof(struct so_np_extensions);
    sonpx.npx_flags = SONPX_SETOPTSHUT;
    sonpx.npx_mask  = SONPX_SETOPTSHUT;
    if (setsockopt(skt, SOL_SOCKET, SO_NP_EXTENSIONS, &sonpx, optlen) < 0)
        my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
#endif
#if defined(_WIN32)
    // SEH: do we even need to do this on windows?
    // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
    u_long opt = 1;
    if (ioctlsocket(skt, FIONBIO, &opt) != 0)
#else
    if (fcntl(skt, F_SETFL, fcntl(skt, F_GETFL, 0) | O_NONBLOCK) != 0)
#endif
    {
        my_perror("ERROR: could not set listen socket to non-blocking mode");
        return mDNSfalse;
    }

    if (listen(skt, LISTENQ) != 0)
    {
        my_perror("ERROR: could not listen on listen socket");
        return mDNSfalse;
    }

    if (mStatus_NoError != udsSupportAddFDToEventLoop(skt, connect_callback, (void *) NULL, (void **) NULL))
    {
        my_perror("ERROR: could not add listen socket to event loop");
        return mDNSfalse;
    }
    else
    {
        LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt);
        mDNSStorage.uds_listener_skt = skt;
    }
    return mDNStrue;
}

#if MDNS_MALLOC_DEBUGGING
mDNSlocal void udsserver_validatelists(void *context);
#endif

mDNSexport int udsserver_init(dnssd_sock_t skts[], const size_t count)
{
    dnssd_sockaddr_t laddr;
    int ret;

#ifndef NO_PID_FILE
    FILE *fp = fopen(PID_FILE, "w");
    if (fp != NULL)
    {
        fprintf(fp, "%d\n", getpid());
        fclose(fp);
    }
#endif

#if MDNS_MALLOC_DEBUGGING
	static mDNSListValidator validator;
	mDNSPlatformAddListValidator(&validator, udsserver_validatelists, "udsserver_validatelists", NULL);
#endif

    if (skts)
    {
        size_t i;
        for (i = 0; i < count; i++)
            if (dnssd_SocketValid(skts[i]) && !uds_socket_setup(skts[i]))
                goto error;
    }
    else
    {
        listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
        if (!dnssd_SocketValid(listenfd))
        {
            my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
            goto error;
        }

        mDNSPlatformMemZero(&laddr, sizeof(laddr));

        #if defined(USE_TCP_LOOPBACK)
        {
            laddr.sin_family = AF_INET;
            laddr.sin_port = htons(MDNS_TCP_SERVERPORT);
            laddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
            ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
            if (ret < 0)
            {
                my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
                goto error;
            }
        }
        #else
        {
            mode_t mask = umask(0);
            unlink(boundPath);  // OK if this fails
            laddr.sun_family = AF_LOCAL;
            #ifndef NOT_HAVE_SA_LEN
            // According to Stevens (section 3.2), there is no portable way to
            // determine whether sa_len is defined on a particular platform.
            laddr.sun_len = sizeof(struct sockaddr_un);
            #endif
            if (strlen(boundPath) >= sizeof(laddr.sun_path))
            {
                LogMsg("ERROR: MDNS_UDS_SERVERPATH must be < %d characters", (int)sizeof(laddr.sun_path));
                goto error;
            }
            mDNSPlatformStrLCopy(laddr.sun_path, boundPath, sizeof(laddr.sun_path));
            ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
            umask(mask);
            if (ret < 0)
            {
                my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
                goto error;
            }
        }
        #endif

        if (!uds_socket_setup(listenfd)) goto error;
    }

#if !defined(PLATFORM_NO_RLIMIT)
    {
        // Set maximum number of open file descriptors
    #define MIN_OPENFILES 10240
        struct rlimit maxfds, newfds;

        // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
        // you have to get and set rlimits once before getrlimit will return sensible values
        if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
        if (setrlimit(RLIMIT_NOFILE, &maxfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");

        if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
        newfds.rlim_max = (maxfds.rlim_max > MIN_OPENFILES) ? maxfds.rlim_max : MIN_OPENFILES;
        newfds.rlim_cur = (maxfds.rlim_cur > MIN_OPENFILES) ? maxfds.rlim_cur : MIN_OPENFILES;
        if (newfds.rlim_max != maxfds.rlim_max || newfds.rlim_cur != maxfds.rlim_cur)
            if (setrlimit(RLIMIT_NOFILE, &newfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");

        if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
        debugf("maxfds.rlim_max %d", (long)maxfds.rlim_max);
        debugf("maxfds.rlim_cur %d", (long)maxfds.rlim_cur);
    }
#endif

    // We start a "LocalOnly" query looking for Automatic Browse Domain records.
    // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
    // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
    mDNS_GetDomains(&mDNSStorage, &mDNSStorage.AutomaticBrowseDomainQ, mDNS_DomainTypeBrowseAutomatic,
                    mDNSNULL, mDNSInterface_LocalOnly, AutomaticBrowseDomainChange, mDNSNULL);

    // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
    RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeRegistration);
    RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeBrowse);
    AddAutoBrowseDomain(0, &localdomain);

    udsserver_handle_configchange(&mDNSStorage);
    return 0;

error:

    my_perror("ERROR: udsserver_init");
    return -1;
}

mDNSexport int udsserver_exit(void)
{
    // Cancel all outstanding client requests
    while (all_requests) AbortUnlinkAndFree(all_requests);

    // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
    // created in udsserver_init, and others we created as a result of reading local configuration data
    while (LocalDomainEnumRecords)
    {
        ARListElem *rem = LocalDomainEnumRecords;
        LocalDomainEnumRecords = LocalDomainEnumRecords->next;
        mDNS_Deregister(&mDNSStorage, &rem->ar);
    }

    // If the launching environment created no listening socket,
    // that means we created it ourselves, so we should clean it up on exit
    if (dnssd_SocketValid(listenfd))
    {
        dnssd_close(listenfd);
#if !defined(USE_TCP_LOOPBACK)
        // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
        // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
        // It would be nice if we could find a solution to this problem
        if (unlink(boundPath))
            debugf("Unable to remove %s", MDNS_UDS_SERVERPATH);
#endif
    }

#ifndef NO_PID_FILE
    unlink(PID_FILE);
#endif

    return 0;
}

mDNSlocal void LogClientInfoToFD(int fd, request_state *req)
{
    char reqIDStr[14];
    char prefix[18];

    mDNS_snprintf(reqIDStr, sizeof(reqIDStr), "[R%u]", req->request_id);

    mDNS_snprintf(prefix, sizeof(prefix), "%-6s %2s", reqIDStr, req->primary ? "->" : "");

    if (!req->terminate)
        LogToFD(fd, "%s No operation yet on this socket", prefix);
    else if (req->terminate == connection_termination)
    {
        int num_records = 0, num_ops = 0;
        const registered_record_entry *p;
        request_state *r;
        for (p = req->u.reg_recs; p; p=p->next) num_records++;
        for (r = req->next; r; r=r->next) if (r->primary == req) num_ops++;
        LogToFD(fd, "%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
                  prefix, num_records, num_records != 1 ? "s" : "", num_ops,     num_ops     != 1 ? "s" : "",
                  req->process_id, req->pid_name);
        for (p = req->u.reg_recs; p; p=p->next)
            LogToFD(fd, " ->  DNSServiceRegisterRecord   0x%08X %2d %3d %s PID[%d](%s)",
                      req->flags, req->interfaceIndex, p->key, ARDisplayString(&mDNSStorage, p->rr), req->process_id, req->pid_name);
        for (r = req->next; r; r=r->next) if (r->primary == req) LogClientInfoToFD(fd, r);
    }
    else if (req->terminate == regservice_termination_callback)
    {
        service_instance *ptr;
        for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
            LogToFD(fd, "%-9s DNSServiceRegister         0x%08X %2d %##s %u/%u PID[%d](%s)",
                      (ptr == req->u.servicereg.instances) ? prefix : "", req->flags, req->interfaceIndex, ptr->srs.RR_SRV.resrec.name->c,
                      mDNSVal16(req->u.servicereg.port),
                      SRS_PORT(&ptr->srs), req->process_id, req->pid_name);
    }
    else if (req->terminate == browse_termination_callback)
    {
        browser_t *blist;
        for (blist = req->u.browser.browsers; blist; blist = blist->next)
            LogToFD(fd, "%-9s DNSServiceBrowse           0x%08X %2d %##s PID[%d](%s)",
                      (blist == req->u.browser.browsers) ? prefix : "", req->flags, req->interfaceIndex, blist->q.qname.c,
                      req->process_id, req->pid_name);
    }
    else if (req->terminate == resolve_termination_callback)
        LogToFD(fd, "%s DNSServiceResolve          0x%08X %2d %##s PID[%d](%s)",
                  prefix, req->flags, req->interfaceIndex, req->u.resolve.qsrv.qname.c, req->process_id, req->pid_name);
    else if (req->terminate == queryrecord_termination_callback)
        LogToFD(fd, "%s DNSServiceQueryRecord      0x%08X %2d %##s (%s) PID[%d](%s)",
                  prefix, req->flags, req->interfaceIndex, QueryRecordClientRequestGetQName(&req->u.queryrecord), DNSTypeName(QueryRecordClientRequestGetType(&req->u.queryrecord)), req->process_id, req->pid_name);
    else if (req->terminate == enum_termination_callback)
        LogToFD(fd, "%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
                  prefix, req->flags, req->interfaceIndex, req->u.enumeration.q_all.qname.c, req->process_id, req->pid_name);
    else if (req->terminate == port_mapping_termination_callback)
        LogToFD(fd, "%s DNSServiceNATPortMapping   0x%08X %2d %s%s Int %5d Req %5d Ext %.4a:%5d Req TTL %5d Granted TTL %5d PID[%d](%s)",
                  prefix,
                  req->flags,
                  req->interfaceIndex,
                  req->u.pm.NATinfo.Protocol & NATOp_MapTCP ? "TCP" : "   ",
                  req->u.pm.NATinfo.Protocol & NATOp_MapUDP ? "UDP" : "   ",
                  mDNSVal16(req->u.pm.NATinfo.IntPort),
                  mDNSVal16(req->u.pm.ReqExt),
                  &req->u.pm.NATinfo.ExternalAddress,
                  mDNSVal16(req->u.pm.NATinfo.ExternalPort),
                  req->u.pm.NATinfo.NATLease,
                  req->u.pm.NATinfo.Lifetime,
                  req->process_id, req->pid_name);
    else if (req->terminate == addrinfo_termination_callback)
        LogToFD(fd, "%s DNSServiceGetAddrInfo      0x%08X %2d %s%s %##s PID[%d](%s)",
                  prefix, req->flags, req->interfaceIndex,
                  req->u.addrinfo.protocols & kDNSServiceProtocol_IPv4 ? "v4" : "  ",
                  req->u.addrinfo.protocols & kDNSServiceProtocol_IPv6 ? "v6" : "  ",
                  GetAddrInfoClientRequestGetQName(&req->u.addrinfo), req->process_id, req->pid_name);
    else
        LogToFD(fd, "%s Unrecognized operation %p", prefix, req->terminate);
}

mDNSlocal void LogClientInfo(request_state *req)
{
    char reqIDStr[14];
    char prefix[18];

    mDNS_snprintf(reqIDStr, sizeof(reqIDStr), "[R%u]", req->request_id);

    mDNS_snprintf(prefix, sizeof(prefix), "%-6s %2s", reqIDStr, req->primary ? "->" : "");

    if (!req->terminate)
    LogMsgNoIdent("%s No operation yet on this socket", prefix);
    else if (req->terminate == connection_termination)
    {
        int num_records = 0, num_ops = 0;
        const registered_record_entry *p;
        request_state *r;
        for (p = req->u.reg_recs; p; p=p->next) num_records++;
        for (r = req->next; r; r=r->next) if (r->primary == req) num_ops++;
        LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
                      prefix, num_records, num_records != 1 ? "s" : "", num_ops,     num_ops     != 1 ? "s" : "",
                      req->process_id, req->pid_name);
        for (p = req->u.reg_recs; p; p=p->next)
        LogMsgNoIdent(" ->  DNSServiceRegisterRecord   0x%08X %2d %3d %s PID[%d](%s)",
                      req->flags, req->interfaceIndex, p->key, ARDisplayString(&mDNSStorage, p->rr), req->process_id, req->pid_name);
        for (r = req->next; r; r=r->next) if (r->primary == req) LogClientInfo(r);
    }
    else if (req->terminate == regservice_termination_callback)
    {
        service_instance *ptr;
        for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
        LogMsgNoIdent("%-9s DNSServiceRegister         0x%08X %2d %##s %u/%u PID[%d](%s)",
                      (ptr == req->u.servicereg.instances) ? prefix : "", req->flags, req->interfaceIndex, ptr->srs.RR_SRV.resrec.name->c,
                      mDNSVal16(req->u.servicereg.port),
                      SRS_PORT(&ptr->srs), req->process_id, req->pid_name);
    }
    else if (req->terminate == browse_termination_callback)
    {
        browser_t *blist;
        for (blist = req->u.browser.browsers; blist; blist = blist->next)
        LogMsgNoIdent("%-9s DNSServiceBrowse           0x%08X %2d %##s PID[%d](%s)",
                      (blist == req->u.browser.browsers) ? prefix : "", req->flags, req->interfaceIndex, blist->q.qname.c,
                      req->process_id, req->pid_name);
    }
    else if (req->terminate == resolve_termination_callback)
    LogMsgNoIdent("%s DNSServiceResolve          0x%08X %2d %##s PID[%d](%s)",
                  prefix, req->flags, req->interfaceIndex, req->u.resolve.qsrv.qname.c, req->process_id, req->pid_name);
    else if (req->terminate == queryrecord_termination_callback)
    LogMsgNoIdent("%s DNSServiceQueryRecord      0x%08X %2d %##s (%s) PID[%d](%s)",
                  prefix, req->flags, req->interfaceIndex, QueryRecordClientRequestGetQName(&req->u.queryrecord), DNSTypeName(QueryRecordClientRequestGetType(&req->u.queryrecord)), req->process_id, req->pid_name);
    else if (req->terminate == enum_termination_callback)
    LogMsgNoIdent("%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
                  prefix, req->flags, req->interfaceIndex, req->u.enumeration.q_all.qname.c, req->process_id, req->pid_name);
    else if (req->terminate == port_mapping_termination_callback)
    LogMsgNoIdent("%s DNSServiceNATPortMapping   0x%08X %2d %s%s Int %5d Req %5d Ext %.4a:%5d Req TTL %5d Granted TTL %5d PID[%d](%s)",
                  prefix,
                  req->flags,
                  req->interfaceIndex,
                  req->u.pm.NATinfo.Protocol & NATOp_MapTCP ? "TCP" : "   ",
                  req->u.pm.NATinfo.Protocol & NATOp_MapUDP ? "UDP" : "   ",
                  mDNSVal16(req->u.pm.NATinfo.IntPort),
                  mDNSVal16(req->u.pm.ReqExt),
                  &req->u.pm.NATinfo.ExternalAddress,
                  mDNSVal16(req->u.pm.NATinfo.ExternalPort),
                  req->u.pm.NATinfo.NATLease,
                  req->u.pm.NATinfo.Lifetime,
                  req->process_id, req->pid_name);
    else if (req->terminate == addrinfo_termination_callback)
    LogMsgNoIdent("%s DNSServiceGetAddrInfo      0x%08X %2d %s%s %##s PID[%d](%s)",
                  prefix, req->flags, req->interfaceIndex,
                  req->u.addrinfo.protocols & kDNSServiceProtocol_IPv4 ? "v4" : "  ",
                  req->u.addrinfo.protocols & kDNSServiceProtocol_IPv6 ? "v6" : "  ",
                  GetAddrInfoClientRequestGetQName(&req->u.addrinfo), req->process_id, req->pid_name);
    else
    LogMsgNoIdent("%s Unrecognized operation %p", prefix, req->terminate);
}

mDNSlocal void GetMcastClients(request_state *req)
{
    if (req->terminate == connection_termination)
    {
        int num_records = 0, num_ops = 0;
        const registered_record_entry *p;
        request_state *r;
        for (p = req->u.reg_recs; p; p=p->next)
            num_records++;
        for (r = req->next; r; r=r->next)
            if (r->primary == req)
                num_ops++;
        for (p = req->u.reg_recs; p; p=p->next)
        {
            if (!AuthRecord_uDNS(p->rr))
                n_mrecords++;
        }
        for (r = req->next; r; r=r->next)
            if (r->primary == req)
                GetMcastClients(r);
    }
    else if (req->terminate == regservice_termination_callback)
    {
        service_instance *ptr;
        for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
        {
            if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
                n_mrecords++;
        }
    }
    else if (req->terminate == browse_termination_callback)
    {
        browser_t *blist;
        for (blist = req->u.browser.browsers; blist; blist = blist->next)
        {
            if (mDNSOpaque16IsZero(blist->q.TargetQID))
                n_mquests++;
        }
    }
    else if (req->terminate == resolve_termination_callback)
    {
        if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
            n_mquests++;
    }
    else if (req->terminate == queryrecord_termination_callback)
    {
        if (QueryRecordClientRequestIsMulticast(&req->u.queryrecord))
            n_mquests++;
    }
    else if (req->terminate == addrinfo_termination_callback)
    {
        if (GetAddrInfoClientRequestIsMulticast(&req->u.addrinfo))
            n_mquests++;
    }
    else
    {
        return;
    }
}


mDNSlocal void LogMcastClientInfo(request_state *req)
{
    if (!req->terminate)
        LogMcastNoIdent("No operation yet on this socket");
    else if (req->terminate == connection_termination)
    {
        int num_records = 0, num_ops = 0;
        const registered_record_entry *p;
        request_state *r;
        for (p = req->u.reg_recs; p; p=p->next)
            num_records++;
        for (r = req->next; r; r=r->next)
            if (r->primary == req)
                num_ops++;
        for (p = req->u.reg_recs; p; p=p->next)
        {
            if (!AuthRecord_uDNS(p->rr))
                LogMcastNoIdent("R: ->  DNSServiceRegisterRecord:  %##s %s PID[%d](%s)", p->rr->resrec.name->c,
                                DNSTypeName(p->rr->resrec.rrtype), req->process_id, req->pid_name, i_mcount++);
        }
        for (r = req->next; r; r=r->next)
            if (r->primary == req)
                LogMcastClientInfo(r);
    }
    else if (req->terminate == regservice_termination_callback)
    {
        service_instance *ptr;
        for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
        {
            if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
                LogMcastNoIdent("R: DNSServiceRegister:  %##s %u/%u PID[%d](%s)", ptr->srs.RR_SRV.resrec.name->c, mDNSVal16(req->u.servicereg.port),
                                SRS_PORT(&ptr->srs), req->process_id, req->pid_name, i_mcount++);
        }
    }
    else if (req->terminate == browse_termination_callback)
    {
        browser_t *blist;
        for (blist = req->u.browser.browsers; blist; blist = blist->next)
        {
            if (mDNSOpaque16IsZero(blist->q.TargetQID))
                LogMcastNoIdent("Q: DNSServiceBrowse  %##s %s PID[%d](%s)", blist->q.qname.c, DNSTypeName(blist->q.qtype),
                                req->process_id, req->pid_name, i_mcount++);
        }
    }
    else if (req->terminate == resolve_termination_callback)
    {
        if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
            LogMcastNoIdent("Q: DNSServiceResolve  %##s %s PID[%d](%s)", req->u.resolve.qsrv.qname.c, DNSTypeName(req->u.resolve.qsrv.qtype),
                            req->process_id, req->pid_name, i_mcount++);
    }
    else if (req->terminate == queryrecord_termination_callback)
    {
        if (QueryRecordClientRequestIsMulticast(&req->u.queryrecord))
        {
            LogMcastNoIdent("Q: DNSServiceQueryRecord  %##s %s PID[%d](%s)",
                          QueryRecordClientRequestGetQName(&req->u.queryrecord),
                          DNSTypeName(QueryRecordClientRequestGetType(&req->u.queryrecord)),
                          req->process_id, req->pid_name, i_mcount++);
        }
    }
    else if (req->terminate == addrinfo_termination_callback)
    {
        if (GetAddrInfoClientRequestIsMulticast(&req->u.addrinfo))
        {
            LogMcastNoIdent("Q: DNSServiceGetAddrInfo  %s%s %##s PID[%d](%s)",
                          req->u.addrinfo.protocols & kDNSServiceProtocol_IPv4 ? "v4" : "  ",
                          req->u.addrinfo.protocols & kDNSServiceProtocol_IPv6 ? "v6" : "  ",
                          GetAddrInfoClientRequestGetQName(&req->u.addrinfo), req->process_id, req->pid_name, i_mcount++);
        }
    }
}

mDNSlocal char *RecordTypeName(mDNSu8 rtype)
{
    switch (rtype)
    {
    case kDNSRecordTypeUnregistered:  return ("Unregistered ");
    case kDNSRecordTypeDeregistering: return ("Deregistering");
    case kDNSRecordTypeUnique:        return ("Unique       ");
    case kDNSRecordTypeAdvisory:      return ("Advisory     ");
    case kDNSRecordTypeShared:        return ("Shared       ");
    case kDNSRecordTypeVerified:      return ("Verified     ");
    case kDNSRecordTypeKnownUnique:   return ("KnownUnique  ");
    default: return("Unknown");
    }
}

mDNSlocal int LogEtcHostsToFD(int fd, mDNS *const m)
{
    mDNSBool showheader = mDNStrue;
    const AuthRecord *ar;
    mDNSu32 slot;
    AuthGroup *ag;
    int count = 0;
    int authslot = 0;
    mDNSBool truncated = 0;

    for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
    {
        if (m->rrauth.rrauth_hash[slot]) authslot++;
        for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
            for (ar = ag->members; ar; ar = ar->next)
            {
                if (ar->RecordCallback != FreeEtcHosts) continue;
                if (showheader) { showheader = mDNSfalse; LogToFD(fd, "  State       Interface"); }

                // Print a maximum of 50 records
                if (count++ >= 50) { truncated = mDNStrue; continue; }
                if (ar->ARType == AuthRecordLocalOnly)
                {
                    if (ar->resrec.InterfaceID == mDNSInterface_LocalOnly)
                        LogToFD(fd, " %s   LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
                    else
                    {
                        mDNSu32 scopeid  = (mDNSu32)(uintptr_t)ar->resrec.InterfaceID;
                        LogToFD(fd, " %s   %u  %s", RecordTypeName(ar->resrec.RecordType), scopeid, ARDisplayString(m, ar));
                    }
                }
            }
    }

    if (showheader) LogToFD(fd, "<None>");
    else if (truncated) LogToFD(fd, "<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count, m->rrauth.rrauth_totalused, authslot);
    return count;
}

mDNSlocal void LogLocalOnlyAuthRecordsToFD(int fd, mDNS *const m)
{
    mDNSBool showheader = mDNStrue;
    const AuthRecord *ar;
    mDNSu32 slot;
    AuthGroup *ag;

    for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
    {
        for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
            for (ar = ag->members; ar; ar = ar->next)
            {
                if (ar->RecordCallback == FreeEtcHosts) continue;
                if (showheader) { showheader = mDNSfalse; LogToFD(fd, "  State       Interface"); }

                // Print a maximum of 400 records
                if (ar->ARType == AuthRecordLocalOnly)
                    LogToFD(fd, " %s   LO  %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
                else if (ar->ARType == AuthRecordP2P)
                {
                    if (ar->resrec.InterfaceID == mDNSInterface_BLE)
                        LogToFD(fd, " %s   BLE %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
                    else
                        LogToFD(fd, " %s   PP  %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
                }
            }
    }

    if (showheader) LogToFD(fd, "<None>");
}

mDNSlocal void LogOneAuthRecordToFD(int fd, const AuthRecord *ar, mDNSs32 now, const char *ifname)
{
    if (AuthRecord_uDNS(ar))
    {
        LogToFD(fd, "%7d %7d %7d %-7s %4d %s %s",
                  ar->ThisAPInterval / mDNSPlatformOneSecond,
                  (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
                  ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
                  "-U-",
                  ar->state,
                  ar->AllowRemoteQuery ? "☠" : " ",
                  ARDisplayString(&mDNSStorage, ar));
    }
    else
    {
        LogToFD(fd, "%7d %7d %7d %-7s 0x%02X %s %s",
                  ar->ThisAPInterval / mDNSPlatformOneSecond,
                  ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
                  ar->TimeExpire    ? (ar->TimeExpire                      - now) / mDNSPlatformOneSecond : 0,
                  ifname ? ifname : "ALL",
                  ar->resrec.RecordType,
                  ar->AllowRemoteQuery ? "☠" : " ",
                  ARDisplayString(&mDNSStorage, ar));
    }
}

mDNSlocal void LogAuthRecordsToFD(int fd,
                                    const mDNSs32 now, AuthRecord *ResourceRecords, int *proxy)
{
    mDNSBool showheader = mDNStrue;
    const AuthRecord *ar;
    OwnerOptData owner = zeroOwner;
    for (ar = ResourceRecords; ar; ar=ar->next)
    {
        const char *const ifname = InterfaceNameForID(&mDNSStorage, ar->resrec.InterfaceID);
        if ((ar->WakeUp.HMAC.l[0] != 0) == (proxy != mDNSNULL))
        {
            if (showheader) { showheader = mDNSfalse; LogToFD(fd, "    Int    Next  Expire if     State"); }
            if (proxy) (*proxy)++;
            if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)))
            {
                owner = ar->WakeUp;
                if (owner.password.l[0])
                    LogToFD(fd, "Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
                else if (!mDNSSameEthAddress(&owner.HMAC, &owner.IMAC))
                    LogToFD(fd, "Proxying for H-MAC %.6a I-MAC %.6a seq %d",               &owner.HMAC, &owner.IMAC,                  owner.seq);
                else
                    LogToFD(fd, "Proxying for %.6a seq %d",                                &owner.HMAC,                               owner.seq);
            }
            if (AuthRecord_uDNS(ar))
            {
                LogOneAuthRecordToFD(fd, ar, now, ifname);
            }
            else if (ar->ARType == AuthRecordLocalOnly)
            {
                LogToFD(fd, "                             LO %s", ARDisplayString(&mDNSStorage, ar));
            }
            else if (ar->ARType == AuthRecordP2P)
            {
                if (ar->resrec.InterfaceID == mDNSInterface_BLE)
                    LogToFD(fd, "                             BLE %s", ARDisplayString(&mDNSStorage, ar));
                else
                    LogToFD(fd, "                             PP %s", ARDisplayString(&mDNSStorage, ar));
            }
            else
            {
                LogOneAuthRecordToFD(fd, ar, now, ifname);
            }
        }
    }
    if (showheader) LogToFD(fd, "<None>");
}

mDNSlocal void PrintOneCacheRecordToFD(int fd, const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
{
    LogToFD(fd, "%3d %s%8d %-7s%s %-6s%s",
              slot,
              cr->CRActiveQuestion ? "*" : " ",
              remain,
              ifname ? ifname : "-U-",
              (cr->resrec.RecordType == kDNSRecordTypePacketNegative)  ? "-" :
              (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
              DNSTypeName(cr->resrec.rrtype),
              CRDisplayString(&mDNSStorage, cr));
    (*CacheUsed)++;
}

mDNSlocal void PrintCachedRecordsToFD(int fd, const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
{
    CacheRecord *soa;

    soa = cr->soa;
    if (soa)
    {
        PrintOneCacheRecordToFD(fd, soa, slot, remain, ifname, CacheUsed);
    }
}

mDNSexport void LogMDNSStatisticsToFD(int fd, mDNS *const m)
{
    LogToFD(fd, "--- MDNS Statistics ---");

    LogToFD(fd, "Name Conflicts                 %u", m->mDNSStats.NameConflicts);
    LogToFD(fd, "KnownUnique Name Conflicts     %u", m->mDNSStats.KnownUniqueNameConflicts);
    LogToFD(fd, "Duplicate Query Suppressions   %u", m->mDNSStats.DupQuerySuppressions);
    LogToFD(fd, "KA Suppressions                %u", m->mDNSStats.KnownAnswerSuppressions);
    LogToFD(fd, "KA Multiple Packets            %u", m->mDNSStats.KnownAnswerMultiplePkts);
    LogToFD(fd, "Poof Cache Deletions           %u", m->mDNSStats.PoofCacheDeletions);
    LogToFD(fd, "--------------------------------");

    LogToFD(fd, "Multicast packets Sent         %u", m->MulticastPacketsSent);
    LogToFD(fd, "Multicast packets Received     %u", m->MPktNum);
    LogToFD(fd, "Remote Subnet packets          %u", m->RemoteSubnet);
    LogToFD(fd, "QU questions  received         %u", m->mDNSStats.UnicastBitInQueries);
    LogToFD(fd, "Normal multicast questions     %u", m->mDNSStats.NormalQueries);
    LogToFD(fd, "Answers for questions          %u", m->mDNSStats.MatchingAnswersForQueries);
    LogToFD(fd, "Unicast responses              %u", m->mDNSStats.UnicastResponses);
    LogToFD(fd, "Multicast responses            %u", m->mDNSStats.MulticastResponses);
    LogToFD(fd, "Unicast response Demotions     %u", m->mDNSStats.UnicastDemotedToMulticast);
    LogToFD(fd, "--------------------------------");

    LogToFD(fd, "Sleeps                         %u", m->mDNSStats.Sleeps);
    LogToFD(fd, "Wakeups                        %u", m->mDNSStats.Wakes);
    LogToFD(fd, "Interface UP events            %u", m->mDNSStats.InterfaceUp);
    LogToFD(fd, "Interface UP Flap events       %u", m->mDNSStats.InterfaceUpFlap);
    LogToFD(fd, "Interface Down events          %u", m->mDNSStats.InterfaceDown);
    LogToFD(fd, "Interface DownFlap events      %u", m->mDNSStats.InterfaceDownFlap);
    LogToFD(fd, "Cache refresh queries          %u", m->mDNSStats.CacheRefreshQueries);
    LogToFD(fd, "Cache refreshed                %u", m->mDNSStats.CacheRefreshed);
    LogToFD(fd, "Wakeup on Resolves             %u", m->mDNSStats.WakeOnResolves);
}

mDNSexport void udsserver_info_dump_to_fd(int fd)
{
    mDNS *const m = &mDNSStorage;
    const mDNSs32 now = mDNS_TimeNow(m);
    mDNSu32 CacheUsed = 0, CacheActive = 0, slot;
    int ProxyA = 0, ProxyD = 0;
    mDNSu32 groupCount = 0;
    mDNSu32 mcastRecordCount = 0;
    mDNSu32 ucastRecordCount = 0;
    const CacheGroup *cg;
    const CacheRecord *cr;
    const DNSQuestion *q;
    const DNameListElem *d;
    const SearchListElem *s;

    LogToFD(fd, "------------ Cache -------------");
    LogToFD(fd, "Slt Q     TTL if     U Type rdlen");
    for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
    {
        for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
        {
            groupCount++;   // Count one cache entity for the CacheGroup object
            for (cr = cg->members; cr; cr=cr->next)
            {
                const mDNSs32 remain = cr->resrec.rroriginalttl - (now - cr->TimeRcvd) / mDNSPlatformOneSecond;
                const char *ifname;
                mDNSInterfaceID InterfaceID = cr->resrec.InterfaceID;
                mDNSu32 *const countPtr = InterfaceID ? &mcastRecordCount : &ucastRecordCount;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
                if (!InterfaceID && cr->resrec.dnsservice &&
                    (mdns_dns_service_get_scope(cr->resrec.dnsservice) == mdns_dns_service_scope_interface))
                {
                    InterfaceID = (mDNSInterfaceID)(uintptr_t)mdns_dns_service_get_interface_index(cr->resrec.dnsservice);
                }
#else
                if (!InterfaceID && cr->resrec.rDNSServer && cr->resrec.rDNSServer->scopeType)
                    InterfaceID = cr->resrec.rDNSServer->interface;
#endif
                ifname = InterfaceNameForID(m, InterfaceID);
                if (cr->CRActiveQuestion) CacheActive++;
                PrintOneCacheRecordToFD(fd, cr, slot, remain, ifname, countPtr);
                PrintCachedRecordsToFD(fd, cr, slot, remain, ifname, countPtr);
            }
        }
    }

    CacheUsed = groupCount + mcastRecordCount + ucastRecordCount;
    if (m->rrcache_totalused != CacheUsed)
        LogToFD(fd, "Cache use mismatch: rrcache_totalused is %lu, true count %lu", m->rrcache_totalused, CacheUsed);
    if (m->rrcache_active != CacheActive)
        LogToFD(fd, "Cache use mismatch: rrcache_active is %lu, true count %lu", m->rrcache_active, CacheActive);
    LogToFD(fd, "Cache size %u entities; %u in use (%u group, %u multicast, %u unicast); %u referenced by active questions",
              m->rrcache_size, CacheUsed, groupCount, mcastRecordCount, ucastRecordCount, CacheActive);

    LogToFD(fd, "--------- Auth Records ---------");
    LogAuthRecordsToFD(fd, now, m->ResourceRecords, mDNSNULL);

    LogToFD(fd, "--------- LocalOnly, P2P Auth Records ---------");
    LogLocalOnlyAuthRecordsToFD(fd, m);

    LogToFD(fd, "--------- /etc/hosts ---------");
    LogEtcHostsToFD(fd, m);

    LogToFD(fd, "------ Duplicate Records -------");
    LogAuthRecordsToFD(fd, now, m->DuplicateRecords, mDNSNULL);

    LogToFD(fd, "----- Auth Records Proxied -----");
    LogAuthRecordsToFD(fd, now, m->ResourceRecords, &ProxyA);

    LogToFD(fd, "-- Duplicate Records Proxied ---");
    LogAuthRecordsToFD(fd, now, m->DuplicateRecords, &ProxyD);

    LogToFD(fd, "---------- Questions -----------");
    if (!m->Questions) LogToFD(fd, "<None>");
    else
    {
        CacheUsed = 0;
        CacheActive = 0;
        LogToFD(fd, "   Int  Next if     T NumAns VDNS                               Qptr               DupOf              SU SQ Type Name");
        for (q = m->Questions; q; q=q->next)
        {
            mDNSs32 i = q->ThisQInterval / mDNSPlatformOneSecond;
            mDNSs32 n = (NextQSendTime(q) - now) / mDNSPlatformOneSecond;
            char *ifname = InterfaceNameForID(m, q->InterfaceID);
            CacheUsed++;
            if (q->ThisQInterval) CacheActive++;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
            LogToFD(fd, "%6d%6d %-7s%s %5d 0x%p 0x%p %1d %2d  %-5s%##s%s",
#else
            LogToFD(fd, "%6d%6d %-7s%s %5d 0x%08x%08x%08x%08x 0x%p 0x%p %1d %2d  %-5s%##s%s",
#endif
                      i, n,
                      ifname ? ifname : mDNSOpaque16IsZero(q->TargetQID) ? "" : "-U-",
                      mDNSOpaque16IsZero(q->TargetQID) ? (q->LongLived ? "l" : " ") : (q->LongLived ? "L" : "O"),
                      q->CurrentAnswers,
#if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
                      q->validDNSServers.l[3], q->validDNSServers.l[2], q->validDNSServers.l[1], q->validDNSServers.l[0],
#endif
                      q, q->DuplicateOf,
                      q->SuppressUnusable, q->Suppressed, DNSTypeName(q->qtype), q->qname.c,
                      q->DuplicateOf ? " (dup)" : "");
        }
        LogToFD(fd, "%lu question%s; %lu active", CacheUsed, CacheUsed > 1 ? "s" : "", CacheActive);
    }

    LogToFD(fd, "----- LocalOnly, P2P Questions -----");
    if (!m->LocalOnlyQuestions) LogToFD(fd, "<None>");
    else for (q = m->LocalOnlyQuestions; q; q=q->next)
        LogToFD(fd, "                 %3s   %5d  %-6s%##s%s",
                  q->InterfaceID == mDNSInterface_LocalOnly ? "LO ": q->InterfaceID == mDNSInterface_BLE ? "BLE": "P2P",
                  q->CurrentAnswers, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");

    LogToFD(fd, "---- Active UDS Client Requests ----");
    if (!all_requests) LogToFD(fd, "<None>");
    else
    {
        request_state *req, *r;
        for (req = all_requests; req; req=req->next)
        {
            if (req->primary)   // If this is a subbordinate operation, check that the parent is in the list
            {
                for (r = all_requests; r && r != req; r=r->next) if (r == req->primary) goto foundparent;
                LogToFD(fd, "%3d: Orhpan operation %p; parent %p not found in request list", req->sd);
            }
            // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
            LogClientInfoToFD(fd, req);
        foundparent:;
        }
    }

    LogToFD(fd, "-------- NAT Traversals --------");
    LogToFD(fd, "ExtAddress %.4a Retry %d Interval %d",
              &m->ExtAddress,
              m->retryGetAddr ? (m->retryGetAddr - now) / mDNSPlatformOneSecond : 0,
              m->retryIntervalGetAddr / mDNSPlatformOneSecond);
    if (m->NATTraversals)
    {
        const NATTraversalInfo *nat;
        for (nat = m->NATTraversals; nat; nat=nat->next)
        {
            LogToFD(fd, "%p %s Int %5d %s Err %d Retry %5d Interval %5d Expire %5d Req %.4a:%d Ext %.4a:%d",
                      nat,
                      nat->Protocol ? (nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP") : "ADD",
                      mDNSVal16(nat->IntPort),
                      (nat->lastSuccessfulProtocol == NATTProtocolNone    ? "None    " :
                       nat->lastSuccessfulProtocol == NATTProtocolNATPMP  ? "NAT-PMP " :
                       nat->lastSuccessfulProtocol == NATTProtocolUPNPIGD ? "UPnP/IGD" :
                       nat->lastSuccessfulProtocol == NATTProtocolPCP     ? "PCP     " :
                       /* else */                                           "Unknown " ),
                      nat->Result,
                      nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
                      nat->retryInterval / mDNSPlatformOneSecond,
                      nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
                      &nat->NewAddress, mDNSVal16(nat->RequestedPort),
                      &nat->ExternalAddress, mDNSVal16(nat->ExternalPort));
        }
    }

    LogToFD(fd, "--------- AuthInfoList ---------");
    if (!m->AuthInfoList) LogToFD(fd, "<None>");
    else
    {
        const DomainAuthInfo *a;
        for (a = m->AuthInfoList; a; a = a->next)
        {
            LogToFD(fd, "%##s %##s %##s %d %d",
                      a->domain.c, a->keyname.c,
                      a->hostname.c, (a->port.b[0] << 8 | a->port.b[1]),
                      (a->deltime ? (a->deltime - now) : 0));
        }
    }

    LogToFD(fd, "---------- Misc State ----------");

    LogToFD(fd, "PrimaryMAC:   %.6a", &m->PrimaryMAC);

    LogToFD(fd, "m->SleepState %d (%s) seq %d",
              m->SleepState,
              m->SleepState == SleepState_Awake        ? "Awake"        :
              m->SleepState == SleepState_Transferring ? "Transferring" :
              m->SleepState == SleepState_Sleeping     ? "Sleeping"     : "?",
              m->SleepSeqNum);

    if (!m->SPSSocket) LogToFD(fd, "Not offering Sleep Proxy Service");
#ifndef SPC_DISABLED
    else LogToFD(fd, "Offering Sleep Proxy Service: %#s", m->SPSRecords.RR_SRV.resrec.name->c);
#endif
    if (m->ProxyRecords == ProxyA + ProxyD) LogToFD(fd, "ProxyRecords: %d + %d = %d", ProxyA, ProxyD, ProxyA + ProxyD);
    else LogToFD(fd, "ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA, ProxyD, ProxyA + ProxyD, m->ProxyRecords);

    LogToFD(fd, "------ Auto Browse Domains -----");
    if (!AutoBrowseDomains) LogToFD(fd, "<None>");
    else for (d=AutoBrowseDomains; d; d=d->next) LogToFD(fd, "%##s", d->name.c);

    LogToFD(fd, "--- Auto Registration Domains --");
    if (!AutoRegistrationDomains) LogToFD(fd, "<None>");
    else for (d=AutoRegistrationDomains; d; d=d->next) LogToFD(fd, "%##s", d->name.c);

    LogToFD(fd, "--- Search Domains --");
    if (!SearchList) LogToFD(fd, "<None>");
    else
    {
        for (s=SearchList; s; s=s->next)
        {
            char *ifname = InterfaceNameForID(m, s->InterfaceID);
            LogToFD(fd, "%##s %s", s->domain.c, ifname ? ifname : "");
        }
    }
    LogMDNSStatisticsToFD(fd, m);

    LogToFD(fd, "---- Task Scheduling Timers ----");

#if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
    LogToFD(fd, "BonjourEnabled %d", m->BonjourEnabled);
#endif

#if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
    LogToFD(fd, "EnableBLEBasedDiscovery %d", EnableBLEBasedDiscovery);
    LogToFD(fd, "DefaultToBLETriggered %d", DefaultToBLETriggered);
#endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR

    if (!m->NewQuestions)
        LogToFD(fd, "NewQuestion <NONE>");
    else
        LogToFD(fd, "NewQuestion DelayAnswering %d %d %##s (%s)",
                  m->NewQuestions->DelayAnswering, m->NewQuestions->DelayAnswering-now,
                  m->NewQuestions->qname.c, DNSTypeName(m->NewQuestions->qtype));

    if (!m->NewLocalOnlyQuestions)
        LogToFD(fd, "NewLocalOnlyQuestions <NONE>");
    else
        LogToFD(fd, "NewLocalOnlyQuestions %##s (%s)",
                  m->NewLocalOnlyQuestions->qname.c, DNSTypeName(m->NewLocalOnlyQuestions->qtype));

    if (!m->NewLocalRecords)
        LogToFD(fd, "NewLocalRecords <NONE>");
    else
        LogToFD(fd, "NewLocalRecords %02X %s", m->NewLocalRecords->resrec.RecordType, ARDisplayString(m, m->NewLocalRecords));

    LogToFD(fd, "SPSProxyListChanged%s", m->SPSProxyListChanged ? "" : " <NONE>");
    LogToFD(fd, "LocalRemoveEvents%s",   m->LocalRemoveEvents   ? "" : " <NONE>");
    LogToFD(fd, "m->WABBrowseQueriesCount %d", m->WABBrowseQueriesCount);
    LogToFD(fd, "m->WABLBrowseQueriesCount %d", m->WABLBrowseQueriesCount);
    LogToFD(fd, "m->WABRegQueriesCount %d", m->WABRegQueriesCount);
    LogToFD(fd, "m->AutoTargetServices %u", m->AutoTargetServices);
#if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
    LogToFD(fd, "m->AutoTargetAWDLIncludedCount %u", m->AutoTargetAWDLIncludedCount);
    LogToFD(fd, "m->AutoTargetAWDLOnlyCount     %u", m->AutoTargetAWDLOnlyCount);
#endif

    LogToFD(fd, "                         ABS (hex)  ABS (dec)  REL (hex)  REL (dec)");
    LogToFD(fd, "m->timenow               %08X %11d", now, now);
    LogToFD(fd, "m->timenow_adjust        %08X %11d", m->timenow_adjust, m->timenow_adjust);
    LogTimerToFD(fd, "m->NextScheduledEvent   ", m->NextScheduledEvent);

#ifndef UNICAST_DISABLED
    LogTimerToFD(fd, "m->NextuDNSEvent        ", m->NextuDNSEvent);
    LogTimerToFD(fd, "m->NextSRVUpdate        ", m->NextSRVUpdate);
    LogTimerToFD(fd, "m->NextScheduledNATOp   ", m->NextScheduledNATOp);
    LogTimerToFD(fd, "m->retryGetAddr         ", m->retryGetAddr);
#endif

    LogTimerToFD(fd, "m->NextCacheCheck       ", m->NextCacheCheck);
    LogTimerToFD(fd, "m->NextScheduledSPS     ", m->NextScheduledSPS);
    LogTimerToFD(fd, "m->NextScheduledKA      ", m->NextScheduledKA);

#if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
    LogTimerToFD(fd, "m->NextBonjourDisableTime ", m->NextBonjourDisableTime);
#endif

    LogTimerToFD(fd, "m->NextScheduledSPRetry ", m->NextScheduledSPRetry);
    LogTimerToFD(fd, "m->DelaySleep           ", m->DelaySleep);

    LogTimerToFD(fd, "m->NextScheduledQuery   ", m->NextScheduledQuery);
    LogTimerToFD(fd, "m->NextScheduledProbe   ", m->NextScheduledProbe);
    LogTimerToFD(fd, "m->NextScheduledResponse", m->NextScheduledResponse);

    LogTimerToFD(fd, "m->SuppressSending      ", m->SuppressSending);
    LogTimerToFD(fd, "m->SuppressProbes       ", m->SuppressProbes);
    LogTimerToFD(fd, "m->ProbeFailTime        ", m->ProbeFailTime);
    LogTimerToFD(fd, "m->DelaySleep           ", m->DelaySleep);
    LogTimerToFD(fd, "m->SleepLimit           ", m->SleepLimit);
    LogTimerToFD(fd, "m->NextScheduledStopTime ", m->NextScheduledStopTime);
}

#if MDNS_MALLOC_DEBUGGING
mDNSlocal void udsserver_validatelists(void *context)
{
    const request_state *req, *p;
	(void)context; // unused
    for (req = all_requests; req; req=req->next)
    {
        if (req->next == (request_state *)~0 || (req->sd < 0 && req->sd != -2))
            LogMemCorruption("UDS request list: %p is garbage (%d)", req, req->sd);

        if (req->primary == req)
            LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req, req->sd);

        if (req->primary && req->replies)
            LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
                             req, req->sd, req->primary && req->replies);

        p = req->primary;
        if ((long)p & 3)
            LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req, p, req->sd);
        else if (p && (p->next == (request_state *)~0 || (p->sd < 0 && p->sd != -2)))
            LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req, p, p->sd);

        reply_state *rep;
        for (rep = req->replies; rep; rep=rep->next)
            if (rep->next == (reply_state *)~0)
                LogMemCorruption("UDS req->replies: %p is garbage", rep);

        if (req->terminate == connection_termination)
        {
            registered_record_entry *r;
            for (r = req->u.reg_recs; r; r=r->next)
                if (r->next == (registered_record_entry *)~0)
                    LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r);
        }
        else if (req->terminate == regservice_termination_callback)
        {
            service_instance *s;
            for (s = req->u.servicereg.instances; s; s=s->next)
                if (s->next == (service_instance *)~0)
                    LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s);
        }
        else if (req->terminate == browse_termination_callback)
        {
            browser_t *b;
            for (b = req->u.browser.browsers; b; b=b->next)
                if (b->next == (browser_t *)~0)
                    LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b);
        }
    }

    DNameListElem *d;
    for (d = SCPrefBrowseDomains; d; d=d->next)
        if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
            LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);

    ARListElem *b;
    for (b = LocalDomainEnumRecords; b; b=b->next)
        if (b->next == (ARListElem *)~0 || b->ar.resrec.name->c[0] > 63)
            LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b, b->ar.resrec.name->c[0]);

    for (d = AutoBrowseDomains; d; d=d->next)
        if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
            LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);

    for (d = AutoRegistrationDomains; d; d=d->next)
        if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
            LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d, d->name.c[0]);
}
#endif // MDNS_MALLOC_DEBUGGING

mDNSlocal int send_msg(request_state *const req)
{
    reply_state *const rep = req->replies;      // Send the first waiting reply
    ssize_t nwriten;

    ConvertHeaderBytes(rep->mhdr);
    nwriten = send(req->sd, (char *)&rep->mhdr + rep->nwriten, rep->totallen - rep->nwriten, 0);
    ConvertHeaderBytes(rep->mhdr);

    if (nwriten < 0)
    {
        if (dnssd_errno == dnssd_EINTR || dnssd_errno == dnssd_EWOULDBLOCK) nwriten = 0;
        else
        {
#if !defined(PLATFORM_NO_EPIPE)
            if (dnssd_errno == EPIPE)
                return(req->ts = t_terminated);
            else
#endif
            {
                LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
                       rep->totallen - rep->nwriten, rep->totallen, req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
                return(t_error);
            }
        }
    }
    rep->nwriten += nwriten;
    return (rep->nwriten == rep->totallen) ? t_complete : t_morecoming;
}

mDNSexport mDNSs32 udsserver_idle(mDNSs32 nextevent)
{
    mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
    request_state **req = &all_requests;

    while (*req)
    {
        request_state *const r = *req;

        if (r->terminate == resolve_termination_callback)
            if (r->u.resolve.ReportTime && now - r->u.resolve.ReportTime >= 0)
            {
                r->u.resolve.ReportTime = 0;
                // if client received results and resolve still active
                if (r->u.resolve.txt && r->u.resolve.srv)
                    LogMsgNoIdent("Client application PID[%d](%s) has received results for DNSServiceResolve(%##s) yet remains active over two minutes.", r->process_id, r->pid_name, r->u.resolve.qsrv.qname.c);
            }

        // Note: Only primary req's have reply lists, not subordinate req's.
        while (r->replies)      // Send queued replies
        {
            transfer_state result;
            if (r->replies->next)
                r->replies->rhdr->flags |= dnssd_htonl(kDNSServiceFlagsMoreComing);
            result = send_msg(r);   // Returns t_morecoming if buffer full because client is not reading
            if (result == t_complete)
            {
                reply_state *fptr = r->replies;
                r->replies = r->replies->next;
                freeL("reply_state/udsserver_idle", fptr);
                r->time_blocked = 0; // reset failure counter after successful send
                r->unresponsiveness_reports = 0;
                continue;
            }
            else if (result == t_terminated)
            {
                LogInfo("%3d: Could not write data to client PID[%d](%s) because connection is terminated by the client", r->sd, r->process_id, r->pid_name);
                abort_request(r);
            }
            else if (result == t_error)
            {
                LogMsg("%3d: Could not write data to client PID[%d](%s) because of error - aborting connection", r->sd, r->process_id, r->pid_name);
                LogClientInfo(r);
                abort_request(r);
            }
            break;
        }

        if (r->replies)     // If we failed to send everything, check our time_blocked timer
        {
            if (nextevent - now > mDNSPlatformOneSecond)
                nextevent = now + mDNSPlatformOneSecond;

            LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
               "[R%u] Could not send all replies. Will try again in %d ticks.", r->request_id, nextevent - now);
            if (mDNSStorage.SleepState != SleepState_Awake)
                r->time_blocked = 0;
            else if (!r->time_blocked)
                r->time_blocked = NonZeroTime(now);
            else if (now - r->time_blocked >= 10 * mDNSPlatformOneSecond * (r->unresponsiveness_reports+1))
            {
                int num = 0;
                struct reply_state *x = r->replies;
                while (x)
                {
                    num++;
                    x=x->next;
                }
                LogMsg("%3d: Could not write data to client PID[%d](%s) after %ld seconds, %d repl%s waiting",
                       r->sd, r->process_id, r->pid_name, (now - r->time_blocked) / mDNSPlatformOneSecond, num, num == 1 ? "y" : "ies");
                if (++r->unresponsiveness_reports >= 60)
                {
                    LogMsg("%3d: Client PID[%d](%s) unresponsive; aborting connection", r->sd, r->process_id, r->pid_name);
                    LogClientInfo(r);
                    abort_request(r);
                }
            }
        }

        if (!dnssd_SocketValid(r->sd)) // If this request is finished, unlink it from the list and free the memory
        {
            // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
            *req = r->next;
            freeL("request_state/udsserver_idle", r);
        }
        else
            req = &r->next;
    }
    return nextevent;
}

struct CompileTimeAssertionChecks_uds_daemon
{
    // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
    // other overly-large structures instead of having a pointer to them, can inadvertently
    // cause structure sizes (and therefore memory usage) to balloon unreasonably.
    char sizecheck_request_state          [(sizeof(request_state)           <= 3880) ? 1 : -1];
    char sizecheck_registered_record_entry[(sizeof(registered_record_entry) <=   60) ? 1 : -1];
    char sizecheck_service_instance       [(sizeof(service_instance)        <= 6552) ? 1 : -1];
    char sizecheck_browser_t              [(sizeof(browser_t)               <= 1480) ? 1 : -1];
    char sizecheck_reply_hdr              [(sizeof(reply_hdr)               <=   12) ? 1 : -1];
    char sizecheck_reply_state            [(sizeof(reply_state)             <=   64) ? 1 : -1];
};

#ifdef UNIT_TEST
#include "../unittests/uds_daemon_ut.c"
#endif  //  UNIT_TEST
/* -*- Mode: C; tab-width: 4 -*-
 *
 * Copyright (c) 2002-2020 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 UDS_DAEMON_H
#define UDS_DAEMON_H

#include "mDNSEmbeddedAPI.h"
#include "dnssd_ipc.h"
#include "ClientRequests.h"
#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
#include "mdns_private.h"
#endif

/* Client request: */

// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - Types and Data Structures
#endif

typedef enum
{
	t_uninitialized,
	t_morecoming,
	t_complete,
	t_error,
	t_terminated
} transfer_state;

typedef struct request_state request_state;

typedef void (*req_termination_fn)(request_state *request);

typedef struct registered_record_entry
{
	struct registered_record_entry *next;
	mDNSu32 key;
	client_context_t regrec_client_context;
	request_state *request;
	mDNSBool external_advertise;
	mDNSInterfaceID origInterfaceID;
	AuthRecord *rr;             // Pointer to variable-sized AuthRecord (Why a pointer? Why not just embed it here?)
} registered_record_entry;

// A single registered service: ServiceRecordSet + bookkeeping
// Note that we duplicate some fields from parent service_info object
// to facilitate cleanup, when instances and parent may be deallocated at different times.
typedef struct service_instance
{
	struct service_instance *next;
	request_state *request;
	AuthRecord *subtypes;
	mDNSBool renameonmemfree;       // Set on config change when we deregister original name
	mDNSBool clientnotified;        // Has client been notified of successful registration yet?
	mDNSBool default_local;         // is this the "local." from an empty-string registration?
	mDNSBool external_advertise;    // is this is being advertised externally?
	domainname domain;
	ServiceRecordSet srs;           // note -- variable-sized object -- must be last field in struct
} service_instance;

// for multi-domain default browsing
typedef struct browser_t
{
	struct browser_t *next;
	domainname domain;
	DNSQuestion q;
} browser_t;

#ifdef _WIN32
typedef unsigned int pid_t;
typedef unsigned int socklen_t;
#endif

#if (!defined(MAXCOMLEN))
#define MAXCOMLEN 16
#endif

struct request_state
{
	request_state *next;
	request_state *primary;         // If this operation is on a shared socket, pointer to primary
	// request_state for the original DNSServiceCreateConnection() operation
	dnssd_sock_t sd;
	pid_t process_id;               // Client's PID value
	char  pid_name[MAXCOMLEN];      // Client's process name
	mDNSu8 uuid[UUID_SIZE];
	mDNSBool validUUID;
	dnssd_sock_t errsd;
#if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
    audit_token_t audit_token;
#endif
	mDNSu32 uid;
    mDNSu32 request_id;
	void * platform_data;
#if MDNSRESPONDER_SUPPORTS(APPLE, TRUST_ENFORCEMENT)
    mdns_trust_t trust;
#endif
	// Note: On a shared connection these fields in the primary structure, including hdr, are re-used
	// for each new request. This is because, until we've read the ipc_msg_hdr to find out what the
	// operation is, we don't know if we're going to need to allocate a new request_state or not.
	transfer_state ts;
	mDNSu32 hdr_bytes;              // bytes of header already read
	ipc_msg_hdr hdr;
	mDNSu32 data_bytes;             // bytes of message data already read
	char          *msgbuf;          // pointer to data storage to pass to free()
	const char    *msgptr;          // pointer to data to be read from (may be modified)
	char          *msgend;          // pointer to byte after last byte of message

	// reply, termination, error, and client context info
	int no_reply;                   // don't send asynchronous replies to client
	mDNSs32 time_blocked;           // record time of a blocked client
	int unresponsiveness_reports;
	struct reply_state *replies;    // corresponding (active) reply list
	req_termination_fn terminate;
	DNSServiceFlags flags;
	mDNSu32 interfaceIndex;
#if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
    mdns_dns_service_id_t custom_service_id;
#endif

	union
	{
		registered_record_entry *reg_recs;  // list of registrations for a connection-oriented request
		struct
		{
			mDNSInterfaceID interface_id;
			mDNSBool default_domain;
			mDNSBool ForceMCast;
			domainname regtype;
			browser_t *browsers;
		} browser;
		struct
		{
			mDNSInterfaceID InterfaceID;
			mDNSu16 txtlen;
			void *txtdata;
			mDNSIPPort port;
			domainlabel name;
			char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
			domainname type;
			mDNSBool default_domain;
			domainname host;
			mDNSBool autoname;              // Set if this name is tied to the Computer Name
			mDNSBool autorename;            // Set if this client wants us to automatically rename on conflict
			mDNSBool allowremotequery;      // Respond to unicast queries from outside the local link?
			int num_subtypes;
			service_instance *instances;
		} servicereg;
		struct
		{
			mDNSIPPort ReqExt;              // External port we originally requested, for logging purposes
			NATTraversalInfo NATinfo;
		} pm;
		struct
		{
			DNSServiceFlags flags;
			DNSQuestion q_all;
			DNSQuestion q_default;
			DNSQuestion q_autoall;
		} enumeration;
		struct
		{
			DNSQuestion qtxt;
			DNSQuestion qsrv;
			const ResourceRecord *txt;
			const ResourceRecord *srv;
			mDNSs32 ReportTime;
			mDNSBool external_advertise;
		} resolve;
        GetAddrInfoClientRequest addrinfo;
        QueryRecordClientRequest queryrecord;
	} u;
};

// struct physically sits between ipc message header and call-specific fields in the message buffer
typedef struct
{
	DNSServiceFlags flags;          // Note: This field is in NETWORK byte order
	mDNSu32 ifi;                    // Note: This field is in NETWORK byte order
	DNSServiceErrorType error;      // Note: This field is in NETWORK byte order
} reply_hdr;

typedef struct reply_state
{
	struct reply_state *next;       // If there are multiple unsent replies
	mDNSu32 totallen;
	mDNSu32 nwriten;
	ipc_msg_hdr mhdr[1];
	reply_hdr rhdr[1];
} reply_state;

/* Client interface: */

#define SRS_PORT(S) mDNSVal16((S)->RR_SRV.resrec.rdata->u.srv.port)

#define LogTimerToFD(FILE_DESCRIPTOR, MSG, T) LogToFD((FILE_DESCRIPTOR), MSG " %08X %11d  %08X %11d", (T), (T), (T)-now, (T)-now)

extern int udsserver_init(dnssd_sock_t skts[], size_t count);
extern mDNSs32 udsserver_idle(mDNSs32 nextevent);
extern void udsserver_info_dump_to_fd(int fd);
extern void udsserver_handle_configchange(mDNS *const m);
extern int udsserver_exit(void);    // should be called prior to app exit
extern void LogMcastStateInfo(mDNSBool mflag, mDNSBool start, mDNSBool mstatelog);
#define LogMcastQ       (mDNS_McastLoggingEnabled == 0) ? ((void)0) : LogMcastQuestion
#define LogMcastS       (mDNS_McastLoggingEnabled == 0) ? ((void)0) : LogMcastService
#define LogMcast        (mDNS_McastLoggingEnabled == 0) ? ((void)0) : LogMsg
#define LogMcastNoIdent (mDNS_McastLoggingEnabled == 0) ? ((void)0) : LogMsgNoIdent

/* Routines that uds_daemon expects to link against: */

typedef void (*udsEventCallback)(int fd, void *context);
extern mStatus udsSupportAddFDToEventLoop(dnssd_sock_t fd, udsEventCallback callback, void *context, void **platform_data);
extern int     udsSupportReadFD(dnssd_sock_t fd, char* buf, int len, int flags, void *platform_data);
extern mStatus udsSupportRemoveFDFromEventLoop(dnssd_sock_t fd, void *platform_data); // Note: This also CLOSES the file descriptor as well

extern void RecordUpdatedNiceLabel(mDNSs32 delay);

// Globals and functions defined in uds_daemon.c and also shared with the old "daemon.c" on OS X

extern mDNS mDNSStorage;
extern DNameListElem *AutoRegistrationDomains;
extern DNameListElem *AutoBrowseDomains;

extern int CountExistingRegistrations(domainname *srv, mDNSIPPort port);
extern void FreeExtraRR(mDNS *const m, AuthRecord *const rr, mStatus result);
extern int CountPeerRegistrations(ServiceRecordSet *const srs);

extern const char mDNSResponderVersionString_SCCS[];
#define mDNSResponderVersionString (mDNSResponderVersionString_SCCS+5)

#if DEBUG
extern void SetDebugBoundPath(void);
extern int IsDebugSocketInUse(void);
#endif

#endif /* UDS_DAEMON_H */