Codebase list getdns / upstream/1.6.0 src / mdns.c
upstream/1.6.0

Tree @upstream/1.6.0 (Download .tar.gz)

mdns.c @upstream/1.6.0raw · history · blame

   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
/*
 * Functions for MDNS resolving.
 */

 /*
  * Copyright (c) 2016 Christian Huitema <huitema@huitema.net>
  *
  * Permission to use, copy, modify, and distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
  * copyright notice and this permission notice appear in all copies.
  *
  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */


#include "config.h"
#include "debug.h"
#include "context.h"
#include "general.h"
#include "gldns/pkthdr.h"
#include "gldns/rrdef.h"
#include "util-internal.h"
#include "platform.h"
#include "mdns.h"

#ifdef HAVE_MDNS_SUPPORT

/* Define IPV6_ADD_MEMBERSHIP for FreeBSD and Mac OS X */
#ifndef IPV6_ADD_MEMBERSHIP
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#endif

uint64_t _getdns_get_time_as_uintt64();

#include "util/fptr_wlist.h"
#include "util/lookup3.h"

/*
 * Constants defined in RFC 6762
 */

#define MDNS_MCAST_IPV4_LONG 0xE00000FB /* 224.0.0.251 */
#define MDNS_MCAST_PORT 5353

static uint8_t mdns_mcast_ipv6[] = {
	0xFF, 0x02, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0xFB 
};

static uint8_t mdns_suffix_dot_local[] = { 5, 'l', 'o', 'c', 'a', 'l', 0 };
static uint8_t mdns_suffix_254_169_in_addr_arpa[] = {
	3, '2', '5', '4',
	3, '1', '6', '9',
	7, 'i', 'n', '-', 'a', 'd', 'd', 'r',
	4, 'a', 'r', 'p', 'a', 0 };
static uint8_t mdns_suffix_8_e_f_ip6_arpa[] = {
	1, '8', 1, 'e', 1, 'f',
	3, 'i', 'p', '6',
	4, 'a', 'r', 'p', 'a', 0 };
static uint8_t mdns_suffix_9_e_f_ip6_arpa[] = {
	1, '9', 1, 'e', 1, 'f',
	3, 'i', 'p', '6',
	4, 'a', 'r', 'p', 'a', 0 };
static uint8_t mdns_suffix_a_e_f_ip6_arpa[] = {
	1, 'a', 1, 'e', 1, 'f',
	3, 'i', 'p', '6',
	4, 'a', 'r', 'p', 'a', 0 };
static uint8_t mdns_suffix_b_e_f_ip6_arpa[] = {
	1, 'b', 1, 'e', 1, 'f',
	3, 'i', 'p', '6',
	4, 'a', 'r', 'p', 'a', 0 };

#define MDNS_PACKET_INDEX_QCODE 2
#define MDNS_PACKET_INDEX_QUERY 4
#define MDNS_PACKET_INDEX_ANSWER 6

/*
 * MDNS cache management using LRU Hash.
 *
 * Each record contains a DNS query + response, formatted as received from
 * the network. By convention, there will be exactly one query, and
 * a variable number of answers. Auth and AD sections will not be cached.
 * For maintenance purpose, each recontains a last accessed time stamp.
 *
 * This structure works very well for classic DNS caches, but for MDNS we 
 * have to consider processing a new record for an existing cache entry. If
 * the record is present, its TTL should be updated. If the record is not
 * present, it should be added to the existing data.
 *
 * After an update, the TTL of all the records should be updated. Some
 * records will end up with a TTL value of zero. These records should be 
 * deleted, using a "compression" procedure.
 */



/*
 * For the data part, we want to allocate in rounded increments, so as to reduce the
 * number of calls to XMALLOC
 */

static uint32_t 
mdns_util_suggest_size(uint32_t required_size)
{
	return (required_size <= 512) ? ((required_size <= 256) ? 256 : 512) :
		((required_size + 1023) & 0xFFFFFC00);
}

/*
 * Cache management utilities
 */
static int
mdns_util_skip_name(uint8_t *p)
{
	int x = 0;
	int l;

	for (;;) {
		l = p[x];
		if (l == 0)
		{
			x++;
			break;
		}
		else if (l >= 0xC0)
		{
			x += 2;
			break;
		}
		else
		{
			x += l + 1;
		}
	}
	return x;
}

static size_t 
mdns_util_copy_name(uint8_t * message, size_t message_length, size_t current_index,
	uint8_t *name, int name_len_max, int name_index, int * name_len)
{
	uint8_t l;
	size_t recursive_index;

	*name_len = 0;
	while (current_index < message_length && name_index < name_len_max) {
		l = message[current_index++];
		if (l == 0)
		{
			name[name_index++] = 0;
			*name_len = name_index;
			break;
		}
		else if (l >= 0xC0)
		{
			if (current_index < message_length)
			{
				recursive_index = ((l & 63) << 8) | message[current_index++];

				(void) mdns_util_copy_name(message, message_length, 
					recursive_index, name, name_len_max, name_index, name_len);

				if (*name_len == 0)
				{
					current_index = message_length;
				}
			}
			break;
		}
		else if (current_index + l < message_length &&
			name_index + l + 1 < name_len_max)
		{
			name[name_index++] = l;

			memcpy(name + name_index, message + current_index, l);
			name_index += l;
			current_index += l;
		}
		else
		{
			current_index = message_length;
			break;
		}
	}

	return current_index;
}

static int
mdns_util_skip_query(uint8_t *p)
{
	return mdns_util_skip_name(p) + 4;
}

/*
 * Single copy procedure for many record types
 * copy N octets, then the canonical value of the name.
 */
static int
mdns_util_canonical_flags_and_name(uint8_t *message, int message_length,
	int record_length,
	int current_index,
	int nb_octets_to_copy,
	uint8_t *buffer, int buffer_max,
	uint8_t **actual_record, int *actual_length)
{
	int ret = 0;
	int buffer_index = 0;
	int name_len = 0;

	if (buffer_max <= nb_octets_to_copy || record_length <= nb_octets_to_copy)
	{
		/* incorrect buffer */
		ret = GETDNS_RETURN_GENERIC_ERROR;
	}
	else
	{
		int i;
		for (i = 0; i < nb_octets_to_copy; i++)
		{
			buffer[buffer_index++] = message[current_index++];
		}

		current_index = mdns_util_copy_name(message, message_length, current_index, buffer, buffer_max, buffer_index, &name_len);
		if (current_index == record_length)
		{
			buffer_index += name_len;
			*actual_record = buffer;
			*actual_length = buffer_index;
		}
		else
		{
			/* something went wrong. */
			ret = GETDNS_RETURN_BAD_DOMAIN_NAME;
		}
	}

	return ret;
}
/*
 * Set record value to canonical form
 */
static int
mdns_util_canonical_record(uint8_t *message, int message_length,
	int record_type, int record_class, int record_length,
	int record_index,  
	uint8_t *buffer, int buffer_max,
	uint8_t **actual_record, int *actual_length)
{
	int ret = 0;
	int current_index = record_index;
	/* Check whether the record needs canonization */
	*actual_record = message + record_index;
	*actual_length = record_length;

	if (record_class != GLDNS_RR_CLASS_IN)
	{
		/*
		 * No attempt at canonization outside the IN class.
		 */
		return 0;
	}
	
	switch (record_type)
	{
		
	case GLDNS_RR_TYPE_NS:
	case GLDNS_RR_TYPE_CNAME:
	case GLDNS_RR_TYPE_PTR:
	case GLDNS_RR_TYPE_MD:
	case GLDNS_RR_TYPE_MB:
	case GLDNS_RR_TYPE_MF:
	case GLDNS_RR_TYPE_MG:
	case GLDNS_RR_TYPE_MR:
	case GLDNS_RR_TYPE_NSAP_PTR:
		/* 
		 * copy the name in canonical form 
		 */
		ret = mdns_util_canonical_flags_and_name(message, message_length,
			record_length, current_index, 0,
			buffer, buffer_max, actual_record, actual_length);
		break;

	case GLDNS_RR_TYPE_A:
	case GLDNS_RR_TYPE_AAAA:
	case GLDNS_RR_TYPE_TXT:
	case GLDNS_RR_TYPE_HINFO:
	case GLDNS_RR_TYPE_MINFO:
	case GLDNS_RR_TYPE_NULL:
	case GLDNS_RR_TYPE_WKS:
	case GLDNS_RR_TYPE_X25:
	case GLDNS_RR_TYPE_ISDN:
	case GLDNS_RR_TYPE_NSAP:
	case GLDNS_RR_TYPE_SIG:
	case GLDNS_RR_TYPE_KEY:
	case GLDNS_RR_TYPE_GPOS:
	case GLDNS_RR_TYPE_LOC:
	case GLDNS_RR_TYPE_EID:
	case GLDNS_RR_TYPE_NIMLOC:
		/* leave the content as is, no domain name in content */
		break;

	case GLDNS_RR_TYPE_SRV:
		/*
		 * Copy 6 octets for weight(2), priority(2) and port(2),
		 * then copy the name.
		 */
		ret = mdns_util_canonical_flags_and_name(message, message_length,
			record_length, current_index, 6,
			buffer, buffer_max, actual_record, actual_length);
		break;

	case GLDNS_RR_TYPE_MX:
	case GLDNS_RR_TYPE_RT:
	case GLDNS_RR_TYPE_AFSDB:
		/* 
		 * copy two bytes preference or subtype, then 
		 * copy the name in canonical form 
		 */
		ret = mdns_util_canonical_flags_and_name(message, message_length,
			record_length, current_index, 2,
			buffer, buffer_max, actual_record, actual_length);
		break;

	case GLDNS_RR_TYPE_NAPTR:
	case GLDNS_RR_TYPE_SOA:
	case GLDNS_RR_TYPE_RP:
	case GLDNS_RR_TYPE_NXT:
	case GLDNS_RR_TYPE_PX:
	case GLDNS_RR_TYPE_ATMA:
		/*
		 * Group of record types that are complex, and also
		 * unexpected in MDNS/DNS-SD operation. Copying the 
		 * record directly will work as long as the sender
		 * does not attempt name compression.
		 * TODO: log some kind of error.
		 */
		break;
#if 0

			/**  RFC2915 */
			GLDNS_RR_TYPE_NAPTR = 35,
			/**  RFC2230 */
			GLDNS_RR_TYPE_KX = 36,
			/**  RFC2538 */
			GLDNS_RR_TYPE_CERT = 37,
			/**  RFC2874 */
			GLDNS_RR_TYPE_A6 = 38,
			/**  RFC2672 */
			GLDNS_RR_TYPE_DNAME = 39,
			/**  dnsind-kitchen-sink-02.txt */
			GLDNS_RR_TYPE_SINK = 40,
			/**  Pseudo OPT record... */
			GLDNS_RR_TYPE_OPT = 41,
			/**  RFC3123 */
			GLDNS_RR_TYPE_APL = 42,
			/**  RFC4034, RFC3658 */
			GLDNS_RR_TYPE_DS = 43,
			/**  SSH Key Fingerprint */
			GLDNS_RR_TYPE_SSHFP = 44, /* RFC 4255 */
									  /**  IPsec Key */
			GLDNS_RR_TYPE_IPSECKEY = 45, /* RFC 4025 */
										 /**  DNSSEC */
			GLDNS_RR_TYPE_RRSIG = 46, /* RFC 4034 */
			GLDNS_RR_TYPE_NSEC = 47, /* RFC 4034 */
			GLDNS_RR_TYPE_DNSKEY = 48, /* RFC 4034 */

			GLDNS_RR_TYPE_DHCID = 49, /* RFC 4701 */
									  /* NSEC3 */
			GLDNS_RR_TYPE_NSEC3 = 50, /* RFC 5155 */
			GLDNS_RR_TYPE_NSEC3PARAM = 51, /* RFC 5155 */
			GLDNS_RR_TYPE_NSEC3PARAMS = 51,
			GLDNS_RR_TYPE_TLSA = 52, /* RFC 6698 */
			GLDNS_RR_TYPE_SMIMEA = 53, /* draft-ietf-dane-smime, TLSA-like but may
									   be extended */

			GLDNS_RR_TYPE_HIP = 55, /* RFC 5205 */

									/** draft-reid-dnsext-zs */
			GLDNS_RR_TYPE_NINFO = 56,
			/** draft-reid-dnsext-rkey */
			GLDNS_RR_TYPE_RKEY = 57,
			/** draft-ietf-dnsop-trust-history */
			GLDNS_RR_TYPE_TALINK = 58,
			GLDNS_RR_TYPE_CDS = 59, /** RFC 7344 */
			GLDNS_RR_TYPE_CDNSKEY = 60, /** RFC 7344 */
			GLDNS_RR_TYPE_OPENPGPKEY = 61, /* RFC 7929 */
			GLDNS_RR_TYPE_CSYNC = 62, /* RFC 7477 */

			GLDNS_RR_TYPE_SPF = 99, /* RFC 4408 */

			GLDNS_RR_TYPE_UINFO = 100,
			GLDNS_RR_TYPE_UID = 101,
			GLDNS_RR_TYPE_GID = 102,
			GLDNS_RR_TYPE_UNSPEC = 103,

			GLDNS_RR_TYPE_NID = 104, /* RFC 6742 */
			GLDNS_RR_TYPE_L32 = 105, /* RFC 6742 */
			GLDNS_RR_TYPE_L64 = 106, /* RFC 6742 */
			GLDNS_RR_TYPE_LP = 107, /* RFC 6742 */

									/** draft-jabley-dnsext-eui48-eui64-rrtypes */
			GLDNS_RR_TYPE_EUI48 = 108,
			GLDNS_RR_TYPE_EUI64 = 109,

			GLDNS_RR_TYPE_TKEY = 249, /* RFC 2930 */
			GLDNS_RR_TYPE_TSIG = 250,
			GLDNS_RR_TYPE_IXFR = 251,
			GLDNS_RR_TYPE_AXFR = 252,
			/**  A request for mailbox-related records (MB, MG or MR) */
			GLDNS_RR_TYPE_MAILB = 253,
			/**  A request for mail agent RRs (Obsolete - see MX) */
			GLDNS_RR_TYPE_MAILA = 254,
			/**  any type (wildcard) */
			GLDNS_RR_TYPE_ANY = 255,
			GLDNS_RR_TYPE_URI = 256, /* RFC 7553 */
			GLDNS_RR_TYPE_CAA = 257, /* RFC 6844 */
#endif
	default:
		/* 
		 * Unknown record type. Not expected in MDNS/DNS-SD. Just keep the current value. 
		 * TODO: log some kind of error.
		 */
		break;
	}

	return ret;
}
/*
 * Comparison and other functions required for cache management
 */

 /**
 * Calculates the size of an entry.
 *
 * size = mdns_cache_size (key, data).
 */
static size_t mdns_cache_entry_size(void* vkey, void* vdata)
{
	size_t sz = 0;

	if (vkey != NULL)
	{
		sz += sizeof(getdns_mdns_cached_key_header) + ((getdns_mdns_cached_key_header*)vkey)->name_len;
	}

	if (vdata != NULL)
	{
		sz += ((getdns_mdns_cached_record_header*)vdata)->allocated_length;
	}

	return  sz;
}

/** type of function that compares two keys. return 0 if equal. */
static int mdns_cache_key_comp(void* vkey1, void* vkey2)
{
	getdns_mdns_cached_key_header *header1 = (getdns_mdns_cached_key_header*)vkey1;
	getdns_mdns_cached_key_header *header2 = (getdns_mdns_cached_key_header*)vkey2;

	return (header1->record_type == header2->record_type &&
		header1->record_class == header2->record_class &&
		header1->name_len == header2->name_len)
		? memcmp(((uint8_t*)vkey1) + sizeof(getdns_mdns_cached_key_header),
			((uint8_t*)vkey2) + sizeof(getdns_mdns_cached_key_header),
			header1->name_len)
		: -1;
}

/** old keys are deleted.
* markdel() is used first.
* This function is called: func(key, userarg)
* the userarg is set to the context in which the LRU hash table was created.
* TODO: is there a need to free the lock in the embedded hash entry structure?
*/
static void msdn_cache_delkey(void* vkey, void* vcontext)
{
	GETDNS_FREE(((struct getdns_context *) vcontext)->mf, vkey);
}

/** old data is deleted. This function is called: func(data, userarg). 
 * Since we use the hash table for both data and requests, need to
 * terminate whatever request was ongoing. TODO: we should have some smarts
 * in cache management and never drop cached entries with active requests.
 */
static void msdn_cache_deldata(void* vdata, void* vcontext)
{
	getdns_mdns_cached_record_header* header = ((getdns_mdns_cached_record_header*)vdata);

	while (header->netreq_first)
	{
		/* Need to unchain the request from that entry */
		getdns_network_req* netreq = header->netreq_first;
		header->netreq_first = netreq->mdns_netreq_next;
		netreq->mdns_netreq_next = NULL;

		/* TODO: treating as a timeout for now, may consider treating as error */
		netreq->debug_end_time = _getdns_get_time_as_uintt64();
		_getdns_netreq_change_state(netreq, NET_REQ_TIMED_OUT);
		if (netreq->owner->user_callback) {
			(void)_getdns_context_request_timed_out(netreq->owner);
		}
		_getdns_check_dns_req_complete(netreq->owner);

	}
	GETDNS_FREE(((struct getdns_context *) vcontext)->mf, vdata);
}

/*
 * Read the number of answers in a cached record
 */
static int
mdns_cache_nb_records_in_entry(uint8_t * cached_data)
{
	int message_index = sizeof(getdns_mdns_cached_record_header);
	int nb_answers = (cached_data[message_index + MDNS_PACKET_INDEX_ANSWER] << 8) | 
		cached_data[message_index + MDNS_PACKET_INDEX_ANSWER + 1];

	return nb_answers;
}

/*
 * Create a key in preallocated buffer
 * the allocated size of key should be >= sizeof(getdns_mdns_cached_key_header) + name_len
 */
static void msdn_cache_create_key_in_buffer(
	uint8_t* key, 
	uint8_t * name, int name_len,
	int record_type, int record_class)
{
	getdns_mdns_cached_key_header * header = (getdns_mdns_cached_key_header*)key;

	memset(key, 0, sizeof(getdns_mdns_cached_key_header));
	header->record_type = record_type;
	header->record_class = record_class;
	header->name_len = name_len;
	(void) memcpy(key + sizeof(getdns_mdns_cached_key_header), name, name_len);
}

static uint8_t * mdns_cache_create_key(
	uint8_t * name, int name_len,
	int record_type, int record_class,
	struct getdns_context * context)
{
	uint8_t* key = GETDNS_XMALLOC(context->mf, uint8_t, sizeof(getdns_mdns_cached_key_header) + name_len);

	if (key != NULL)
	{
		msdn_cache_create_key_in_buffer(key, name, name_len, record_type, record_class);
	}

	return key;
}

static uint8_t * mdns_cache_create_data(
	uint8_t * name, int name_len,
	int record_type, int record_class,
	int record_data_len,
	uint64_t current_time,
	struct getdns_context * context)
{
	getdns_mdns_cached_record_header * header;
	int current_index;
	size_t data_size = sizeof(getdns_mdns_cached_record_header) + 12 + name_len + 4;
	size_t alloc_size = mdns_util_suggest_size(data_size + record_data_len + 2 + 2 + 2 + 4 + 2);

	uint8_t* data = GETDNS_XMALLOC(context->mf, uint8_t, alloc_size);

	if (data != NULL)
	{
		header = (getdns_mdns_cached_record_header *)data;
		header->insertion_microsec = current_time;
		header->content_len = data_size;
		header->allocated_length = alloc_size;
		header->netreq_first = NULL;
		current_index = sizeof(getdns_mdns_cached_record_header);
		memset(data + current_index, 0, 12);
		data[current_index + MDNS_PACKET_INDEX_QUERY + 1] = 1; /* 1 query present by default */
		current_index += 12;
		memcpy(data + current_index, name, name_len);
		current_index += name_len;
		data[current_index++] = (uint8_t)(record_type >> 8);
		data[current_index++] = (uint8_t)(record_type);
		data[current_index++] = (uint8_t)(record_class >> 8);
		data[current_index++] = (uint8_t)(record_class);
	}

	return data;
}


/*
 * Add a record.
 */
static int
mdns_add_record_to_cache_entry(struct getdns_context *context,
	uint8_t * old_record, uint8_t ** new_record,
	int record_type, int record_class, int ttl,
	uint8_t * record_data, int record_data_len)
{
	int ret = 0;
	getdns_mdns_cached_record_header *header = (getdns_mdns_cached_record_header*)old_record;
	/* Compute the record length */
	uint32_t record_length = 2 + 2 + 2 + 4 + 2 + record_data_len;
	uint32_t current_length = header->content_len;
	/* update the number of records */
	uint8_t *start_answer_code = old_record + sizeof(getdns_mdns_cached_record_header) + MDNS_PACKET_INDEX_ANSWER;
	uint16_t nb_answers = (start_answer_code[0] << 8) + start_answer_code[1];
	nb_answers++;
	start_answer_code[0] = (uint8_t)(nb_answers >> 8);
	start_answer_code[1] = (uint8_t)(nb_answers&0xFF);

	/* Update the content length and reallocate memory if needed */
	header->content_len += record_length;
	if (header->content_len > header->allocated_length)
	{
		/* realloc to a new length, */
		do {
			header->allocated_length = mdns_util_suggest_size(header->content_len);
		} while (header->content_len > header->allocated_length);

		*new_record = GETDNS_XREALLOC(context->mf, old_record, uint8_t, header->allocated_length); 
	}
	else
	{
		*new_record = old_record;
	}

	if (*new_record == NULL)
	{
		ret = GETDNS_RETURN_MEMORY_ERROR;
	}
	else
	{
		/* copy the record */
		/* First, point name relative to beginning of DNS message */
		(*new_record)[current_length++] = 0xC0;
		(*new_record)[current_length++] = 12;
		/* encode the components of the per record header */
		(*new_record)[current_length++] = (uint8_t)((record_type >> 8) & 0xFF);
		(*new_record)[current_length++] = (uint8_t)((record_type)& 0xFF);
		(*new_record)[current_length++] = (uint8_t)((record_class >> 8) & 0xFF);
		(*new_record)[current_length++] = (uint8_t)((record_class)& 0xFF);
		(*new_record)[current_length++] = (uint8_t)((ttl >> 24) & 0xFF);
		(*new_record)[current_length++] = (uint8_t)((ttl >> 16) & 0xFF);
		(*new_record)[current_length++] = (uint8_t)((ttl >> 8) & 0xFF);
		(*new_record)[current_length++] = (uint8_t)((ttl)& 0xFF);
		(*new_record)[current_length++] = (uint8_t)((record_data_len >> 8) & 0xFF);
		(*new_record)[current_length++] = (uint8_t)((record_data_len) & 0xFF);
		memcpy(*new_record + current_length, record_data, record_data_len);

	}

	return ret;
}

static int
mdns_update_cache_ttl_and_prune(struct getdns_context *context,
	uint8_t * old_record, uint8_t ** new_record,
	int record_type, int record_class, int ttl,
	uint8_t * record_data, int record_data_len,
	uint64_t current_time)
{
	/*
	 * Compute the TTL delta
	 */
	int ret = 0;
	getdns_mdns_cached_record_header *header = (getdns_mdns_cached_record_header*)old_record;
	uint32_t delta_t_sec = (uint32_t)((current_time - header->insertion_microsec) / 1000000ll);
	header->insertion_microsec += delta_t_sec * 1000000;
	int message_index;
	int answer_index;
	int nb_answers;
	int nb_answers_left;
	int current_record_length;
	int current_record_data_len;
	uint32_t current_record_ttl;
	int not_matched_yet = (record_data == NULL) ? 0 : 1;
	int last_copied_index;
	int current_hole_index = 0;
	int record_name_length = 0;
	int record_ttl_index = 0;
	int i;

	/*
	 * Skip the query
	 */
	message_index = sizeof(getdns_mdns_cached_record_header);
	nb_answers = (old_record[message_index + MDNS_PACKET_INDEX_ANSWER] << 8) |
		old_record[message_index + MDNS_PACKET_INDEX_ANSWER + 1];
	nb_answers_left = nb_answers;
	answer_index = message_index + 12 + mdns_util_skip_query(old_record + message_index + 12);
	last_copied_index = answer_index;

	/*
	 * Examine each record
	 */
	for (i = 0; i < nb_answers; i++)
	{
		record_name_length = mdns_util_skip_name(old_record + answer_index);
		record_ttl_index = answer_index + record_name_length + 2 + 2;

		current_record_ttl = (old_record[record_ttl_index] << 24)
			| (old_record[record_ttl_index + 1] << 16)
			| (old_record[record_ttl_index + 2] << 8)
			| (old_record[record_ttl_index + 3]);

		current_record_data_len = (old_record[record_ttl_index + 4] << 8)
			| (old_record[record_ttl_index + 5]);

		current_record_length = record_name_length + 2 + 2 + 4 + 2 + current_record_data_len;

		if (not_matched_yet &&
		    current_record_data_len == record_data_len &&
			memcmp(old_record + record_ttl_index + 4 + 2, record_data, record_data_len) == 0)
		{
			not_matched_yet = 0;
			current_record_ttl = ttl;
		}
		else
		{
			/* Not a match */
			if (current_record_ttl > delta_t_sec)
			{
				current_record_ttl -= delta_t_sec;
			}
			else
			{
				current_record_ttl = 0;
			}
		}

		if (current_record_ttl == 0)
		{
			nb_answers_left--;

			/* this record should be compacted away */
			if (current_hole_index == 0)
			{
				/* encountering the first hole in the message,
				 * no need to copy anything yet.
				 */
				last_copied_index = answer_index;
			}
			else if (current_hole_index != answer_index)
			{
				/* copy the data from hole to answer */
				memmove(old_record + last_copied_index, old_record + current_hole_index,
					answer_index - current_hole_index);
				last_copied_index += answer_index - current_hole_index;
			}
			
			/* extend the current hole */
			current_hole_index = answer_index + current_record_length;
		}
		else
		{
			/* keeping this record, but updating the TTL */
			old_record[record_ttl_index] = (uint8_t)(current_record_ttl >> 24);
			old_record[record_ttl_index + 1] = (uint8_t)(current_record_ttl >> 16);
			old_record[record_ttl_index + 2] = (uint8_t)(current_record_ttl >> 8);
			old_record[record_ttl_index + 3] = (uint8_t)(current_record_ttl);
		}
		/* progress to the next record */
		answer_index += current_record_length;
	}

	/* if necessary, copy the pending data */
	if (current_hole_index != answer_index && current_hole_index != 0)
	{
		/* copy the data from hole to last answer */
		memmove(old_record + last_copied_index, old_record + current_hole_index,
			answer_index - current_hole_index);
		last_copied_index += answer_index - current_hole_index;

		/* dead assignment */
		/* answer_index = last_copied_index; */
	}

	/* if some records were deleted, update the record headers */
	if (nb_answers != nb_answers_left)
	{
		header->content_len = last_copied_index;
		old_record[message_index + MDNS_PACKET_INDEX_ANSWER] = (uint8_t)(nb_answers_left >> 8);
		old_record[message_index + MDNS_PACKET_INDEX_ANSWER + 1] = (uint8_t)(nb_answers_left);
	}

	/*
	* if the update was never seen, ask for an addition
	*/
	if (ttl > 0 && not_matched_yet)
	{
		mdns_add_record_to_cache_entry(context, old_record, new_record,
			record_type, record_class, ttl, record_data, record_data_len);
		nb_answers_left++;
	}
	else
	{
		*new_record = old_record;
	}

	return ret;
}

/*
 * Get a cached entry by name and record type .
 */
static struct lruhash_entry *
mdns_access_cached_entry_by_name(
struct getdns_context *context,
	uint8_t * name, int name_len,
	int record_type, int record_class)
{
	uint8_t temp_key[256 + sizeof(getdns_mdns_cached_key_header)];
	hashvalue_type hash;
	struct lruhash_entry *entry;

	msdn_cache_create_key_in_buffer(temp_key, name, name_len, record_type, record_class);

	/* TODO: make hash init value a random number in the context, for defense against DOS */
	hash = hashlittle(temp_key, name_len + sizeof(getdns_mdns_cached_key_header), 0xCAC8E);

	entry = lruhash_lookup(context->mdns_cache, hash, temp_key, 1);

	return entry;
}


/*
* Add entry function for the MDNS record cache.
*/
static int
mdns_propose_entry_to_cache(
	struct getdns_context *context,
	uint8_t * name, int name_len,
	int record_type, int record_class, int ttl,
	uint8_t * record_data, int record_data_len,
	getdns_network_req * netreq,
	uint64_t current_time)
{
	int ret = 0;
	uint8_t temp_key[256 + sizeof(getdns_mdns_cached_key_header)];
	hashvalue_type hash;
	struct lruhash_entry *entry, *new_entry;
	uint8_t *key, *data;
	getdns_mdns_cached_record_header * header;

	msdn_cache_create_key_in_buffer(temp_key, name, name_len, record_type, record_class);

	
	/* TODO: make hash init value a random number in the context, for defense against DOS */
	hash = hashlittle(temp_key, name_len + sizeof(getdns_mdns_cached_key_header), 0xCAC8E);

	entry = lruhash_lookup(context->mdns_cache, hash, temp_key, 1);

	if (entry == NULL && ttl != 0)
	{
		/*
		 * Create an empty entry.
		 */
		key = mdns_cache_create_key(name, name_len, record_type, record_class, context);
		data = mdns_cache_create_data(name, name_len, record_type, record_class,
				record_data_len, current_time, context);

		if (key == NULL || data == NULL)
		{
			if (key != NULL)
			{
				GETDNS_FREE(context->mf, key);
				key = NULL;
			}

			if (data != NULL)
			{
				GETDNS_FREE(context->mf, data);
				data = NULL;
			}
		}
		else
		{
			new_entry = &((getdns_mdns_cached_key_header*)key)->entry;

			memset(new_entry, 0, sizeof(struct lruhash_entry));
			lock_rw_init(&new_entry->lock);
			new_entry->hash = hash;
			new_entry->key = key;
			new_entry->data = data;

			entry = lruhash_insert_or_retrieve(context->mdns_cache, hash, new_entry, data, NULL);

			if (entry != new_entry)
			{
				/* There was already an entry for this name, which is really weird. 
				 * But it can in theory happen in a race condition.
				 */
				GETDNS_FREE(context->mf, key);
				key = NULL;
				GETDNS_FREE(context->mf, data);
				data = NULL;
			}
		}
	}

	if (entry != NULL)
	{
		if (record_data != NULL && record_data_len > 0)
			ret = mdns_update_cache_ttl_and_prune(context,
				(uint8_t*)entry->data, &data,
				record_type, record_class, ttl, record_data, record_data_len,
				current_time);

		if (netreq != NULL)
		{
			/* chain the continuous request to the cache line */
			header = (getdns_mdns_cached_record_header *) entry->data;
			netreq->mdns_netreq_next = header->netreq_first;
			header->netreq_first = netreq;
		}
		else
		{
			header = (getdns_mdns_cached_record_header *)entry->data;

			/* if the entry is empty, move it to the bottom of the LRU */
			if (mdns_cache_nb_records_in_entry((uint8_t*)(entry->data)) == 0 &&
				header->netreq_first == NULL)
			{
				lru_demote(context->mdns_cache, entry);
			}
		}

		/* then, unlock the entry */
		lock_rw_unlock(&entry->lock);
	} 

	return ret;
}


/*
 * Serve a request from the cached value
 */
static int
mdns_complete_query_from_cache_entry(
	getdns_network_req *netreq,
	struct lruhash_entry *entry)
{
	int ret = 0;
	uint8_t *packet = ((uint8_t *)entry->data) + sizeof(getdns_mdns_cached_record_header);
	getdns_mdns_cached_record_header * header = (getdns_mdns_cached_record_header*)entry->data;
	size_t packet_length = header->content_len - sizeof(getdns_mdns_cached_record_header);
	getdns_network_req **prev_netreq;
	int found = 0;
	int nb_answers = mdns_cache_nb_records_in_entry((uint8_t *)entry->data);

	/* Clear the event associated to the query */
	GETDNS_CLEAR_EVENT(netreq->owner->loop, &netreq->event);

	/* remove the completed query from the waiting list */
	prev_netreq = &header->netreq_first;
	while (*prev_netreq != NULL)
	{
		if (*prev_netreq == netreq)
		{
			*prev_netreq = netreq->mdns_netreq_next;
			netreq->mdns_netreq_next = NULL;
			found = 1;
			break;
		}
		else
		{
			prev_netreq = &((*prev_netreq)->mdns_netreq_next);
		}
	}

	if (found)
	{
		if (nb_answers == 0)
		{
		}
		else
		{
			/* copy the returned value in the response field  */
			if (packet_length > netreq->wire_data_sz)
			{
				netreq->response = GETDNS_XREALLOC(
					netreq->owner->context->mf, netreq->response, uint8_t, packet_length);
			}

			if (netreq->response != NULL)
			{
				memcpy(netreq->response, packet, packet_length);

				netreq->response[MDNS_PACKET_INDEX_QCODE] = 0x84;

				netreq->response_len = packet_length;
				netreq->debug_end_time = _getdns_get_time_as_uintt64();
				_getdns_netreq_change_state(netreq, NET_REQ_FINISHED);
				_getdns_check_dns_req_complete(netreq->owner);
			}
			else
			{
				/* Fail the query? */
				netreq->response_len = 0;
				netreq->debug_end_time = _getdns_get_time_as_uintt64();
				_getdns_netreq_change_state(netreq, NET_REQ_ERRORED);
				_getdns_check_dns_req_complete(netreq->owner);
			}
		}
	}
	else
	{
		/* Failure */
		netreq->response_len = 0;
		netreq->debug_end_time = _getdns_get_time_as_uintt64();
		_getdns_netreq_change_state(netreq, NET_REQ_ERRORED);
		_getdns_check_dns_req_complete(netreq->owner);
	}

	return ret;
}

/*
 * Processing of requests after cache update.
 * This is coded as synchronous processing, under lock. This is probably wrong.
 * It would be better to just collate the responses for now, and 
 * process the queries out of the loop.
 */
static int
mdns_cache_complete_queries(
	struct getdns_context *context,
	uint8_t * name, int name_len,
	int record_type, int record_class)
{
	int ret = 0;
	struct lruhash_entry *entry;
	getdns_mdns_cached_record_header * header;
	getdns_network_req * netreq;

	entry = mdns_access_cached_entry_by_name(context, name, name_len, record_type, record_class);

	if (entry != NULL)
	{
		if (entry->data != NULL)
		{
			header = (getdns_mdns_cached_record_header *)entry->data;

			while ((netreq = header->netreq_first) != NULL)
			{
				mdns_complete_query_from_cache_entry(netreq, entry);
			}
		}
		lock_rw_unlock(&entry->lock);
	}

	return ret;
}

/*
* Timeout of multicast MDNS query
*/
static void
mdns_mcast_timeout_cb(void *userarg)
{
	getdns_network_req *netreq = (getdns_network_req *)userarg;
	getdns_dns_req *dnsreq = netreq->owner;
	getdns_context *context = dnsreq->context;

	uint8_t temp_key[256 + sizeof(getdns_mdns_cached_key_header)];
	hashvalue_type hash;
	struct lruhash_entry *entry;
	int found = 0;

	DEBUG_MDNS("%s %-35s: MSG:  %p\n",
		MDNS_DEBUG_CLEANUP, __FUNC__, netreq);

	msdn_cache_create_key_in_buffer(temp_key, dnsreq->name, dnsreq->name_len,
		netreq->request_type, dnsreq->request_class);


	/* TODO: make hash init value a random number in the context, for defense against DOS */
	hash = hashlittle(temp_key, dnsreq->name_len + sizeof(getdns_mdns_cached_key_header), 0xCAC8E);

	/* Open the corresponding cache entry */
	entry = lruhash_lookup(context->mdns_cache, hash, temp_key, 1);

	if (entry != NULL)
	{
		if (entry->data != NULL)
		{
			/* Remove entry from chain and serve the query */
			found = 1;
			mdns_complete_query_from_cache_entry(netreq, entry);
		}
		lock_rw_unlock(&entry->lock);
	}

	if (!found)
	{
		/* Fail the request on timeout */
		netreq->response_len = 0;
		netreq->debug_end_time = _getdns_get_time_as_uintt64();
		_getdns_netreq_change_state(netreq, NET_REQ_ERRORED);
		_getdns_check_dns_req_complete(netreq->owner);
	}
}

/*
 * Multicast receive event callback
 */
static void
mdns_udp_multicast_read_cb(void *userarg)
{
	mdns_network_connection * cnx = (mdns_network_connection *)userarg;
	uint64_t current_time;
	ssize_t       read;
	DEBUG_MDNS("%s %-35s: CTX: %p, NET=%d \n", MDNS_DEBUG_MREAD,
		__FUNC__, cnx->context, cnx->addr_mcast.ss_family);

	current_time = _getdns_get_time_as_uintt64();

	GETDNS_CLEAR_EVENT(
		cnx->context->extension, &cnx->event);

	read = recvfrom(cnx->fd, (void *)cnx->response,
		sizeof(cnx->response), 0, NULL, NULL);


	if (read == -1 && (_getdns_socketerror() == _getdns_EWOULDBLOCK ||
		           _getdns_socketerror() == _getdns_ECONNRESET))
		return; /* TODO: this will stop the receive loop! */

	if (read >= GLDNS_HEADER_SIZE)
	{
		/* parse the response, find the relevant queries, submit the records to the cache */
		int opcodeAndflags = cnx->response[2];
		int nb_queries = (cnx->response[4] << 8) | cnx->response[5];
		int nb_responses = (cnx->response[6] << 8) | cnx->response[7];

		if (opcodeAndflags != 0x84)
		{
			/* this is not an MDNS answer packet. */
		}
		else
		{
			ssize_t current_index = 12;
			uint8_t name[256];
			int name_len;
			int record_type;
			int record_class;
			int record_ttl;
			int record_data_len;
			int nb_records = 0;
			int nb_queries_skipped = 0;
			int start_of_records;
			int signalled_records = 0;

			/*
			 * In normal mDNS operation, there should not be any query here. 
			 * But just in case, we can skip the queries...
			 */
			while (current_index < read && nb_queries_skipped < nb_queries)
			{
				current_index += mdns_util_skip_query(&cnx->response[current_index]);
				nb_queries_skipped++;
			}
			start_of_records = current_index;
			/*
			 * Parse the answers and propose them to the cache
			 */

			while (current_index < read && nb_records < nb_responses)
			{
				/* Copy and skip the name */
				current_index = mdns_util_copy_name(cnx->response, read, current_index,
					name, sizeof(name), 0, &name_len);
				if (current_index + 12 >= read)
				{
					/* bogus packet.. Should log. */
					current_index = read;
				}
				else
				{
					/* Parse the record header */
					record_type = (cnx->response[current_index++] << 8);
					record_type |= (cnx->response[current_index++]);
					/* TODO: handle the cache flush bit! */
					record_class = (cnx->response[current_index++] << 8)&0x7F;
					record_class |= (cnx->response[current_index++]);
					record_ttl = (cnx->response[current_index++] << 24);
					record_ttl |= (cnx->response[current_index++] << 16);
					record_ttl |= (cnx->response[current_index++] << 8);
					record_ttl |= (cnx->response[current_index++]);
					record_data_len = (cnx->response[current_index++] << 8);
					record_data_len |= (cnx->response[current_index++]);

					if (current_index + record_data_len <= read)
					{
						/* 
						 * Set the record to canonical form. This is required, since 
						 * MDNS software commonly uses name compression for PTR or SRV records.
						 */
						int actual_length;
						uint8_t *actual_record;
						uint8_t buffer[1024];

						/* TODO: do something in case of canonization failures */
						(void) mdns_util_canonical_record(cnx->response, read,
							record_type, record_class, record_data_len, current_index,
							buffer, sizeof(buffer), &actual_record, &actual_length);


						/* Submit to the cache. As a side effect, may signal that a continuous request is done. */
						(void) mdns_propose_entry_to_cache(cnx->context, name, name_len,
							record_type, record_class, record_ttl,
							actual_record, actual_length, NULL,
							current_time);

						current_index += record_data_len;
						nb_records++;
					}
					else
					{
						/* bogus packet.. Should log. */
						current_index = read;
					}
				}
			}

			/* Go over the queries that were mentioned in the update, and prepare returns. */
			current_index = start_of_records;
			while (current_index < read && signalled_records < nb_responses)
			{
				/* copy the name */
				current_index = mdns_util_copy_name(cnx->response, read, current_index,
					name, sizeof(name), 0, &name_len);
				if (current_index + 12 >= read)
				{
					/* bogus packet.. Should log. */
					current_index = read;
				}
				else
				{
					/* Parse the record header */
					record_type = (cnx->response[current_index++] << 8);
					record_type |= (cnx->response[current_index++]);
					record_class = (cnx->response[current_index++] << 8);
					record_class |= (cnx->response[current_index++]);
					current_index += 4;
					record_data_len = (cnx->response[current_index++] << 8);
					record_data_len |= (cnx->response[current_index++]);
					current_index += record_data_len;

					/* process the pending requests */
					(void)mdns_cache_complete_queries(cnx->context, name, name_len, record_type, record_class);
				}
			}
		}
	}
	else
	{
		/* bogus packet.. Should log. */
	}

	/*
	 * Relaunch the event, so we can go read the next packet.
	 */
	GETDNS_SCHEDULE_EVENT(
		cnx->context->extension, cnx->fd, 0,
		getdns_eventloop_event_init(&cnx->event, cnx,
			mdns_udp_multicast_read_cb, NULL, NULL));
}

/*
 * Create the two required multicast sockets
 */
static int mdns_open_ipv4_multicast(SOCKADDR_STORAGE* mcast_dest, int* mcast_dest_len)
{
	getdns_return_t ret = 0;
	SOCKET fd4 = -1;
	SOCKADDR_IN ipv4_dest;
	SOCKADDR_IN ipv4_port;
	BOOL so_reuse_bool = TRUE;
	int so_reuse_bool_OptLen = sizeof(BOOL);
	uint8_t ttl = 255;
	IP_MREQ mreq4;

	memset(mcast_dest, 0, sizeof(SOCKADDR_STORAGE));
	*mcast_dest_len = 0;
	memset(&ipv4_dest, 0, sizeof(ipv4_dest));
	memset(&ipv4_port, 0, sizeof(ipv4_dest));
	ipv4_dest.sin_family = AF_INET;
	ipv4_dest.sin_port = htons(MDNS_MCAST_PORT);
	ipv4_dest.sin_addr.s_addr = htonl(MDNS_MCAST_IPV4_LONG);
	ipv4_port.sin_family = AF_INET;
	ipv4_port.sin_port = htons(MDNS_MCAST_PORT);
	/* memcpy(&ipv4_dest.sin_addr, mdns_mcast_ipv4, sizeof(mdns_mcast_ipv4)); */



	fd4 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

	if (fd4 != -1)
	{
		/*
		 * No need to test the output of the so_reuse call,
		 * since the only result that matters is that of bind.
		 */
		(void)setsockopt(fd4, SOL_SOCKET, SO_REUSEADDR
			, (const char*)&so_reuse_bool, so_reuse_bool_OptLen);

		if (bind(fd4, (SOCKADDR*)&ipv4_port, sizeof(ipv4_port)) != 0)
		{
			ret = -1;
		}
		else
		{
			mreq4.imr_multiaddr = ipv4_dest.sin_addr;
			mreq4.imr_interface = ipv4_port.sin_addr;

			if (setsockopt(fd4, IPPROTO_IP, IP_ADD_MEMBERSHIP
				, (const char*)&mreq4, (int) sizeof(mreq4)) != 0)
			{
				ret = -1;
			}
			else if (setsockopt(fd4, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) != 0)
			{
				ret = -1;
			}
		}
	}

	if (ret != 0 && fd4 != -1)
	{
			_getdns_closesocket(fd4);
			fd4 = -1;
	}

	if (ret == 0)
	{
		memcpy(mcast_dest, &ipv4_dest, sizeof(ipv4_dest));
		*mcast_dest_len = sizeof(ipv4_dest);
	}

	return fd4;
}

static int mdns_open_ipv6_multicast(SOCKADDR_STORAGE* mcast_dest, int* mcast_dest_len)
{
	getdns_return_t ret = 0;
	SOCKET fd6 = -1;
	SOCKADDR_IN6 ipv6_dest;
	SOCKADDR_IN6 ipv6_port;
	uint8_t so_reuse_bool = 1;
	uint8_t ttl = 255;
	IPV6_MREQ mreq6;

	memset(mcast_dest, 0, sizeof(SOCKADDR_STORAGE));
	*mcast_dest_len = 0;
	memset(&ipv6_dest, 0, sizeof(ipv6_dest));
	memset(&ipv6_port, 0, sizeof(ipv6_dest));
	ipv6_dest.sin6_family = AF_INET6;
	ipv6_dest.sin6_port = htons(MDNS_MCAST_PORT);
	ipv6_port.sin6_family = AF_INET6;
	ipv6_port.sin6_port = htons(MDNS_MCAST_PORT);
	memcpy(&ipv6_dest.sin6_addr
		, mdns_mcast_ipv6, sizeof(mdns_mcast_ipv6));


	fd6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);

	if (fd6 != -1)
	{
		/*
		* No need to test the output of the so_reuse call,
		* since the only result that matters is that of bind.
		*/
		(void)setsockopt(fd6, SOL_SOCKET, SO_REUSEADDR
			, (const char*)&so_reuse_bool, (int) sizeof(BOOL));

		if (bind(fd6, (SOCKADDR*)&ipv6_port, sizeof(ipv6_port)) != 0)
		{
			ret = -1;
		}
		else
		{
			memcpy(&mreq6.ipv6mr_multiaddr
				, &ipv6_dest.sin6_addr, sizeof(mreq6.ipv6mr_multiaddr));
			memcpy(&mreq6.ipv6mr_interface
				, &ipv6_port.sin6_addr, sizeof(mreq6.ipv6mr_interface));

			if (setsockopt(fd6, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP
				, (const char*)&mreq6, (int) sizeof(mreq6)) != 0)
			{
				ret = -1;
			}
			else if (setsockopt(fd6, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(ttl)) != 0)
			{
				ret = -1;
			}
		}
	}

	if (ret != 0 && fd6 != -1)
	{
		_getdns_closesocket(fd6);
		fd6 = -1;
	}

	if (ret == 0)
	{
		memcpy(mcast_dest, &ipv6_dest, sizeof(ipv6_dest));
		*mcast_dest_len = sizeof(ipv6_dest);
	}
	return fd6;
}

/*
 * Delayed opening of the MDNS sockets, and launch of the MDNS listeners
 */
static getdns_return_t mdns_delayed_network_init(struct getdns_context *context)
{
	getdns_return_t ret = 0;

	if (context->mdns_extended_support == 2)
	{
		context->mdns_cache = lruhash_create(128, 10000000,
			mdns_cache_entry_size, mdns_cache_key_comp,
			msdn_cache_delkey, msdn_cache_deldata,
			context);

		if (context->mdns_cache == NULL)
		{
			ret = GETDNS_RETURN_MEMORY_ERROR;
		}
		else
		{
			context->mdns_connection = (mdns_network_connection *)
				GETDNS_XMALLOC(context->my_mf, mdns_network_connection, 2);

			if (context->mdns_connection == NULL)
			{
				ret = GETDNS_RETURN_MEMORY_ERROR;
			}
			else
			{
				context->mdns_connection_nb = 2;

				context->mdns_connection[0].fd = mdns_open_ipv4_multicast(
					&context->mdns_connection[0].addr_mcast
					, &context->mdns_connection[0].addr_mcast_len);
				context->mdns_connection[0].context = context;
				context->mdns_connection[1].fd = mdns_open_ipv6_multicast(
					&context->mdns_connection[1].addr_mcast
					, &context->mdns_connection[1].addr_mcast_len);
				context->mdns_connection[1].context = context;

				if (context->mdns_connection[0].fd == -1 ||
					context->mdns_connection[1].fd == -1)
				{
					ret = GETDNS_RETURN_GENERIC_ERROR;
				}
				else
				{
					int i;
					/* TODO: launch the receive loops */
					for (i = 0; i < 2; i++)
					{
						GETDNS_CLEAR_EVENT(context->extension, &context->mdns_connection[i].event);
						GETDNS_SCHEDULE_EVENT(
							context->extension, context->mdns_connection[i].fd, 0,
							getdns_eventloop_event_init(&context->mdns_connection[i].event,
								&context->mdns_connection[i],
								mdns_udp_multicast_read_cb, NULL, NULL));
					}
				}

				if (ret != 0)
				{
					int i;
					for (i = 0; i < 2; i++)
					{
						if (context->mdns_connection[i].fd != -1)
						{

							GETDNS_CLEAR_EVENT(context->extension
								, &context->mdns_connection[i].event);
							_getdns_closesocket(context->mdns_connection[i].fd);
						}
					}

					GETDNS_FREE(context->my_mf, context->mdns_connection);
					context->mdns_connection = NULL;
					context->mdns_connection_nb = 0;
				}
			} /* mdns-connection != NULL */

			if (ret != 0)
			{
				/* delete the cache that was just created, since the network connection failed */
				lruhash_delete(context->mdns_cache);
				context->mdns_cache = NULL;
			}
		} /* cache != NULL */

		context->mdns_extended_support = (ret == 0) ? 1 : 0;
	}

	return ret;
}

/*
 * Initialize a continuous query from netreq
 */
static getdns_return_t mdns_initialize_continuous_request(getdns_network_req *netreq)
{
	getdns_return_t ret = 0;
	getdns_dns_req *dnsreq = netreq->owner;
	struct getdns_context *context = dnsreq->context;

	uint8_t temp_key[256 + sizeof(getdns_mdns_cached_key_header)];
	hashvalue_type hash;
	struct lruhash_entry *entry;
	size_t pkt_len = netreq->response - netreq->query;

	msdn_cache_create_key_in_buffer(temp_key, dnsreq->name, dnsreq->name_len,
		netreq->request_type, dnsreq->request_class);

	/* TODO: make hash init value a random number in the context, for defense against DOS */
	hash = hashlittle(temp_key, dnsreq->name_len + sizeof(getdns_mdns_cached_key_header), 0xCAC8E);

	entry = lruhash_lookup(context->mdns_cache, hash, temp_key, 1);

	if (entry == NULL)
	{
		/*
		 * First, create an entry for the query
		 */

		ret = mdns_propose_entry_to_cache(context, dnsreq->name, dnsreq->name_len,
			netreq->request_type, dnsreq->request_class, 1, NULL, 0,
			netreq, _getdns_get_time_as_uintt64());
	}
	else
	{
		/*
		 * Check whether the cache entry is recent.
		 * If yes, just return it, but first update the entry tracking in the cache entry.
		 */

		 /*
		  * and unlock the entry!
		  */
	}

	if (ret == 0)
	{
		/* If the query is not actually complete, are a per query timer. */
		if (netreq->state < NET_REQ_FINISHED)
		{
			GETDNS_CLEAR_EVENT(dnsreq->loop, &netreq->event);
			GETDNS_SCHEDULE_EVENT(
				dnsreq->loop, -1, _getdns_ms_until_expiry(dnsreq->expires),
				getdns_eventloop_event_init(&netreq->event, netreq,
					NULL, NULL, mdns_mcast_timeout_cb));
		}
		/* If the entry was created less than 1 sec ago, send a query */

		if (context->mdns_connection_nb <= 0)
		{
			/* oops, no network! */
			ret = GETDNS_RETURN_GENERIC_ERROR;
		}
		else
		{
			/* TODO? Set TTL=255 for compliance with RFC 6762 */
			int fd_index = context->mdns_connection_nb - 1;
			int sent = sendto(
				context->mdns_connection[fd_index].fd
				, (const void *)netreq->query, pkt_len, 0
				, (SOCKADDR*)&context->mdns_connection[fd_index].addr_mcast
				, context->mdns_connection[fd_index].addr_mcast_len);

			if (sent < 0 || pkt_len != (size_t)sent)
			{
				ret = GETDNS_RETURN_GENERIC_ERROR;
			}

			/* TODO: update the send query time */
		}
	}

	return ret;
}

/*
 * Initialize the MDNS part of the context structure.
 */
void _getdns_mdns_context_init(struct getdns_context *context)
{
	context->mdns_extended_support = 2; /* 0 = no support, 1 = supported, 2 = initialization needed */
	context->mdns_connection = NULL;
	context->mdns_connection_nb = 0;
	context->mdns_cache = NULL;
}

/*
 * Delete all the data allocated for MDNS in a context
 */
void _getdns_mdns_context_destroy(struct getdns_context *context)
{
	/* Clear all the cached records. This will terminate all pending network requests */
	if (context->mdns_cache != NULL)
	{
		lruhash_delete(context->mdns_cache);
		context->mdns_cache = NULL;
	}
	/* Close the connections */
	if (context->mdns_connection != NULL)
	{
		int i;
		for (i = 0; i < context->mdns_connection_nb; i++)
		{
			/* suppress the receive event */
			GETDNS_CLEAR_EVENT(context->extension, &context->mdns_connection[i].event);
			/* close the socket */
			_getdns_closesocket(context->mdns_connection[i].fd);
		}

		GETDNS_FREE(context->mf, context->mdns_connection);
		context->mdns_connection = NULL;
		context->mdns_connection_nb = 0;
	}
}

/* TODO: actually delete what is required.. */
static void
mdns_cleanup(getdns_network_req *netreq)
{
	DEBUG_MDNS("%s %-35s: MSG: %p\n",
		MDNS_DEBUG_CLEANUP, __FUNC__, netreq);
	getdns_dns_req *dnsreq = netreq->owner;

	GETDNS_CLEAR_EVENT(dnsreq->loop, &netreq->event);
}

void
_getdns_cancel_mdns_request(getdns_network_req *netreq)
{
	mdns_cleanup(netreq);
	if (netreq->fd >= 0) {
		_getdns_closesocket(netreq->fd);
	}
}

static void
mdns_timeout_cb(void *userarg)
{
	getdns_network_req *netreq = (getdns_network_req *)userarg;
	DEBUG_MDNS("%s %-35s: MSG:  %p\n",
		MDNS_DEBUG_CLEANUP, __FUNC__, netreq);

	/* TODO: do we need a retry logic here? */

	/* Check the required cleanup */
	mdns_cleanup(netreq);
	if (netreq->fd >= 0)
		_getdns_closesocket(netreq->fd);
	_getdns_netreq_change_state(netreq, NET_REQ_TIMED_OUT);
	if (netreq->owner->user_callback) {
		netreq->debug_end_time = _getdns_get_time_as_uintt64();
		(void)_getdns_context_request_timed_out(netreq->owner);
	}
	else
		_getdns_check_dns_req_complete(netreq->owner);
}



/*****************************************/
/* UDP callback functions for basic MDNS */
/*****************************************/

static void
mdns_udp_read_cb(void *userarg)
{
	getdns_network_req *netreq = (getdns_network_req *)userarg;
	getdns_dns_req *dnsreq = netreq->owner;
	ssize_t       read;
	DEBUG_MDNS("%s %-35s: MSG: %p \n", MDNS_DEBUG_READ,
		__FUNC__, netreq);

	GETDNS_CLEAR_EVENT(dnsreq->loop, &netreq->event);

	read = recvfrom(netreq->fd, (void *)netreq->response,
		netreq->max_udp_payload_size + 1, /* If read == max_udp_payload_size
										  * then all is good.  If read ==
										  * max_udp_payload_size + 1, then
										  * we receive more then requested!
										  * i.e. overflow
										  */
		0, NULL, NULL);
	if (read == -1 && (_getdns_socketerror() == _getdns_EWOULDBLOCK ||
		           _getdns_socketerror() == _getdns_ECONNRESET))
		return;

	if (read < GLDNS_HEADER_SIZE)
		return; /* Not DNS */

	if (GLDNS_ID_WIRE(netreq->response) != GLDNS_ID_WIRE(netreq->query))
		return; /* Cache poisoning attempt ;) */

	// TODO: check whether EDNS server cookies are required for MDNS

	// TODO: check that the source address originates from the local network.
	// TODO: check TTL = 255

	_getdns_closesocket(netreq->fd);
	/* 
	 * TODO: how to handle an MDNS response with TC bit set?
	 * Ignore it for now, as we do not support any kind of TCP fallback
	 * for basic MDNS.
	 */
	
	netreq->response_len = read;
	netreq->debug_end_time = _getdns_get_time_as_uintt64();
	_getdns_netreq_change_state(netreq, NET_REQ_FINISHED);
	_getdns_check_dns_req_complete(dnsreq);
}

static void
mdns_udp_write_cb(void *userarg)
{
	getdns_network_req *netreq = (getdns_network_req *)userarg;
	getdns_dns_req     *dnsreq = netreq->owner;
	size_t             pkt_len = netreq->response - netreq->query;
	struct sockaddr_in mdns_mcast_v4;
	int	ttl = 255;
	int r;

	DEBUG_MDNS("%s %-35s: MSG: %p \n", MDNS_DEBUG_WRITE,
		__FUNC__, netreq);

	GETDNS_CLEAR_EVENT(dnsreq->loop, &netreq->event);

	netreq->debug_start_time = _getdns_get_time_as_uintt64();
	netreq->debug_udp = 1;
	GLDNS_ID_SET(netreq->query, (uint16_t) arc4random());

	/* do we need to handle options valid in the MDNS context? */

	/* Probably no need for TSIG in MDNS */


	/* Always use multicast address */
	mdns_mcast_v4.sin_family = AF_INET;
	mdns_mcast_v4.sin_port = htons(MDNS_MCAST_PORT);
	mdns_mcast_v4.sin_addr.s_addr = htonl(MDNS_MCAST_IPV4_LONG);
	/* memcpy(&mdns_mcast_v4.sin_addr.s_addr, mdns_mcast_ipv4, sizeof(mdns_mcast_ipv4)); */

	/* Set TTL=255 for compliance with RFC 6762 */
	r = setsockopt(netreq->fd, IPPROTO_IP, IP_TTL, (const char *)&ttl, sizeof(ttl));

	if (r != 0 || 
		(ssize_t)pkt_len != sendto(
		netreq->fd, (const void *)netreq->query, pkt_len, 0,
		(struct sockaddr *)&mdns_mcast_v4,
		sizeof(mdns_mcast_v4))) {
		_getdns_closesocket(netreq->fd);
		return;
	}
	GETDNS_SCHEDULE_EVENT(
		dnsreq->loop, netreq->fd,
		_getdns_ms_until_expiry(dnsreq->expires),
		getdns_eventloop_event_init(&netreq->event, netreq,
			mdns_udp_read_cb, NULL, mdns_timeout_cb));
}

/*
 * MDNS Request Submission
 */

getdns_return_t
_getdns_submit_mdns_request(getdns_network_req *netreq)
{
	DEBUG_MDNS("%s %-35s: MSG: %p TYPE: %d\n", MDNS_DEBUG_ENTRY, __FUNC__,
		netreq, netreq->request_type);
	int fd = -1;
	getdns_dns_req *dnsreq = netreq->owner;
	struct getdns_context * context = dnsreq->context;
	getdns_return_t ret = 0;

	/*
	 * TO DO: depending on context type, perform basic processing versus full MDNS
	 */

	if (context->mdns_extended_support == 2)
	{
		/* Not initialize yet. Do it know before processing the query */
		ret = mdns_delayed_network_init(context);

		if (ret != 0)
		{
			return ret;
		}
	}

	if (context->mdns_extended_support == 1)
	{
		/* extended DNS support */
		ret = mdns_initialize_continuous_request(netreq);
	}
	else
	{
		/* basic MDNS request */

		/* Open the UDP socket required for the request */
		if ((fd = socket(
			AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
			return -1;
		/* TODO: do we need getdns_sock_nonblock(fd); */

		/* Schedule the MDNS request */
		netreq->fd = fd;
		GETDNS_CLEAR_EVENT(dnsreq->loop, &netreq->event);
		GETDNS_SCHEDULE_EVENT(
			dnsreq->loop, netreq->fd,
			_getdns_ms_until_expiry(dnsreq->expires),
			getdns_eventloop_event_init(&netreq->event, netreq,
				NULL, mdns_udp_write_cb, mdns_timeout_cb));
		ret = GETDNS_RETURN_GOOD;
	}

	return ret;
}

/*
 * MDNS name space management
 */

static int
mdns_suffix_compare(register const uint8_t *d1, register const uint8_t *d2)
{
	int ret = 0;
	uint8_t *d1_head = (uint8_t *) d1;
	uint8_t *d1_current;
	uint8_t *d2_current;
	int is_matching = 0;
	int part_length;
	int i;
	uint8_t c;

	/* Skip the first name part, since we want at least one label before the suffix */
	if (*d1_head != 0)
		d1_head += *d1_head + 1;

	while (*d1_head != 0)
	{
		/* check whether we have a match at this point */
		d1_current = d1_head;
		d2_current = (uint8_t *) d2;
		is_matching = 0;

		/* compare length and value of all successive labels */
		while (*d1_current == *d2_current)
		{
			part_length = *d1_current;
			if (part_length == 0)
			{
				/* We have reached the top label, there is a match */
				ret = 1;
				break;
			}

			/* The label's lengths are matching, check the content */
			is_matching = 1;
			d1_current++;
			d2_current++;

			for (i = 0; i < part_length; i++)
			{
				c = d1_current[i];
				if (isupper(c))
					c = tolower(c);
				if (c != d2_current[i])
				{
					is_matching = 0;
					break;
				}
			}
			
			/* move the pointers to the next label */
			if (is_matching)
			{
				d1_current += part_length;
				d2_current += part_length;
			}
		}

		/* if no match found yet, move to the next label of d1 */
		if (is_matching)
			break;
		else
			d1_head += *d1_head + 1;
	}

	return ret;
}


getdns_return_t
_getdns_mdns_namespace_check(
	getdns_dns_req *dnsreq)
{
	getdns_return_t ret = GETDNS_RETURN_GENERIC_ERROR;

	/* Checking the prefixes defined in RFC 6762  */
	if (mdns_suffix_compare(dnsreq->name, mdns_suffix_dot_local) ||
		mdns_suffix_compare(dnsreq->name, mdns_suffix_254_169_in_addr_arpa) ||
		mdns_suffix_compare(dnsreq->name, mdns_suffix_8_e_f_ip6_arpa) ||
		mdns_suffix_compare(dnsreq->name, mdns_suffix_9_e_f_ip6_arpa) ||
		mdns_suffix_compare(dnsreq->name, mdns_suffix_a_e_f_ip6_arpa) ||
		mdns_suffix_compare(dnsreq->name, mdns_suffix_b_e_f_ip6_arpa))
		ret = GETDNS_RETURN_GOOD;

	return ret;
}

#endif /* HAVE_MDNS_SUPPORT */

#ifdef MDNS_UNIT_TEST

/*
 * Test adding data to the LRU Cache
 */

static BYTE mdns_exampleRRAM[] = {
	0, 0, /* Transaction ID = 0 */
	0x84, 0, /* Answer: QR=1 (80), AA=1 (04) */
	0, 0, /* QD Count = 0 */
	0, 1, /* AN Count = 1 */
	0, 0, /* NS Count = 0 */
	0, 0, /* AD Count = 0 */
	7, /* length of "example" name part */
	'e', 'x', 'a', 'm', 'p', 'l', 'e',
	5, /* length of "local" name part */
	'l', 'o', 'c', 'a', 'l',
	0, /* length of the root name part */
	0, 1, /* QTYPE = 1, A record */
	0, 1, /* QCLASS = 1, IN */
	0, 0, 0, 255, /* TTL: 255 sec */
	0, 4, /* length of RDATA */
	10, 0, 0, 1 /* Value of RDATA (some IPv4 address) */
};


uint8_t mdns_test_name[] = {
	7, /* length of "example" name part */
	't', 'e', 's', 't', 'i', 'n', 'g',
	5, /* length of "local" name part */
	'l', 'o', 'c', 'a', 'l',
	0, /* length of the root name part */
};

uint8_t mdns_test_first_address[4] = { 10, 0, 0, 1 };
uint8_t mdns_test_second_address[4] = { 10, 0, 0, 2 };
uint8_t mdns_test_third_address[4] = { 10, 0, 0, 3 };

int mdns_finalize_lru_test(struct getdns_context* context,
	uint8_t * name, int name_len, int record_type, int record_class,
	int expected_nb_records,
	uint8_t * buffer, size_t buffer_max, size_t* entry_length)
{
	int ret = 0;
	/* verify that the entry is there */
	struct lruhash_entry * entry =
		mdns_access_cached_entry_by_name(context, name, name_len, record_type, record_class);

	
	*entry_length = 0;

	if (entry == NULL)
	{
		if (expected_nb_records != 0)
			ret = -1;
	}
	else
	{
		int nbanswers = mdns_cache_nb_records_in_entry((uint8_t*)entry->data);
		if (nbanswers != expected_nb_records)
		{
			ret = -2;
		}
		
		if (buffer != NULL)
		{
			getdns_mdns_cached_record_header * header =
				(getdns_mdns_cached_record_header*)entry->data;
			size_t record_length = header->content_len - sizeof(getdns_mdns_cached_record_header);

			if (record_length > buffer_max)
			{
				ret = -3;
			}
			else
			{
				memcpy(buffer, ((uint8_t *)entry->data) + sizeof(getdns_mdns_cached_record_header),
					record_length);
				*entry_length = record_length;
			}
		}

		lock_rw_unlock(&entry->lock);
	}

	return ret;
}

int mdns_addition_test(struct getdns_context* context, 
	uint8_t * buffer, size_t buffer_max, size_t* entry_length)
{
	int ret = 
	mdns_propose_entry_to_cache(context, mdns_test_name, sizeof(mdns_test_name), 1, 1, 255,
		mdns_test_first_address, 4, NULL, _getdns_get_time_as_uintt64());

	if (ret == 0)
	{
		ret = mdns_finalize_lru_test(context, mdns_test_name, sizeof(mdns_test_name), 1, 1,
			1, buffer, buffer_max, entry_length);
	}

	return ret;
}

int mdns_addition_test2(struct getdns_context* context,
	uint8_t * buffer, size_t buffer_max, size_t* entry_length)
{
	int ret =
		mdns_propose_entry_to_cache(context, mdns_test_name, sizeof(mdns_test_name), 1, 1, 255,
			mdns_test_first_address, 4, NULL, _getdns_get_time_as_uintt64());

	if (ret == 0)
	{
		/* add a second entry, with a different value */
		ret =
			mdns_propose_entry_to_cache(context, mdns_test_name, sizeof(mdns_test_name), 1, 1, 255,
				mdns_test_second_address, 4, NULL, _getdns_get_time_as_uintt64());
	}

	if (ret == 0)
	{
		/* add a third entry, with a different value */
		ret =
			mdns_propose_entry_to_cache(context, mdns_test_name, sizeof(mdns_test_name), 1, 1, 255,
				mdns_test_third_address, 4, NULL, _getdns_get_time_as_uintt64());
	}

	if (ret == 0)
	{
		ret = mdns_finalize_lru_test(context, mdns_test_name, sizeof(mdns_test_name), 1, 1,
			3, buffer, buffer_max, entry_length);
	}

	return ret;
}

int mdns_deletion_test(struct getdns_context* context,
	uint8_t * buffer, size_t buffer_max, size_t* entry_length)
{
	/* insert data with TTL = 0 to trigger suppression */
	int ret =
		mdns_propose_entry_to_cache(context, mdns_test_name, sizeof(mdns_test_name), 1, 1, 0,
			mdns_test_second_address, 4, NULL, _getdns_get_time_as_uintt64());

	if (ret == 0)
	{
		ret = mdns_finalize_lru_test(context, mdns_test_name, sizeof(mdns_test_name), 1, 1,
			2, buffer, buffer_max, entry_length);
	}

	return ret;
}

int mdns_deletion_test2(struct getdns_context* context,
	uint8_t * buffer, size_t buffer_max, size_t* entry_length)
{
	/* insert data with TTL = 0 to trigger suppression */
	int ret =
		mdns_propose_entry_to_cache(context, mdns_test_name, sizeof(mdns_test_name), 1, 1, 0,
			mdns_test_first_address, 4, NULL, _getdns_get_time_as_uintt64());

	if (ret == 0)
	{
		ret =
			mdns_propose_entry_to_cache(context, mdns_test_name, sizeof(mdns_test_name), 1, 1, 0,
				mdns_test_third_address, 4, NULL, _getdns_get_time_as_uintt64());
	}

	if (ret == 0)
	{
		ret = mdns_finalize_lru_test(context, mdns_test_name, sizeof(mdns_test_name), 1, 1,
			0, buffer, buffer_max, entry_length);
	}

	return ret;
}


int mdns_test_prepare(struct getdns_context* context)
{
	return mdns_delayed_network_init(context);
}

#endif