summaryrefslogtreecommitdiff
path: root/usr.sbin/unbound/services/mesh.c
blob: e886c4b92c846ce4f686b99c5a3a8d1319e9993e (plain)
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
/*
 * services/mesh.c - deal with mesh of query states and handle events for that.
 *
 * Copyright (c) 2007, NLnet Labs. All rights reserved.
 *
 * This software is open source.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 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.
 *
 * Neither the name of the NLNET LABS 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * \file
 *
 * This file contains functions to assist in dealing with a mesh of
 * query states. This mesh is supposed to be thread-specific.
 * It consists of query states (per qname, qtype, qclass) and connections
 * between query states and the super and subquery states, and replies to
 * send back to clients.
 */
#include "config.h"
#include "services/mesh.h"
#include "services/outbound_list.h"
#include "services/cache/dns.h"
#include "services/cache/rrset.h"
#include "services/cache/infra.h"
#include "util/log.h"
#include "util/net_help.h"
#include "util/module.h"
#include "util/regional.h"
#include "util/data/msgencode.h"
#include "util/timehist.h"
#include "util/fptr_wlist.h"
#include "util/alloc.h"
#include "util/config_file.h"
#include "util/edns.h"
#include "sldns/sbuffer.h"
#include "sldns/wire2str.h"
#include "services/localzone.h"
#include "util/data/dname.h"
#include "respip/respip.h"
#include "services/listen_dnsport.h"
#include "util/timeval_func.h"

#ifdef CLIENT_SUBNET
#include "edns-subnet/subnetmod.h"
#include "edns-subnet/edns-subnet.h"
#endif
#ifdef HAVE_SYS_TYPES_H
#  include <sys/types.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif

/**
 * Compare two response-ip client info entries for the purpose of mesh state
 * compare.  It returns 0 if ci_a and ci_b are considered equal; otherwise
 * 1 or -1 (they mean 'ci_a is larger/smaller than ci_b', respectively, but
 * in practice it should be only used to mean they are different).
 * We cannot share the mesh state for two queries if different response-ip
 * actions can apply in the end, even if those queries are otherwise identical.
 * For this purpose we compare tag lists and tag action lists; they should be
 * identical to share the same state.
 * For tag data, we don't look into the data content, as it can be
 * expensive; unless tag data are not defined for both or they point to the
 * exact same data in memory (i.e., they come from the same ACL entry), we
 * consider these data different.
 * Likewise, if the client info is associated with views, we don't look into
 * the views.  They are considered different unless they are exactly the same
 * even if the views only differ in the names.
 */
static int
client_info_compare(const struct respip_client_info* ci_a,
	const struct respip_client_info* ci_b)
{
	int cmp;

	if(!ci_a && !ci_b)
		return 0;
	if(ci_a && !ci_b)
		return -1;
	if(!ci_a && ci_b)
		return 1;
	if(ci_a->taglen != ci_b->taglen)
		return (ci_a->taglen < ci_b->taglen) ? -1 : 1;
	if(ci_a->taglist && !ci_b->taglist)
		return -1;
	if(!ci_a->taglist && ci_b->taglist)
		return 1;
	if(ci_a->taglist && ci_b->taglist) {
		cmp = memcmp(ci_a->taglist, ci_b->taglist, ci_a->taglen);
		if(cmp != 0)
			return cmp;
	}
	if(ci_a->tag_actions_size != ci_b->tag_actions_size)
		return (ci_a->tag_actions_size < ci_b->tag_actions_size) ?
			-1 : 1;
	if(ci_a->tag_actions && !ci_b->tag_actions)
		return -1;
	if(!ci_a->tag_actions && ci_b->tag_actions)
		return 1;
	if(ci_a->tag_actions && ci_b->tag_actions) {
		cmp = memcmp(ci_a->tag_actions, ci_b->tag_actions,
			ci_a->tag_actions_size);
		if(cmp != 0)
			return cmp;
	}
	if(ci_a->tag_datas != ci_b->tag_datas)
		return ci_a->tag_datas < ci_b->tag_datas ? -1 : 1;
	if(ci_a->view != ci_b->view)
		return ci_a->view < ci_b->view ? -1 : 1;
	/* For the unbound daemon these should be non-NULL and identical,
	 * but we check that just in case. */
	if(ci_a->respip_set != ci_b->respip_set)
		return ci_a->respip_set < ci_b->respip_set ? -1 : 1;
	return 0;
}

int
mesh_state_compare(const void* ap, const void* bp)
{
	struct mesh_state* a = (struct mesh_state*)ap;
	struct mesh_state* b = (struct mesh_state*)bp;
	int cmp;

	if(a->unique < b->unique)
		return -1;
	if(a->unique > b->unique)
		return 1;

	if(a->s.is_priming && !b->s.is_priming)
		return -1;
	if(!a->s.is_priming && b->s.is_priming)
		return 1;

	if(a->s.is_valrec && !b->s.is_valrec)
		return -1;
	if(!a->s.is_valrec && b->s.is_valrec)
		return 1;

	if((a->s.query_flags&BIT_RD) && !(b->s.query_flags&BIT_RD))
		return -1;
	if(!(a->s.query_flags&BIT_RD) && (b->s.query_flags&BIT_RD))
		return 1;

	if((a->s.query_flags&BIT_CD) && !(b->s.query_flags&BIT_CD))
		return -1;
	if(!(a->s.query_flags&BIT_CD) && (b->s.query_flags&BIT_CD))
		return 1;

	cmp = query_info_compare(&a->s.qinfo, &b->s.qinfo);
	if(cmp != 0)
		return cmp;
	return client_info_compare(a->s.client_info, b->s.client_info);
}

int
mesh_state_ref_compare(const void* ap, const void* bp)
{
	struct mesh_state_ref* a = (struct mesh_state_ref*)ap;
	struct mesh_state_ref* b = (struct mesh_state_ref*)bp;
	return mesh_state_compare(a->s, b->s);
}

struct mesh_area*
mesh_create(struct module_stack* stack, struct module_env* env)
{
	struct mesh_area* mesh = calloc(1, sizeof(struct mesh_area));
	if(!mesh) {
		log_err("mesh area alloc: out of memory");
		return NULL;
	}
	mesh->histogram = timehist_setup();
	mesh->qbuf_bak = sldns_buffer_new(env->cfg->msg_buffer_size);
	if(!mesh->histogram || !mesh->qbuf_bak) {
		free(mesh);
		log_err("mesh area alloc: out of memory");
		return NULL;
	}
	mesh->mods = *stack;
	mesh->env = env;
	rbtree_init(&mesh->run, &mesh_state_compare);
	rbtree_init(&mesh->all, &mesh_state_compare);
	mesh->num_reply_addrs = 0;
	mesh->num_reply_states = 0;
	mesh->num_detached_states = 0;
	mesh->num_forever_states = 0;
	mesh->stats_jostled = 0;
	mesh->stats_dropped = 0;
	mesh->ans_expired = 0;
	mesh->ans_cachedb = 0;
	mesh->max_reply_states = env->cfg->num_queries_per_thread;
	mesh->max_forever_states = (mesh->max_reply_states+1)/2;
#ifndef S_SPLINT_S
	mesh->jostle_max.tv_sec = (time_t)(env->cfg->jostle_time / 1000);
	mesh->jostle_max.tv_usec = (time_t)((env->cfg->jostle_time % 1000)
		*1000);
#endif
	return mesh;
}

/** help mesh delete delete mesh states */
static void
mesh_delete_helper(rbnode_type* n)
{
	struct mesh_state* mstate = (struct mesh_state*)n->key;
	/* perform a full delete, not only 'cleanup' routine,
	 * because other callbacks expect a clean state in the mesh.
	 * For 're-entrant' calls */
	mesh_state_delete(&mstate->s);
	/* but because these delete the items from the tree, postorder
	 * traversal and rbtree rebalancing do not work together */
}

void
mesh_delete(struct mesh_area* mesh)
{
	if(!mesh)
		return;
	/* free all query states */
	while(mesh->all.count)
		mesh_delete_helper(mesh->all.root);
	timehist_delete(mesh->histogram);
	sldns_buffer_free(mesh->qbuf_bak);
	free(mesh);
}

void
mesh_delete_all(struct mesh_area* mesh)
{
	/* free all query states */
	while(mesh->all.count)
		mesh_delete_helper(mesh->all.root);
	mesh->stats_dropped += mesh->num_reply_addrs;
	/* clear mesh area references */
	rbtree_init(&mesh->run, &mesh_state_compare);
	rbtree_init(&mesh->all, &mesh_state_compare);
	mesh->num_reply_addrs = 0;
	mesh->num_reply_states = 0;
	mesh->num_detached_states = 0;
	mesh->num_forever_states = 0;
	mesh->forever_first = NULL;
	mesh->forever_last = NULL;
	mesh->jostle_first = NULL;
	mesh->jostle_last = NULL;
}

int mesh_make_new_space(struct mesh_area* mesh, sldns_buffer* qbuf)
{
	struct mesh_state* m = mesh->jostle_first;
	/* free space is available */
	if(mesh->num_reply_states < mesh->max_reply_states)
		return 1;
	/* try to kick out a jostle-list item */
	if(m && m->reply_list && m->list_select == mesh_jostle_list) {
		/* how old is it? */
		struct timeval age;
		timeval_subtract(&age, mesh->env->now_tv,
			&m->reply_list->start_time);
		if(timeval_smaller(&mesh->jostle_max, &age)) {
			/* its a goner */
			log_nametypeclass(VERB_ALGO, "query jostled out to "
				"make space for a new one",
				m->s.qinfo.qname, m->s.qinfo.qtype,
				m->s.qinfo.qclass);
			/* backup the query */
			if(qbuf) sldns_buffer_copy(mesh->qbuf_bak, qbuf);
			/* notify supers */
			if(m->super_set.count > 0) {
				verbose(VERB_ALGO, "notify supers of failure");
				m->s.return_msg = NULL;
				m->s.return_rcode = LDNS_RCODE_SERVFAIL;
				mesh_walk_supers(mesh, m);
			}
			mesh->stats_jostled ++;
			mesh_state_delete(&m->s);
			/* restore the query - note that the qinfo ptr to
			 * the querybuffer is then correct again. */
			if(qbuf) sldns_buffer_copy(qbuf, mesh->qbuf_bak);
			return 1;
		}
	}
	/* no space for new item */
	return 0;
}

struct dns_msg*
mesh_serve_expired_lookup(struct module_qstate* qstate,
	struct query_info* lookup_qinfo)
{
	hashvalue_type h;
	struct lruhash_entry* e;
	struct dns_msg* msg;
	struct reply_info* data;
	struct msgreply_entry* key;
	time_t timenow = *qstate->env->now;
	int must_validate = (!(qstate->query_flags&BIT_CD)
		|| qstate->env->cfg->ignore_cd) && qstate->env->need_to_validate;
	/* Lookup cache */
	h = query_info_hash(lookup_qinfo, qstate->query_flags);
	e = slabhash_lookup(qstate->env->msg_cache, h, lookup_qinfo, 0);
	if(!e) return NULL;

	key = (struct msgreply_entry*)e->key;
	data = (struct reply_info*)e->data;
	msg = tomsg(qstate->env, &key->key, data, qstate->region, timenow,
		qstate->env->cfg->serve_expired, qstate->env->scratch);
	if(!msg)
		goto bail_out;

	/* Check CNAME chain (if any)
	 * This is part of tomsg above; no need to check now. */

	/* Check security status of the cached answer.
	 * tomsg above has a subset of these checks, so we are leaving
	 * these as is.
	 * In case of bogus or revalidation we don't care to reply here. */
	if(must_validate && (msg->rep->security == sec_status_bogus ||
		msg->rep->security == sec_status_secure_sentinel_fail)) {
		verbose(VERB_ALGO, "Serve expired: bogus answer found in cache");
		goto bail_out;
	} else if(msg->rep->security == sec_status_unchecked && must_validate) {
		verbose(VERB_ALGO, "Serve expired: unchecked entry needs "
			"validation");
		goto bail_out; /* need to validate cache entry first */
	} else if(msg->rep->security == sec_status_secure &&
		!reply_all_rrsets_secure(msg->rep) && must_validate) {
			verbose(VERB_ALGO, "Serve expired: secure entry"
				" changed status");
			goto bail_out; /* rrset changed, re-verify */
	}

	lock_rw_unlock(&e->lock);
	return msg;

bail_out:
	lock_rw_unlock(&e->lock);
	return NULL;
}


/** Init the serve expired data structure */
static int
mesh_serve_expired_init(struct mesh_state* mstate, int timeout)
{
	struct timeval t;

	/* Create serve_expired_data if not there yet */
	if(!mstate->s.serve_expired_data) {
		mstate->s.serve_expired_data = (struct serve_expired_data*)
			regional_alloc_zero(
				mstate->s.region, sizeof(struct serve_expired_data));
		if(!mstate->s.serve_expired_data)
			return 0;
	}

	/* Don't overwrite the function if already set */
	mstate->s.serve_expired_data->get_cached_answer =
		mstate->s.serve_expired_data->get_cached_answer?
		mstate->s.serve_expired_data->get_cached_answer:
		&mesh_serve_expired_lookup;

	/* In case this timer already popped, start it again */
	if(!mstate->s.serve_expired_data->timer && timeout != -1) {
		mstate->s.serve_expired_data->timer = comm_timer_create(
			mstate->s.env->worker_base, mesh_serve_expired_callback, mstate);
		if(!mstate->s.serve_expired_data->timer)
			return 0;
#ifndef S_SPLINT_S
		t.tv_sec = timeout/1000;
		t.tv_usec = (timeout%1000)*1000;
#endif
		comm_timer_set(mstate->s.serve_expired_data->timer, &t);
	}
	return 1;
}

void mesh_new_client(struct mesh_area* mesh, struct query_info* qinfo,
	struct respip_client_info* cinfo, uint16_t qflags,
	struct edns_data* edns, struct comm_reply* rep, uint16_t qid,
	int rpz_passthru)
{
	struct mesh_state* s = NULL;
	int unique = unique_mesh_state(edns->opt_list_in, mesh->env);
	int was_detached = 0;
	int was_noreply = 0;
	int added = 0;
	int timeout = mesh->env->cfg->serve_expired?
		mesh->env->cfg->serve_expired_client_timeout:0;
	struct sldns_buffer* r_buffer = rep->c->buffer;
	if(rep->c->tcp_req_info) {
		r_buffer = rep->c->tcp_req_info->spool_buffer;
	}
	if(!infra_wait_limit_allowed(mesh->env->infra_cache, rep,
		edns->cookie_valid, mesh->env->cfg)) {
		verbose(VERB_ALGO, "Too many queries waiting from the IP. "
			"dropping incoming query.");
		comm_point_drop_reply(rep);
		mesh->stats_dropped++;
		return;
	}
	if(!unique)
		s = mesh_area_find(mesh, cinfo, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
	/* does this create a new reply state? */
	if(!s || s->list_select == mesh_no_list) {
		if(!mesh_make_new_space(mesh, rep->c->buffer)) {
			verbose(VERB_ALGO, "Too many queries. dropping "
				"incoming query.");
			comm_point_drop_reply(rep);
			mesh->stats_dropped++;
			return;
		}
		/* for this new reply state, the reply address is free,
		 * so the limit of reply addresses does not stop reply states*/
	} else {
		/* protect our memory usage from storing reply addresses */
		if(mesh->num_reply_addrs > mesh->max_reply_states*16) {
			verbose(VERB_ALGO, "Too many requests queued. "
				"dropping incoming query.");
			comm_point_drop_reply(rep);
			mesh->stats_dropped++;
			return;
		}
	}
	/* see if it already exists, if not, create one */
	if(!s) {
#ifdef UNBOUND_DEBUG
		struct rbnode_type* n;
#endif
		s = mesh_state_create(mesh->env, qinfo, cinfo,
			qflags&(BIT_RD|BIT_CD), 0, 0);
		if(!s) {
			log_err("mesh_state_create: out of memory; SERVFAIL");
			if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL, NULL,
				LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch, mesh->env->now_tv))
					edns->opt_list_inplace_cb_out = NULL;
			error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
				qinfo, qid, qflags, edns);
			comm_point_send_reply(rep);
			return;
		}
		/* set detached (it is now) */
		mesh->num_detached_states++;
		if(unique)
			mesh_state_make_unique(s);
		s->s.rpz_passthru = rpz_passthru;
		/* copy the edns options we got from the front */
		if(edns->opt_list_in) {
			s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list_in,
				s->s.region);
			if(!s->s.edns_opts_front_in) {
				log_err("edns_opt_copy_region: out of memory; SERVFAIL");
				if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL,
					NULL, LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch, mesh->env->now_tv))
						edns->opt_list_inplace_cb_out = NULL;
				error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
					qinfo, qid, qflags, edns);
				comm_point_send_reply(rep);
				mesh_state_delete(&s->s);
				return;
			}
		}

#ifdef UNBOUND_DEBUG
		n =
#else
		(void)
#endif
		rbtree_insert(&mesh->all, &s->node);
		log_assert(n != NULL);
		added = 1;
	}
	if(!s->reply_list && !s->cb_list) {
		was_noreply = 1;
		if(s->super_set.count == 0) {
			was_detached = 1;
		}
	}
	/* add reply to s */
	if(!mesh_state_add_reply(s, edns, rep, qid, qflags, qinfo)) {
		log_err("mesh_new_client: out of memory; SERVFAIL");
		goto servfail_mem;
	}
	if(rep->c->tcp_req_info) {
		if(!tcp_req_info_add_meshstate(rep->c->tcp_req_info, mesh, s)) {
			log_err("mesh_new_client: out of memory add tcpreqinfo");
			goto servfail_mem;
		}
	}
	if(rep->c->use_h2) {
		http2_stream_add_meshstate(rep->c->h2_stream, mesh, s);
	}
	/* add serve expired timer if required and not already there */
	if(timeout && !mesh_serve_expired_init(s, timeout)) {
		log_err("mesh_new_client: out of memory initializing serve expired");
		goto servfail_mem;
	}
#ifdef USE_CACHEDB
	if(!timeout && mesh->env->cfg->serve_expired &&
		!mesh->env->cfg->serve_expired_client_timeout &&
		(mesh->env->cachedb_enabled &&
		 mesh->env->cfg->cachedb_check_when_serve_expired)) {
		if(!mesh_serve_expired_init(s, -1)) {
			log_err("mesh_new_client: out of memory initializing serve expired");
			goto servfail_mem;
		}
	}
#endif
	infra_wait_limit_inc(mesh->env->infra_cache, rep, *mesh->env->now,
		mesh->env->cfg);
	/* update statistics */
	if(was_detached) {
		log_assert(mesh->num_detached_states > 0);
		mesh->num_detached_states--;
	}
	if(was_noreply) {
		mesh->num_reply_states ++;
	}
	mesh->num_reply_addrs++;
	if(s->list_select == mesh_no_list) {
		/* move to either the forever or the jostle_list */
		if(mesh->num_forever_states < mesh->max_forever_states) {
			mesh->num_forever_states ++;
			mesh_list_insert(s, &mesh->forever_first,
				&mesh->forever_last);
			s->list_select = mesh_forever_list;
		} else {
			mesh_list_insert(s, &mesh->jostle_first,
				&mesh->jostle_last);
			s->list_select = mesh_jostle_list;
		}
	}
	if(added)
		mesh_run(mesh, s, module_event_new, NULL);
	return;

servfail_mem:
	if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, &s->s,
		NULL, LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch, mesh->env->now_tv))
			edns->opt_list_inplace_cb_out = NULL;
	error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
		qinfo, qid, qflags, edns);
	comm_point_send_reply(rep);
	if(added)
		mesh_state_delete(&s->s);
	return;
}

int
mesh_new_callback(struct mesh_area* mesh, struct query_info* qinfo,
	uint16_t qflags, struct edns_data* edns, sldns_buffer* buf,
	uint16_t qid, mesh_cb_func_type cb, void* cb_arg, int rpz_passthru)
{
	struct mesh_state* s = NULL;
	int unique = unique_mesh_state(edns->opt_list_in, mesh->env);
	int timeout = mesh->env->cfg->serve_expired?
		mesh->env->cfg->serve_expired_client_timeout:0;
	int was_detached = 0;
	int was_noreply = 0;
	int added = 0;
	if(!unique)
		s = mesh_area_find(mesh, NULL, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);

	/* there are no limits on the number of callbacks */

	/* see if it already exists, if not, create one */
	if(!s) {
#ifdef UNBOUND_DEBUG
		struct rbnode_type* n;
#endif
		s = mesh_state_create(mesh->env, qinfo, NULL,
			qflags&(BIT_RD|BIT_CD), 0, 0);
		if(!s) {
			return 0;
		}
		/* set detached (it is now) */
		mesh->num_detached_states++;
		if(unique)
			mesh_state_make_unique(s);
		s->s.rpz_passthru = rpz_passthru;
		if(edns->opt_list_in) {
			s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list_in,
				s->s.region);
			if(!s->s.edns_opts_front_in) {
				mesh_state_delete(&s->s);
				return 0;
			}
		}
#ifdef UNBOUND_DEBUG
		n =
#else
		(void)
#endif
		rbtree_insert(&mesh->all, &s->node);
		log_assert(n != NULL);
		added = 1;
	}
	if(!s->reply_list && !s->cb_list) {
		was_noreply = 1;
		if(s->super_set.count == 0) {
			was_detached = 1;
		}
	}
	/* add reply to s */
	if(!mesh_state_add_cb(s, edns, buf, cb, cb_arg, qid, qflags)) {
		if(added)
			mesh_state_delete(&s->s);
		return 0;
	}
	/* add serve expired timer if not already there */
	if(timeout && !mesh_serve_expired_init(s, timeout)) {
		if(added)
			mesh_state_delete(&s->s);
		return 0;
	}
#ifdef USE_CACHEDB
	if(!timeout && mesh->env->cfg->serve_expired &&
		!mesh->env->cfg->serve_expired_client_timeout &&
		(mesh->env->cachedb_enabled &&
		 mesh->env->cfg->cachedb_check_when_serve_expired)) {
		if(!mesh_serve_expired_init(s, -1)) {
			if(added)
				mesh_state_delete(&s->s);
			return 0;
		}
	}
#endif
	/* update statistics */
	if(was_detached) {
		log_assert(mesh->num_detached_states > 0);
		mesh->num_detached_states--;
	}
	if(was_noreply) {
		mesh->num_reply_states ++;
	}
	mesh->num_reply_addrs++;
	if(added)
		mesh_run(mesh, s, module_event_new, NULL);
	return 1;
}

/* Internal backend routine of mesh_new_prefetch().  It takes one additional
 * parameter, 'run', which controls whether to run the prefetch state
 * immediately.  When this function is called internally 'run' could be
 * 0 (false), in which case the new state is only made runnable so it
 * will not be run recursively on top of the current state. */
static void mesh_schedule_prefetch(struct mesh_area* mesh,
	struct query_info* qinfo, uint16_t qflags, time_t leeway, int run,
	int rpz_passthru)
{
	struct mesh_state* s = mesh_area_find(mesh, NULL, qinfo,
		qflags&(BIT_RD|BIT_CD), 0, 0);
#ifdef UNBOUND_DEBUG
	struct rbnode_type* n;
#endif
	/* already exists, and for a different purpose perhaps.
	 * if mesh_no_list, keep it that way. */
	if(s) {
		/* make it ignore the cache from now on */
		if(!s->s.blacklist)
			sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
		if(s->s.prefetch_leeway < leeway)
			s->s.prefetch_leeway = leeway;
		return;
	}
	if(!mesh_make_new_space(mesh, NULL)) {
		verbose(VERB_ALGO, "Too many queries. dropped prefetch.");
		mesh->stats_dropped ++;
		return;
	}

	s = mesh_state_create(mesh->env, qinfo, NULL,
		qflags&(BIT_RD|BIT_CD), 0, 0);
	if(!s) {
		log_err("prefetch mesh_state_create: out of memory");
		return;
	}
#ifdef UNBOUND_DEBUG
	n =
#else
	(void)
#endif
	rbtree_insert(&mesh->all, &s->node);
	log_assert(n != NULL);
	/* set detached (it is now) */
	mesh->num_detached_states++;
	/* make it ignore the cache */
	sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
	s->s.prefetch_leeway = leeway;

	if(s->list_select == mesh_no_list) {
		/* move to either the forever or the jostle_list */
		if(mesh->num_forever_states < mesh->max_forever_states) {
			mesh->num_forever_states ++;
			mesh_list_insert(s, &mesh->forever_first,
				&mesh->forever_last);
			s->list_select = mesh_forever_list;
		} else {
			mesh_list_insert(s, &mesh->jostle_first,
				&mesh->jostle_last);
			s->list_select = mesh_jostle_list;
		}
	}
	s->s.rpz_passthru = rpz_passthru;

	if(!run) {
#ifdef UNBOUND_DEBUG
		n =
#else
		(void)
#endif
		rbtree_insert(&mesh->run, &s->run_node);
		log_assert(n != NULL);
		return;
	}

	mesh_run(mesh, s, module_event_new, NULL);
}

#ifdef CLIENT_SUBNET
/* Same logic as mesh_schedule_prefetch but tailored to the subnet module logic
 * like passing along the comm_reply info. This will be faked into an EDNS
 * option for processing by the subnet module if the client has not already
 * attached its own ECS data. */
static void mesh_schedule_prefetch_subnet(struct mesh_area* mesh,
	struct query_info* qinfo, uint16_t qflags, time_t leeway, int run,
	int rpz_passthru, struct sockaddr_storage* addr, struct edns_option* edns_list)
{
	struct mesh_state* s = NULL;
	struct edns_option* opt = NULL;
#ifdef UNBOUND_DEBUG
	struct rbnode_type* n;
#endif
	if(!mesh_make_new_space(mesh, NULL)) {
		verbose(VERB_ALGO, "Too many queries. dropped prefetch.");
		mesh->stats_dropped ++;
		return;
	}

	s = mesh_state_create(mesh->env, qinfo, NULL,
		qflags&(BIT_RD|BIT_CD), 0, 0);
	if(!s) {
		log_err("prefetch_subnet mesh_state_create: out of memory");
		return;
	}
	mesh_state_make_unique(s);

	opt = edns_opt_list_find(edns_list, mesh->env->cfg->client_subnet_opcode);
	if(opt) {
		/* Use the client's ECS data */
		if(!edns_opt_list_append(&s->s.edns_opts_front_in, opt->opt_code,
			opt->opt_len, opt->opt_data, s->s.region)) {
			log_err("prefetch_subnet edns_opt_list_append: out of memory");
			return;
		}
	} else {
		/* Store the client's address. Later in the subnet module,
		 * it is decided whether to include an ECS option or not.
		 */
		s->s.client_addr =  *addr;
	}
#ifdef UNBOUND_DEBUG
	n =
#else
	(void)
#endif
	rbtree_insert(&mesh->all, &s->node);
	log_assert(n != NULL);
	/* set detached (it is now) */
	mesh->num_detached_states++;
	/* make it ignore the cache */
	sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
	s->s.prefetch_leeway = leeway;

	if(s->list_select == mesh_no_list) {
		/* move to either the forever or the jostle_list */
		if(mesh->num_forever_states < mesh->max_forever_states) {
			mesh->num_forever_states ++;
			mesh_list_insert(s, &mesh->forever_first,
				&mesh->forever_last);
			s->list_select = mesh_forever_list;
		} else {
			mesh_list_insert(s, &mesh->jostle_first,
				&mesh->jostle_last);
			s->list_select = mesh_jostle_list;
		}
	}
	s->s.rpz_passthru = rpz_passthru;

	if(!run) {
#ifdef UNBOUND_DEBUG
		n =
#else
		(void)
#endif
		rbtree_insert(&mesh->run, &s->run_node);
		log_assert(n != NULL);
		return;
	}

	mesh_run(mesh, s, module_event_new, NULL);
}
#endif /* CLIENT_SUBNET */

void mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo,
	uint16_t qflags, time_t leeway, int rpz_passthru,
	struct sockaddr_storage* addr, struct edns_option* opt_list)
{
	(void)addr;
	(void)opt_list;
#ifdef CLIENT_SUBNET
	if(addr)
		mesh_schedule_prefetch_subnet(mesh, qinfo, qflags, leeway, 1,
			rpz_passthru, addr, opt_list);
	else
#endif
		mesh_schedule_prefetch(mesh, qinfo, qflags, leeway, 1,
			rpz_passthru);
}

void mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e,
        struct comm_reply* reply, int what)
{
	enum module_ev event = module_event_reply;
	e->qstate->reply = reply;
	if(what != NETEVENT_NOERROR) {
		event = module_event_noreply;
		if(what == NETEVENT_CAPSFAIL)
			event = module_event_capsfail;
	}
	mesh_run(mesh, e->qstate->mesh_info, event, e);
}

struct mesh_state*
mesh_state_create(struct module_env* env, struct query_info* qinfo,
	struct respip_client_info* cinfo, uint16_t qflags, int prime,
	int valrec)
{
	struct regional* region = alloc_reg_obtain(env->alloc);
	struct mesh_state* mstate;
	int i;
	if(!region)
		return NULL;
	mstate = (struct mesh_state*)regional_alloc(region,
		sizeof(struct mesh_state));
	if(!mstate) {
		alloc_reg_release(env->alloc, region);
		return NULL;
	}
	memset(mstate, 0, sizeof(*mstate));
	mstate->node = *RBTREE_NULL;
	mstate->run_node = *RBTREE_NULL;
	mstate->node.key = mstate;
	mstate->run_node.key = mstate;
	mstate->reply_list = NULL;
	mstate->list_select = mesh_no_list;
	mstate->replies_sent = 0;
	rbtree_init(&mstate->super_set, &mesh_state_ref_compare);
	rbtree_init(&mstate->sub_set, &mesh_state_ref_compare);
	mstate->num_activated = 0;
	mstate->unique = NULL;
	/* init module qstate */
	mstate->s.qinfo.qtype = qinfo->qtype;
	mstate->s.qinfo.qclass = qinfo->qclass;
	mstate->s.qinfo.local_alias = NULL;
	mstate->s.qinfo.qname_len = qinfo->qname_len;
	mstate->s.qinfo.qname = regional_alloc_init(region, qinfo->qname,
		qinfo->qname_len);
	if(!mstate->s.qinfo.qname) {
		alloc_reg_release(env->alloc, region);
		return NULL;
	}
	if(cinfo) {
		mstate->s.client_info = regional_alloc_init(region, cinfo,
			sizeof(*cinfo));
		if(!mstate->s.client_info) {
			alloc_reg_release(env->alloc, region);
			return NULL;
		}
	}
	/* remove all weird bits from qflags */
	mstate->s.query_flags = (qflags & (BIT_RD|BIT_CD));
	mstate->s.is_priming = prime;
	mstate->s.is_valrec = valrec;
	mstate->s.reply = NULL;
	mstate->s.region = region;
	mstate->s.curmod = 0;
	mstate->s.return_msg = 0;
	mstate->s.return_rcode = LDNS_RCODE_NOERROR;
	mstate->s.env = env;
	mstate->s.mesh_info = mstate;
	mstate->s.prefetch_leeway = 0;
	mstate->s.serve_expired_data = NULL;
	mstate->s.no_cache_lookup = 0;
	mstate->s.no_cache_store = 0;
	mstate->s.need_refetch = 0;
	mstate->s.was_ratelimited = 0;
	mstate->s.qstarttime = *env->now;

	/* init modules */
	for(i=0; i<env->mesh->mods.num; i++) {
		mstate->s.minfo[i] = NULL;
		mstate->s.ext_state[i] = module_state_initial;
	}
	/* init edns option lists */
	mstate->s.edns_opts_front_in = NULL;
	mstate->s.edns_opts_back_out = NULL;
	mstate->s.edns_opts_back_in = NULL;
	mstate->s.edns_opts_front_out = NULL;

	return mstate;
}

void
mesh_state_make_unique(struct mesh_state* mstate)
{
	mstate->unique = mstate;
}

void
mesh_state_cleanup(struct mesh_state* mstate)
{
	struct mesh_area* mesh;
	int i;
	if(!mstate)
		return;
	mesh = mstate->s.env->mesh;
	/* Stop and delete the serve expired timer */
	if(mstate->s.serve_expired_data && mstate->s.serve_expired_data->timer) {
		comm_timer_delete(mstate->s.serve_expired_data->timer);
		mstate->s.serve_expired_data->timer = NULL;
	}
	/* drop unsent replies */
	if(!mstate->replies_sent) {
		struct mesh_reply* rep = mstate->reply_list;
		struct mesh_cb* cb;
		/* in tcp_req_info, the mstates linked are removed, but
		 * the reply_list is now NULL, so the remove-from-empty-list
		 * takes no time and also it does not do the mesh accounting */
		mstate->reply_list = NULL;
		for(; rep; rep=rep->next) {
			infra_wait_limit_dec(mesh->env->infra_cache,
				&rep->query_reply, mesh->env->cfg);
			comm_point_drop_reply(&rep->query_reply);
			log_assert(mesh->num_reply_addrs > 0);
			mesh->num_reply_addrs--;
		}
		while((cb = mstate->cb_list)!=NULL) {
			mstate->cb_list = cb->next;
			fptr_ok(fptr_whitelist_mesh_cb(cb->cb));
			(*cb->cb)(cb->cb_arg, LDNS_RCODE_SERVFAIL, NULL,
				sec_status_unchecked, NULL, 0);
			log_assert(mesh->num_reply_addrs > 0);
			mesh->num_reply_addrs--;
		}
	}

	/* de-init modules */
	for(i=0; i<mesh->mods.num; i++) {
		fptr_ok(fptr_whitelist_mod_clear(mesh->mods.mod[i]->clear));
		(*mesh->mods.mod[i]->clear)(&mstate->s, i);
		mstate->s.minfo[i] = NULL;
		mstate->s.ext_state[i] = module_finished;
	}
	alloc_reg_release(mstate->s.env->alloc, mstate->s.region);
}

void
mesh_state_delete(struct module_qstate* qstate)
{
	struct mesh_area* mesh;
	struct mesh_state_ref* super, ref;
	struct mesh_state* mstate;
	if(!qstate)
		return;
	mstate = qstate->mesh_info;
	mesh = mstate->s.env->mesh;
	mesh_detach_subs(&mstate->s);
	if(mstate->list_select == mesh_forever_list) {
		mesh->num_forever_states --;
		mesh_list_remove(mstate, &mesh->forever_first,
			&mesh->forever_last);
	} else if(mstate->list_select == mesh_jostle_list) {
		mesh_list_remove(mstate, &mesh->jostle_first,
			&mesh->jostle_last);
	}
	if(!mstate->reply_list && !mstate->cb_list
		&& mstate->super_set.count == 0) {
		log_assert(mesh->num_detached_states > 0);
		mesh->num_detached_states--;
	}
	if(mstate->reply_list || mstate->cb_list) {
		log_assert(mesh->num_reply_states > 0);
		mesh->num_reply_states--;
	}
	ref.node.key = &ref;
	ref.s = mstate;
	RBTREE_FOR(super, struct mesh_state_ref*, &mstate->super_set) {
		(void)rbtree_delete(&super->s->sub_set, &ref);
	}
	(void)rbtree_delete(&mesh->run, mstate);
	(void)rbtree_delete(&mesh->all, mstate);
	mesh_state_cleanup(mstate);
}

/** helper recursive rbtree find routine */
static int
find_in_subsub(struct mesh_state* m, struct mesh_state* tofind, size_t *c)
{
	struct mesh_state_ref* r;
	if((*c)++ > MESH_MAX_SUBSUB)
		return 1;
	RBTREE_FOR(r, struct mesh_state_ref*, &m->sub_set) {
		if(r->s == tofind || find_in_subsub(r->s, tofind, c))
			return 1;
	}
	return 0;
}

/** find cycle for already looked up mesh_state */
static int
mesh_detect_cycle_found(struct module_qstate* qstate, struct mesh_state* dep_m)
{
	struct mesh_state* cyc_m = qstate->mesh_info;
	size_t counter = 0;
	if(!dep_m)
		return 0;
	if(dep_m == cyc_m || find_in_subsub(dep_m, cyc_m, &counter)) {
		if(counter > MESH_MAX_SUBSUB)
			return 2;
		return 1;
	}
	return 0;
}

void mesh_detach_subs(struct module_qstate* qstate)
{
	struct mesh_area* mesh = qstate->env->mesh;
	struct mesh_state_ref* ref, lookup;
#ifdef UNBOUND_DEBUG
	struct rbnode_type* n;
#endif
	lookup.node.key = &lookup;
	lookup.s = qstate->mesh_info;
	RBTREE_FOR(ref, struct mesh_state_ref*, &qstate->mesh_info->sub_set) {
#ifdef UNBOUND_DEBUG
		n =
#else
		(void)
#endif
		rbtree_delete(&ref->s->super_set, &lookup);
		log_assert(n != NULL); /* must have been present */
		if(!ref->s->reply_list && !ref->s->cb_list
			&& ref->s->super_set.count == 0) {
			mesh->num_detached_states++;
			log_assert(mesh->num_detached_states +
				mesh->num_reply_states <= mesh->all.count);
		}
	}
	rbtree_init(&qstate->mesh_info->sub_set, &mesh_state_ref_compare);
}

int mesh_add_sub(struct module_qstate* qstate, struct query_info* qinfo,
        uint16_t qflags, int prime, int valrec, struct module_qstate** newq,
	struct mesh_state** sub)
{
	/* find it, if not, create it */
	struct mesh_area* mesh = qstate->env->mesh;
	*sub = mesh_area_find(mesh, NULL, qinfo, qflags,
		prime, valrec);
	if(mesh_detect_cycle_found(qstate, *sub)) {
		verbose(VERB_ALGO, "attach failed, cycle detected");
		return 0;
	}
	if(!*sub) {
#ifdef UNBOUND_DEBUG
		struct rbnode_type* n;
#endif
		/* create a new one */
		*sub = mesh_state_create(qstate->env, qinfo, NULL, qflags, prime,
			valrec);
		if(!*sub) {
			log_err("mesh_attach_sub: out of memory");
			return 0;
		}
#ifdef UNBOUND_DEBUG
		n =
#else
		(void)
#endif
		rbtree_insert(&mesh->all, &(*sub)->node);
		log_assert(n != NULL);
		/* set detached (it is now) */
		mesh->num_detached_states++;
		/* set new query state to run */
#ifdef UNBOUND_DEBUG
		n =
#else
		(void)
#endif
		rbtree_insert(&mesh->run, &(*sub)->run_node);
		log_assert(n != NULL);
		*newq = &(*sub)->s;
	} else
		*newq = NULL;
	return 1;
}

int mesh_attach_sub(struct module_qstate* qstate, struct query_info* qinfo,
        uint16_t qflags, int prime, int valrec, struct module_qstate** newq)
{
	struct mesh_area* mesh = qstate->env->mesh;
	struct mesh_state* sub = NULL;
	int was_detached;
	if(!mesh_add_sub(qstate, qinfo, qflags, prime, valrec, newq, &sub))
		return 0;
	was_detached = (sub->super_set.count == 0);
	if(!mesh_state_attachment(qstate->mesh_info, sub))
		return 0;
	/* if it was a duplicate  attachment, the count was not zero before */
	if(!sub->reply_list && !sub->cb_list && was_detached &&
		sub->super_set.count == 1) {
		/* it used to be detached, before this one got added */
		log_assert(mesh->num_detached_states > 0);
		mesh->num_detached_states--;
	}
	/* *newq will be run when inited after the current module stops */
	return 1;
}

int mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub)
{
#ifdef UNBOUND_DEBUG
	struct rbnode_type* n;
#endif
	struct mesh_state_ref* subref; /* points to sub, inserted in super */
	struct mesh_state_ref* superref; /* points to super, inserted in sub */
	if( !(subref = regional_alloc(super->s.region,
		sizeof(struct mesh_state_ref))) ||
		!(superref = regional_alloc(sub->s.region,
		sizeof(struct mesh_state_ref))) ) {
		log_err("mesh_state_attachment: out of memory");
		return 0;
	}
	superref->node.key = superref;
	superref->s = super;
	subref->node.key = subref;
	subref->s = sub;
	if(!rbtree_insert(&sub->super_set, &superref->node)) {
		/* this should not happen, iterator and validator do not
		 * attach subqueries that are identical. */
		/* already attached, we are done, nothing todo.
		 * since superref and subref already allocated in region,
		 * we cannot free them */
		return 1;
	}
#ifdef UNBOUND_DEBUG
	n =
#else
	(void)
#endif
	rbtree_insert(&super->sub_set, &subref->node);
	log_assert(n != NULL); /* we checked above if statement, the reverse
	  administration should not fail now, unless they are out of sync */
	return 1;
}

/**
 * callback results to mesh cb entry
 * @param m: mesh state to send it for.
 * @param rcode: if not 0, error code.
 * @param rep: reply to send (or NULL if rcode is set).
 * @param r: callback entry
 * @param start_time: the time to pass to callback functions, it is 0 or
 * 	a value from one of the packets if the mesh state had packets.
 */
static void
mesh_do_callback(struct mesh_state* m, int rcode, struct reply_info* rep,
	struct mesh_cb* r, struct timeval* start_time)
{
	int secure;
	char* reason = NULL;
	int was_ratelimited = m->s.was_ratelimited;
	/* bogus messages are not made into servfail, sec_status passed
	 * to the callback function */
	if(rep && rep->security == sec_status_secure)
		secure = 1;
	else	secure = 0;
	if(!rep && rcode == LDNS_RCODE_NOERROR)
		rcode = LDNS_RCODE_SERVFAIL;
	if(!rcode && rep && (rep->security == sec_status_bogus ||
		rep->security == sec_status_secure_sentinel_fail)) {
		if(!(reason = errinf_to_str_bogus(&m->s, NULL)))
			rcode = LDNS_RCODE_SERVFAIL;
	}
	/* send the reply */
	if(rcode) {
		if(rcode == LDNS_RCODE_SERVFAIL) {
			if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
				rep, rcode, &r->edns, NULL, m->s.region, start_time))
					r->edns.opt_list_inplace_cb_out = NULL;
		} else {
			if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode,
				&r->edns, NULL, m->s.region, start_time))
					r->edns.opt_list_inplace_cb_out = NULL;
		}
		fptr_ok(fptr_whitelist_mesh_cb(r->cb));
		(*r->cb)(r->cb_arg, rcode, r->buf, sec_status_unchecked, NULL,
			was_ratelimited);
	} else {
		size_t udp_size = r->edns.udp_size;
		sldns_buffer_clear(r->buf);
		r->edns.edns_version = EDNS_ADVERTISED_VERSION;
		r->edns.udp_size = EDNS_ADVERTISED_SIZE;
		r->edns.ext_rcode = 0;
		r->edns.bits &= EDNS_DO;
		if(m->s.env->cfg->disable_edns_do && (r->edns.bits&EDNS_DO))
			r->edns.edns_present = 0;

		if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep,
			LDNS_RCODE_NOERROR, &r->edns, NULL, m->s.region, start_time) ||
			!reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
			r->qflags, r->buf, 0, 1,
			m->s.env->scratch, udp_size, &r->edns,
			(int)(r->edns.bits & EDNS_DO), secure))
		{
			fptr_ok(fptr_whitelist_mesh_cb(r->cb));
			(*r->cb)(r->cb_arg, LDNS_RCODE_SERVFAIL, r->buf,
				sec_status_unchecked, NULL, 0);
		} else {
			fptr_ok(fptr_whitelist_mesh_cb(r->cb));
			(*r->cb)(r->cb_arg, LDNS_RCODE_NOERROR, r->buf,
				(rep?rep->security:sec_status_unchecked),
				reason, was_ratelimited);
		}
	}
	free(reason);
	log_assert(m->s.env->mesh->num_reply_addrs > 0);
	m->s.env->mesh->num_reply_addrs--;
}

static inline int
mesh_is_rpz_respip_tcponly_action(struct mesh_state const* m)
{
	struct respip_action_info const* respip_info = m->s.respip_action_info;
	return (respip_info == NULL
			? 0
			: (respip_info->rpz_used
			&& !respip_info->rpz_disabled
			&& respip_info->action == respip_truncate))
		|| m->s.tcp_required;
}

static inline int
mesh_is_udp(struct mesh_reply const* r)
{
	return r->query_reply.c->type == comm_udp;
}

static inline void
mesh_find_and_attach_ede_and_reason(struct mesh_state* m,
	struct reply_info* rep, struct mesh_reply* r)
{
	/* OLD note:
	 * During validation the EDE code can be received via two
	 * code paths. One code path fills the reply_info EDE, and
	 * the other fills it in the errinf_strlist. These paths
	 * intersect at some points, but where is opaque due to
	 * the complexity of the validator. At the time of writing
	 * we make the choice to prefer the EDE from errinf_strlist
	 * but a compelling reason to do otherwise is just as valid
	 * NEW note:
	 * The compelling reason is that with caching support, the value
	 * in the reply_info is cached.
	 * The reason members of the reply_info struct should be
	 * updated as they are already cached. No reason to
	 * try and find the EDE information in errinf anymore.
	 */
	if(rep->reason_bogus != LDNS_EDE_NONE) {
		edns_opt_list_append_ede(&r->edns.opt_list_out,
			m->s.region, rep->reason_bogus, rep->reason_bogus_str);
	}
}

/**
 * Send reply to mesh reply entry
 * @param m: mesh state to send it for.
 * @param rcode: if not 0, error code.
 * @param rep: reply to send (or NULL if rcode is set).
 * @param r: reply entry
 * @param r_buffer: buffer to use for reply entry.
 * @param prev: previous reply, already has its answer encoded in buffer.
 * @param prev_buffer: buffer for previous reply.
 */
static void
mesh_send_reply(struct mesh_state* m, int rcode, struct reply_info* rep,
	struct mesh_reply* r, struct sldns_buffer* r_buffer,
	struct mesh_reply* prev, struct sldns_buffer* prev_buffer)
{
	struct timeval end_time;
	struct timeval duration;
	int secure;
	/* briefly set the replylist to null in case the
	 * meshsendreply calls tcpreqinfo sendreply that
	 * comm_point_drops because of size, and then the
	 * null stops the mesh state remove and thus
	 * reply_list modification and accounting */
	struct mesh_reply* rlist = m->reply_list;

	/* rpz: apply actions */
	rcode = mesh_is_udp(r) && mesh_is_rpz_respip_tcponly_action(m)
			? (rcode|BIT_TC) : rcode;

	/* examine security status */
	if(m->s.env->need_to_validate && (!(r->qflags&BIT_CD) ||
		m->s.env->cfg->ignore_cd) && rep &&
		(rep->security <= sec_status_bogus ||
		rep->security == sec_status_secure_sentinel_fail)) {
		rcode = LDNS_RCODE_SERVFAIL;
		if(m->s.env->cfg->stat_extended)
			m->s.env->mesh->ans_bogus++;
	}
	if(rep && rep->security == sec_status_secure)
		secure = 1;
	else	secure = 0;
	if(!rep && rcode == LDNS_RCODE_NOERROR)
		rcode = LDNS_RCODE_SERVFAIL;
	if(r->query_reply.c->use_h2) {
		r->query_reply.c->h2_stream = r->h2_stream;
		/* Mesh reply won't exist for long anymore. Make it impossible
		 * for HTTP/2 stream to refer to mesh state, in case
		 * connection gets cleanup before HTTP/2 stream close. */
		r->h2_stream->mesh_state = NULL;
	}
	/* send the reply */
	/* We don't reuse the encoded answer if:
	 * - either the previous or current response has a local alias.  We could
	 *   compare the alias records and still reuse the previous answer if they
	 *   are the same, but that would be complicated and error prone for the
	 *   relatively minor case. So we err on the side of safety.
	 * - there are registered callback functions for the given rcode, as these
	 *   need to be called for each reply. */
	if(((rcode != LDNS_RCODE_SERVFAIL &&
			!m->s.env->inplace_cb_lists[inplace_cb_reply]) ||
		(rcode == LDNS_RCODE_SERVFAIL &&
			!m->s.env->inplace_cb_lists[inplace_cb_reply_servfail])) &&
		prev && prev_buffer && prev->qflags == r->qflags &&
		!prev->local_alias && !r->local_alias &&
		prev->edns.edns_present == r->edns.edns_present &&
		prev->edns.bits == r->edns.bits &&
		prev->edns.udp_size == r->edns.udp_size &&
		edns_opt_list_compare(prev->edns.opt_list_out, r->edns.opt_list_out) == 0 &&
		edns_opt_list_compare(prev->edns.opt_list_inplace_cb_out, r->edns.opt_list_inplace_cb_out) == 0
		) {
		/* if the previous reply is identical to this one, fix ID */
		if(prev_buffer != r_buffer)
			sldns_buffer_copy(r_buffer, prev_buffer);
		sldns_buffer_write_at(r_buffer, 0, &r->qid, sizeof(uint16_t));
		sldns_buffer_write_at(r_buffer, 12, r->qname,
			m->s.qinfo.qname_len);
		m->reply_list = NULL;
		comm_point_send_reply(&r->query_reply);
		m->reply_list = rlist;
	} else if(rcode) {
		m->s.qinfo.qname = r->qname;
		m->s.qinfo.local_alias = r->local_alias;
		if(rcode == LDNS_RCODE_SERVFAIL) {
			if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
				rep, rcode, &r->edns, &r->query_reply, m->s.region, &r->start_time))
					r->edns.opt_list_inplace_cb_out = NULL;
		} else {
			if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode,
				&r->edns, &r->query_reply, m->s.region, &r->start_time))
					r->edns.opt_list_inplace_cb_out = NULL;
		}
		/* Send along EDE EDNS0 option when SERVFAILing; usually
		 * DNSSEC validation failures */
		/* Since we are SERVFAILing here, CD bit and rep->security
		 * is already handled. */
		if(m->s.env->cfg->ede && rep) {
			mesh_find_and_attach_ede_and_reason(m, rep, r);
		}
		error_encode(r_buffer, rcode, &m->s.qinfo, r->qid,
			r->qflags, &r->edns);
		m->reply_list = NULL;
		comm_point_send_reply(&r->query_reply);
		m->reply_list = rlist;
	} else {
		size_t udp_size = r->edns.udp_size;
		r->edns.edns_version = EDNS_ADVERTISED_VERSION;
		r->edns.udp_size = EDNS_ADVERTISED_SIZE;
		r->edns.ext_rcode = 0;
		r->edns.bits &= EDNS_DO;
		if(m->s.env->cfg->disable_edns_do && (r->edns.bits&EDNS_DO))
			r->edns.edns_present = 0;
		m->s.qinfo.qname = r->qname;
		m->s.qinfo.local_alias = r->local_alias;

		/* Attach EDE without SERVFAIL if the validation failed.
		 * Need to explicitly check for rep->security otherwise failed
		 * validation paths may attach to a secure answer. */
		if(m->s.env->cfg->ede && rep &&
			(rep->security <= sec_status_bogus ||
			rep->security == sec_status_secure_sentinel_fail)) {
			mesh_find_and_attach_ede_and_reason(m, rep, r);
		}

		if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep,
			LDNS_RCODE_NOERROR, &r->edns, &r->query_reply, m->s.region, &r->start_time) ||
			!reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
			r->qflags, r_buffer, 0, 1, m->s.env->scratch,
			udp_size, &r->edns, (int)(r->edns.bits & EDNS_DO),
			secure))
		{
			if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
			rep, LDNS_RCODE_SERVFAIL, &r->edns, &r->query_reply, m->s.region, &r->start_time))
				r->edns.opt_list_inplace_cb_out = NULL;
			/* internal server error (probably malloc failure) so no
			 * EDE (RFC8914) needed */
			error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
				&m->s.qinfo, r->qid, r->qflags, &r->edns);
		}
		m->reply_list = NULL;
		comm_point_send_reply(&r->query_reply);
		m->reply_list = rlist;
	}
	infra_wait_limit_dec(m->s.env->infra_cache, &r->query_reply,
		m->s.env->cfg);
	/* account */
	log_assert(m->s.env->mesh->num_reply_addrs > 0);
	m->s.env->mesh->num_reply_addrs--;
	end_time = *m->s.env->now_tv;
	timeval_subtract(&duration, &end_time, &r->start_time);
	verbose(VERB_ALGO, "query took " ARG_LL "d.%6.6d sec",
		(long long)duration.tv_sec, (int)duration.tv_usec);
	m->s.env->mesh->replies_sent++;
	timeval_add(&m->s.env->mesh->replies_sum_wait, &duration);
	timehist_insert(m->s.env->mesh->histogram, &duration);
	if(m->s.env->cfg->stat_extended) {
		uint16_t rc = FLAGS_GET_RCODE(sldns_buffer_read_u16_at(
			r_buffer, 2));
		if(secure) m->s.env->mesh->ans_secure++;
		m->s.env->mesh->ans_rcode[ rc ] ++;
		if(rc == 0 && LDNS_ANCOUNT(sldns_buffer_begin(r_buffer)) == 0)
			m->s.env->mesh->ans_nodata++;
	}
	/* Log reply sent */
	if(m->s.env->cfg->log_replies) {
		log_reply_info(NO_VERBOSE, &m->s.qinfo,
			&r->query_reply.client_addr,
			r->query_reply.client_addrlen, duration, 0, r_buffer,
			(m->s.env->cfg->log_destaddr?(void*)r->query_reply.c->socket->addr:NULL),
			r->query_reply.c->type);
	}
}

void mesh_query_done(struct mesh_state* mstate)
{
	struct mesh_reply* r;
	struct mesh_reply* prev = NULL;
	struct sldns_buffer* prev_buffer = NULL;
	struct mesh_cb* c;
	struct reply_info* rep = (mstate->s.return_msg?
		mstate->s.return_msg->rep:NULL);
	struct timeval tv = {0, 0};
	int i = 0;
	/* No need for the serve expired timer anymore; we are going to reply. */
	if(mstate->s.serve_expired_data) {
		comm_timer_delete(mstate->s.serve_expired_data->timer);
		mstate->s.serve_expired_data->timer = NULL;
	}
	if(mstate->s.return_rcode == LDNS_RCODE_SERVFAIL ||
		(rep && FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_SERVFAIL)) {
		/* we are SERVFAILing; check for expired answer here */
		mesh_serve_expired_callback(mstate);
		if((mstate->reply_list || mstate->cb_list)
		&& mstate->s.env->cfg->log_servfail
		&& !mstate->s.env->cfg->val_log_squelch) {
			char* err = errinf_to_str_servfail(&mstate->s);
			if(err) { log_err("%s", err); }
		}
	}
	for(r = mstate->reply_list; r; r = r->next) {
		struct timeval old;
		timeval_subtract(&old, mstate->s.env->now_tv, &r->start_time);
		if(mstate->s.env->cfg->discard_timeout != 0 &&
			((int)old.tv_sec)*1000+((int)old.tv_usec)/1000 >
			mstate->s.env->cfg->discard_timeout) {
			/* Drop the reply, it is too old */
			/* briefly set the reply_list to NULL, so that the
			 * tcp req info cleanup routine that calls the mesh
			 * to deregister the meshstate for it is not done
			 * because the list is NULL and also accounting is not
			 * done there, but instead we do that here. */
			struct mesh_reply* reply_list = mstate->reply_list;
			verbose(VERB_ALGO, "drop reply, it is older than discard-timeout");
			infra_wait_limit_dec(mstate->s.env->infra_cache,
				&r->query_reply, mstate->s.env->cfg);
			mstate->reply_list = NULL;
			comm_point_drop_reply(&r->query_reply);
			mstate->reply_list = reply_list;
			mstate->s.env->mesh->stats_dropped++;
			continue;
		}

		i++;
		tv = r->start_time;

		/* if a response-ip address block has been stored the
		 *  information should be logged for each client. */
		if(mstate->s.respip_action_info &&
			mstate->s.respip_action_info->addrinfo) {
			respip_inform_print(mstate->s.respip_action_info,
				r->qname, mstate->s.qinfo.qtype,
				mstate->s.qinfo.qclass, r->local_alias,
				&r->query_reply.client_addr,
				r->query_reply.client_addrlen);
		}

		/* if this query is determined to be dropped during the
		 * mesh processing, this is the point to take that action. */
		if(mstate->s.is_drop) {
			/* briefly set the reply_list to NULL, so that the
			 * tcp req info cleanup routine that calls the mesh
			 * to deregister the meshstate for it is not done
			 * because the list is NULL and also accounting is not
			 * done there, but instead we do that here. */
			struct mesh_reply* reply_list = mstate->reply_list;
			infra_wait_limit_dec(mstate->s.env->infra_cache,
				&r->query_reply, mstate->s.env->cfg);
			mstate->reply_list = NULL;
			comm_point_drop_reply(&r->query_reply);
			mstate->reply_list = reply_list;
		} else {
			struct sldns_buffer* r_buffer = r->query_reply.c->buffer;
			if(r->query_reply.c->tcp_req_info) {
				r_buffer = r->query_reply.c->tcp_req_info->spool_buffer;
				prev_buffer = NULL;
			}
			mesh_send_reply(mstate, mstate->s.return_rcode, rep,
				r, r_buffer, prev, prev_buffer);
			if(r->query_reply.c->tcp_req_info) {
				tcp_req_info_remove_mesh_state(r->query_reply.c->tcp_req_info, mstate);
				r_buffer = NULL;
			}
			prev = r;
			prev_buffer = r_buffer;
		}
	}
	/* Account for each reply sent. */
	if(i > 0 && mstate->s.respip_action_info &&
		mstate->s.respip_action_info->addrinfo &&
		mstate->s.env->cfg->stat_extended &&
		mstate->s.respip_action_info->rpz_used) {
		if(mstate->s.respip_action_info->rpz_disabled)
			mstate->s.env->mesh->rpz_action[RPZ_DISABLED_ACTION] += i;
		if(mstate->s.respip_action_info->rpz_cname_override)
			mstate->s.env->mesh->rpz_action[RPZ_CNAME_OVERRIDE_ACTION] += i;
		else
			mstate->s.env->mesh->rpz_action[respip_action_to_rpz_action(
				mstate->s.respip_action_info->action)] += i;
	}
	if(!mstate->s.is_drop && i > 0) {
		if(mstate->s.env->cfg->stat_extended
			&& mstate->s.is_cachedb_answer) {
			mstate->s.env->mesh->ans_cachedb += i;
		}
	}

	/* Mesh area accounting */
	if(mstate->reply_list) {
		mstate->reply_list = NULL;
		if(!mstate->reply_list && !mstate->cb_list) {
			/* was a reply state, not anymore */
			log_assert(mstate->s.env->mesh->num_reply_states > 0);
			mstate->s.env->mesh->num_reply_states--;
		}
		if(!mstate->reply_list && !mstate->cb_list &&
			mstate->super_set.count == 0)
			mstate->s.env->mesh->num_detached_states++;
	}
	mstate->replies_sent = 1;

	while((c = mstate->cb_list) != NULL) {
		/* take this cb off the list; so that the list can be
		 * changed, eg. by adds from the callback routine */
		if(!mstate->reply_list && mstate->cb_list && !c->next) {
			/* was a reply state, not anymore */
			log_assert(mstate->s.env->mesh->num_reply_states > 0);
			mstate->s.env->mesh->num_reply_states--;
		}
		mstate->cb_list = c->next;
		if(!mstate->reply_list && !mstate->cb_list &&
			mstate->super_set.count == 0)
			mstate->s.env->mesh->num_detached_states++;
		mesh_do_callback(mstate, mstate->s.return_rcode, rep, c, &tv);
	}
}

void mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate)
{
	struct mesh_state_ref* ref;
	RBTREE_FOR(ref, struct mesh_state_ref*, &mstate->super_set)
	{
		/* make super runnable */
		(void)rbtree_insert(&mesh->run, &ref->s->run_node);
		/* callback the function to inform super of result */
		fptr_ok(fptr_whitelist_mod_inform_super(
			mesh->mods.mod[ref->s->s.curmod]->inform_super));
		(*mesh->mods.mod[ref->s->s.curmod]->inform_super)(&mstate->s,
			ref->s->s.curmod, &ref->s->s);
		/* copy state that is always relevant to super */
		copy_state_to_super(&mstate->s, ref->s->s.curmod, &ref->s->s);
	}
}

struct mesh_state* mesh_area_find(struct mesh_area* mesh,
	struct respip_client_info* cinfo, struct query_info* qinfo,
	uint16_t qflags, int prime, int valrec)
{
	struct mesh_state key;
	struct mesh_state* result;

	key.node.key = &key;
	key.s.is_priming = prime;
	key.s.is_valrec = valrec;
	key.s.qinfo = *qinfo;
	key.s.query_flags = qflags;
	/* We are searching for a similar mesh state when we DO want to
	 * aggregate the state. Thus unique is set to NULL. (default when we
	 * desire aggregation).*/
	key.unique = NULL;
	key.s.client_info = cinfo;

	result = (struct mesh_state*)rbtree_search(&mesh->all, &key);
	return result;
}

int mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns,
        sldns_buffer* buf, mesh_cb_func_type cb, void* cb_arg,
	uint16_t qid, uint16_t qflags)
{
	struct mesh_cb* r = regional_alloc(s->s.region,
		sizeof(struct mesh_cb));
	if(!r)
		return 0;
	r->buf = buf;
	log_assert(fptr_whitelist_mesh_cb(cb)); /* early failure ifmissing*/
	r->cb = cb;
	r->cb_arg = cb_arg;
	r->edns = *edns;
	if(edns->opt_list_in && !(r->edns.opt_list_in =
			edns_opt_copy_region(edns->opt_list_in, s->s.region)))
		return 0;
	if(edns->opt_list_out && !(r->edns.opt_list_out =
			edns_opt_copy_region(edns->opt_list_out, s->s.region)))
		return 0;
	if(edns->opt_list_inplace_cb_out && !(r->edns.opt_list_inplace_cb_out =
			edns_opt_copy_region(edns->opt_list_inplace_cb_out, s->s.region)))
		return 0;
	r->qid = qid;
	r->qflags = qflags;
	r->next = s->cb_list;
	s->cb_list = r;
	return 1;

}

int mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns,
        struct comm_reply* rep, uint16_t qid, uint16_t qflags,
        const struct query_info* qinfo)
{
	struct mesh_reply* r = regional_alloc(s->s.region,
		sizeof(struct mesh_reply));
	if(!r)
		return 0;
	r->query_reply = *rep;
	r->edns = *edns;
	if(edns->opt_list_in && !(r->edns.opt_list_in =
			edns_opt_copy_region(edns->opt_list_in, s->s.region)))
		return 0;
	if(edns->opt_list_out && !(r->edns.opt_list_out =
			edns_opt_copy_region(edns->opt_list_out, s->s.region)))
		return 0;
	if(edns->opt_list_inplace_cb_out && !(r->edns.opt_list_inplace_cb_out =
			edns_opt_copy_region(edns->opt_list_inplace_cb_out, s->s.region)))
		return 0;
	r->qid = qid;
	r->qflags = qflags;
	r->start_time = *s->s.env->now_tv;
	r->next = s->reply_list;
	r->qname = regional_alloc_init(s->s.region, qinfo->qname,
		s->s.qinfo.qname_len);
	if(!r->qname)
		return 0;
	if(rep->c->use_h2)
		r->h2_stream = rep->c->h2_stream;

	/* Data related to local alias stored in 'qinfo' (if any) is ephemeral
	 * and can be different for different original queries (even if the
	 * replaced query name is the same).  So we need to make a deep copy
	 * and store the copy for each reply info. */
	if(qinfo->local_alias) {
		struct packed_rrset_data* d;
		struct packed_rrset_data* dsrc;
		r->local_alias = regional_alloc_zero(s->s.region,
			sizeof(*qinfo->local_alias));
		if(!r->local_alias)
			return 0;
		r->local_alias->rrset = regional_alloc_init(s->s.region,
			qinfo->local_alias->rrset,
			sizeof(*qinfo->local_alias->rrset));
		if(!r->local_alias->rrset)
			return 0;
		dsrc = qinfo->local_alias->rrset->entry.data;

		/* In the current implementation, a local alias must be
		 * a single CNAME RR (see worker_handle_request()). */
		log_assert(!qinfo->local_alias->next && dsrc->count == 1 &&
			qinfo->local_alias->rrset->rk.type ==
			htons(LDNS_RR_TYPE_CNAME));
		/* we should make a local copy for the owner name of
		 * the RRset */
		r->local_alias->rrset->rk.dname_len =
			qinfo->local_alias->rrset->rk.dname_len;
		r->local_alias->rrset->rk.dname = regional_alloc_init(
			s->s.region, qinfo->local_alias->rrset->rk.dname,
			qinfo->local_alias->rrset->rk.dname_len);
		if(!r->local_alias->rrset->rk.dname)
			return 0;

		/* the rrset is not packed, like in the cache, but it is
		 * individually allocated with an allocator from localzone. */
		d = regional_alloc_zero(s->s.region, sizeof(*d));
		if(!d)
			return 0;
		r->local_alias->rrset->entry.data = d;
		if(!rrset_insert_rr(s->s.region, d, dsrc->rr_data[0],
			dsrc->rr_len[0], dsrc->rr_ttl[0], "CNAME local alias"))
			return 0;
	} else
		r->local_alias = NULL;

	s->reply_list = r;
	return 1;
}

/* Extract the query info and flags from 'mstate' into '*qinfop' and '*qflags'.
 * Since this is only used for internal refetch of otherwise-expired answer,
 * we simply ignore the rare failure mode when memory allocation fails. */
static void
mesh_copy_qinfo(struct mesh_state* mstate, struct query_info** qinfop,
	uint16_t* qflags)
{
	struct regional* region = mstate->s.env->scratch;
	struct query_info* qinfo;

	qinfo = regional_alloc_init(region, &mstate->s.qinfo, sizeof(*qinfo));
	if(!qinfo)
		return;
	qinfo->qname = regional_alloc_init(region, qinfo->qname,
		qinfo->qname_len);
	if(!qinfo->qname)
		return;
	*qinfop = qinfo;
	*qflags = mstate->s.query_flags;
}

/**
 * Continue processing the mesh state at another module.
 * Handles module to modules transfer of control.
 * Handles module finished.
 * @param mesh: the mesh area.
 * @param mstate: currently active mesh state.
 * 	Deleted if finished, calls _done and _supers to
 * 	send replies to clients and inform other mesh states.
 * 	This in turn may create additional runnable mesh states.
 * @param s: state at which the current module exited.
 * @param ev: the event sent to the module.
 * 	returned is the event to send to the next module.
 * @return true if continue processing at the new module.
 * 	false if not continued processing is needed.
 */
static int
mesh_continue(struct mesh_area* mesh, struct mesh_state* mstate,
	enum module_ext_state s, enum module_ev* ev)
{
	mstate->num_activated++;
	if(mstate->num_activated > MESH_MAX_ACTIVATION) {
		/* module is looping. Stop it. */
		log_err("internal error: looping module (%s) stopped",
			mesh->mods.mod[mstate->s.curmod]->name);
		log_query_info(NO_VERBOSE, "pass error for qstate",
			&mstate->s.qinfo);
		s = module_error;
	}
	if(s == module_wait_module || s == module_restart_next) {
		/* start next module */
		mstate->s.curmod++;
		if(mesh->mods.num == mstate->s.curmod) {
			log_err("Cannot pass to next module; at last module");
			log_query_info(VERB_QUERY, "pass error for qstate",
				&mstate->s.qinfo);
			mstate->s.curmod--;
			return mesh_continue(mesh, mstate, module_error, ev);
		}
		if(s == module_restart_next) {
			int curmod = mstate->s.curmod;
			for(; mstate->s.curmod < mesh->mods.num;
				mstate->s.curmod++) {
				fptr_ok(fptr_whitelist_mod_clear(
					mesh->mods.mod[mstate->s.curmod]->clear));
				(*mesh->mods.mod[mstate->s.curmod]->clear)
					(&mstate->s, mstate->s.curmod);
				mstate->s.minfo[mstate->s.curmod] = NULL;
			}
			mstate->s.curmod = curmod;
		}
		*ev = module_event_pass;
		return 1;
	}
	if(s == module_wait_subquery && mstate->sub_set.count == 0) {
		log_err("module cannot wait for subquery, subquery list empty");
		log_query_info(VERB_QUERY, "pass error for qstate",
			&mstate->s.qinfo);
		s = module_error;
	}
	if(s == module_error && mstate->s.return_rcode == LDNS_RCODE_NOERROR) {
		/* error is bad, handle pass back up below */
		mstate->s.return_rcode = LDNS_RCODE_SERVFAIL;
	}
	if(s == module_error) {
		mesh_query_done(mstate);
		mesh_walk_supers(mesh, mstate);
		mesh_state_delete(&mstate->s);
		return 0;
	}
	if(s == module_finished) {
		if(mstate->s.curmod == 0) {
			struct query_info* qinfo = NULL;
			struct edns_option* opt_list = NULL;
			struct sockaddr_storage addr;
			uint16_t qflags;
			int rpz_p = 0;

#ifdef CLIENT_SUBNET
			struct edns_option* ecs;
			if(mstate->s.need_refetch && mstate->reply_list &&
				modstack_find(&mesh->mods, "subnetcache") != -1 &&
				mstate->s.env->unique_mesh) {
				addr = mstate->reply_list->query_reply.client_addr;
			} else
#endif
				memset(&addr, 0, sizeof(addr));

			mesh_query_done(mstate);
			mesh_walk_supers(mesh, mstate);

			/* If the answer to the query needs to be refetched
			 * from an external DNS server, we'll need to schedule
			 * a prefetch after removing the current state, so
			 * we need to make a copy of the query info here. */
			if(mstate->s.need_refetch) {
				mesh_copy_qinfo(mstate, &qinfo, &qflags);
#ifdef CLIENT_SUBNET
				/* Make also a copy of the ecs option if any */
				if((ecs = edns_opt_list_find(
					mstate->s.edns_opts_front_in,
					mstate->s.env->cfg->client_subnet_opcode)) != NULL) {
					(void)edns_opt_list_append(&opt_list,
						ecs->opt_code, ecs->opt_len,
						ecs->opt_data,
						mstate->s.env->scratch);
				}
#endif
				rpz_p = mstate->s.rpz_passthru;
			}

			if(qinfo) {
				mesh_state_delete(&mstate->s);
				mesh_new_prefetch(mesh, qinfo, qflags, 0,
					rpz_p,
					addr.ss_family!=AF_UNSPEC?&addr:NULL,
					opt_list);
			} else {
				mesh_state_delete(&mstate->s);
			}
			return 0;
		}
		/* pass along the locus of control */
		mstate->s.curmod --;
		*ev = module_event_moddone;
		return 1;
	}
	return 0;
}

void mesh_run(struct mesh_area* mesh, struct mesh_state* mstate,
	enum module_ev ev, struct outbound_entry* e)
{
	enum module_ext_state s;
	verbose(VERB_ALGO, "mesh_run: start");
	while(mstate) {
		/* run the module */
		fptr_ok(fptr_whitelist_mod_operate(
			mesh->mods.mod[mstate->s.curmod]->operate));
		(*mesh->mods.mod[mstate->s.curmod]->operate)
			(&mstate->s, ev, mstate->s.curmod, e);

		/* examine results */
		mstate->s.reply = NULL;
		regional_free_all(mstate->s.env->scratch);
		s = mstate->s.ext_state[mstate->s.curmod];
		verbose(VERB_ALGO, "mesh_run: %s module exit state is %s",
			mesh->mods.mod[mstate->s.curmod]->name, strextstate(s));
		e = NULL;
		if(mesh_continue(mesh, mstate, s, &ev))
			continue;

		/* run more modules */
		ev = module_event_pass;
		if(mesh->run.count > 0) {
			/* pop random element off the runnable tree */
			mstate = (struct mesh_state*)mesh->run.root->key;
			(void)rbtree_delete(&mesh->run, mstate);
		} else mstate = NULL;
	}
	if(verbosity >= VERB_ALGO) {
		mesh_stats(mesh, "mesh_run: end");
		mesh_log_list(mesh);
	}
}

void
mesh_log_list(struct mesh_area* mesh)
{
	char buf[30];
	struct mesh_state* m;
	int num = 0;
	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
		snprintf(buf, sizeof(buf), "%d%s%s%s%s%s%s mod%d %s%s",
			num++, (m->s.is_priming)?"p":"",  /* prime */
			(m->s.is_valrec)?"v":"",  /* prime */
			(m->s.query_flags&BIT_RD)?"RD":"",
			(m->s.query_flags&BIT_CD)?"CD":"",
			(m->super_set.count==0)?"d":"", /* detached */
			(m->sub_set.count!=0)?"c":"",  /* children */
			m->s.curmod, (m->reply_list)?"rep":"", /*hasreply*/
			(m->cb_list)?"cb":"" /* callbacks */
			);
		log_query_info(VERB_ALGO, buf, &m->s.qinfo);
	}
}

void
mesh_stats(struct mesh_area* mesh, const char* str)
{
	verbose(VERB_DETAIL, "%s %u recursion states (%u with reply, "
		"%u detached), %u waiting replies, %u recursion replies "
		"sent, %d replies dropped, %d states jostled out",
		str, (unsigned)mesh->all.count,
		(unsigned)mesh->num_reply_states,
		(unsigned)mesh->num_detached_states,
		(unsigned)mesh->num_reply_addrs,
		(unsigned)mesh->replies_sent,
		(unsigned)mesh->stats_dropped,
		(unsigned)mesh->stats_jostled);
	if(mesh->replies_sent > 0) {
		struct timeval avg;
		timeval_divide(&avg, &mesh->replies_sum_wait,
			mesh->replies_sent);
		log_info("average recursion processing time "
			ARG_LL "d.%6.6d sec",
			(long long)avg.tv_sec, (int)avg.tv_usec);
		log_info("histogram of recursion processing times");
		timehist_log(mesh->histogram, "recursions");
	}
}

void
mesh_stats_clear(struct mesh_area* mesh)
{
	if(!mesh)
		return;
	mesh->replies_sent = 0;
	mesh->replies_sum_wait.tv_sec = 0;
	mesh->replies_sum_wait.tv_usec = 0;
	mesh->stats_jostled = 0;
	mesh->stats_dropped = 0;
	timehist_clear(mesh->histogram);
	mesh->ans_secure = 0;
	mesh->ans_bogus = 0;
	mesh->ans_expired = 0;
	mesh->ans_cachedb = 0;
	memset(&mesh->ans_rcode[0], 0, sizeof(size_t)*UB_STATS_RCODE_NUM);
	memset(&mesh->rpz_action[0], 0, sizeof(size_t)*UB_STATS_RPZ_ACTION_NUM);
	mesh->ans_nodata = 0;
}

size_t
mesh_get_mem(struct mesh_area* mesh)
{
	struct mesh_state* m;
	size_t s = sizeof(*mesh) + sizeof(struct timehist) +
		sizeof(struct th_buck)*mesh->histogram->num +
		sizeof(sldns_buffer) + sldns_buffer_capacity(mesh->qbuf_bak);
	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
		/* all, including m itself allocated in qstate region */
		s += regional_get_mem(m->s.region);
	}
	return s;
}

int
mesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo,
	uint16_t flags, int prime, int valrec)
{
	struct mesh_area* mesh = qstate->env->mesh;
	struct mesh_state* dep_m = NULL;
	dep_m = mesh_area_find(mesh, NULL, qinfo, flags, prime, valrec);
	return mesh_detect_cycle_found(qstate, dep_m);
}

void mesh_list_insert(struct mesh_state* m, struct mesh_state** fp,
        struct mesh_state** lp)
{
	/* insert as last element */
	m->prev = *lp;
	m->next = NULL;
	if(*lp)
		(*lp)->next = m;
	else	*fp = m;
	*lp = m;
}

void mesh_list_remove(struct mesh_state* m, struct mesh_state** fp,
        struct mesh_state** lp)
{
	if(m->next)
		m->next->prev = m->prev;
	else	*lp = m->prev;
	if(m->prev)
		m->prev->next = m->next;
	else	*fp = m->next;
}

void mesh_state_remove_reply(struct mesh_area* mesh, struct mesh_state* m,
	struct comm_point* cp)
{
	struct mesh_reply* n, *prev = NULL;
	n = m->reply_list;
	/* when in mesh_cleanup, it sets the reply_list to NULL, so that
	 * there is no accounting twice */
	if(!n) return; /* nothing to remove, also no accounting needed */
	while(n) {
		if(n->query_reply.c == cp) {
			/* unlink it */
			if(prev) prev->next = n->next;
			else m->reply_list = n->next;
			/* delete it, but allocated in m region */
			log_assert(mesh->num_reply_addrs > 0);
			mesh->num_reply_addrs--;
			infra_wait_limit_dec(mesh->env->infra_cache,
				&n->query_reply, mesh->env->cfg);

			/* prev = prev; */
			n = n->next;
			continue;
		}
		prev = n;
		n = n->next;
	}
	/* it was not detached (because it had a reply list), could be now */
	if(!m->reply_list && !m->cb_list
		&& m->super_set.count == 0) {
		mesh->num_detached_states++;
	}
	/* if not replies any more in mstate, it is no longer a reply_state */
	if(!m->reply_list && !m->cb_list) {
		log_assert(mesh->num_reply_states > 0);
		mesh->num_reply_states--;
	}
}


static int
apply_respip_action(struct module_qstate* qstate,
	const struct query_info* qinfo, struct respip_client_info* cinfo,
	struct respip_action_info* actinfo, struct reply_info* rep,
	struct ub_packed_rrset_key** alias_rrset,
	struct reply_info** encode_repp, struct auth_zones* az)
{
	if(qinfo->qtype != LDNS_RR_TYPE_A &&
		qinfo->qtype != LDNS_RR_TYPE_AAAA &&
		qinfo->qtype != LDNS_RR_TYPE_ANY)
		return 1;

	if(!respip_rewrite_reply(qinfo, cinfo, rep, encode_repp, actinfo,
		alias_rrset, 0, qstate->region, az, NULL))
		return 0;

	/* xxx_deny actions mean dropping the reply, unless the original reply
	 * was redirected to response-ip data. */
	if((actinfo->action == respip_deny ||
		actinfo->action == respip_inform_deny) &&
		*encode_repp == rep)
		*encode_repp = NULL;

	return 1;
}

void
mesh_serve_expired_callback(void* arg)
{
	struct mesh_state* mstate = (struct mesh_state*) arg;
	struct module_qstate* qstate = &mstate->s;
	struct mesh_reply* r;
	struct mesh_area* mesh = qstate->env->mesh;
	struct dns_msg* msg;
	struct mesh_cb* c;
	struct mesh_reply* prev = NULL;
	struct sldns_buffer* prev_buffer = NULL;
	struct sldns_buffer* r_buffer = NULL;
	struct reply_info* partial_rep = NULL;
	struct ub_packed_rrset_key* alias_rrset = NULL;
	struct reply_info* encode_rep = NULL;
	struct respip_action_info actinfo;
	struct query_info* lookup_qinfo = &qstate->qinfo;
	struct query_info qinfo_tmp;
	struct timeval tv = {0, 0};
	int must_validate = (!(qstate->query_flags&BIT_CD)
		|| qstate->env->cfg->ignore_cd) && qstate->env->need_to_validate;
	int i = 0;
	if(!qstate->serve_expired_data) return;
	verbose(VERB_ALGO, "Serve expired: Trying to reply with expired data");
	comm_timer_delete(qstate->serve_expired_data->timer);
	qstate->serve_expired_data->timer = NULL;
	/* If is_drop or no_cache_lookup (modules that handle their own cache e.g.,
	 * subnetmod) ignore stale data from the main cache. */
	if(qstate->no_cache_lookup || qstate->is_drop) {
		verbose(VERB_ALGO,
			"Serve expired: Not allowed to look into cache for stale");
		return;
	}
	/* The following while is used instead of the `goto lookup_cache`
	 * like in the worker. */
	while(1) {
		fptr_ok(fptr_whitelist_serve_expired_lookup(
			qstate->serve_expired_data->get_cached_answer));
		msg = (*qstate->serve_expired_data->get_cached_answer)(qstate,
			lookup_qinfo);
		if(!msg)
			return;
		/* Reset these in case we pass a second time from here. */
		encode_rep = msg->rep;
		memset(&actinfo, 0, sizeof(actinfo));
		actinfo.action = respip_none;
		alias_rrset = NULL;
		if((mesh->use_response_ip || mesh->use_rpz) &&
			!partial_rep && !apply_respip_action(qstate, &qstate->qinfo,
			qstate->client_info, &actinfo, msg->rep, &alias_rrset, &encode_rep,
			qstate->env->auth_zones)) {
			return;
		} else if(partial_rep &&
			!respip_merge_cname(partial_rep, &qstate->qinfo, msg->rep,
			qstate->client_info, must_validate, &encode_rep, qstate->region,
			qstate->env->auth_zones)) {
			return;
		}
		if(!encode_rep || alias_rrset) {
			if(!encode_rep) {
				/* Needs drop */
				return;
			} else {
				/* A partial CNAME chain is found. */
				partial_rep = encode_rep;
			}
		}
		/* We've found a partial reply ending with an
		* alias.  Replace the lookup qinfo for the
		* alias target and lookup the cache again to
		* (possibly) complete the reply.  As we're
		* passing the "base" reply, there will be no
		* more alias chasing. */
		if(partial_rep) {
			memset(&qinfo_tmp, 0, sizeof(qinfo_tmp));
			get_cname_target(alias_rrset, &qinfo_tmp.qname,
				&qinfo_tmp.qname_len);
			if(!qinfo_tmp.qname) {
				log_err("Serve expired: unexpected: invalid answer alias");
				return;
			}
			qinfo_tmp.qtype = qstate->qinfo.qtype;
			qinfo_tmp.qclass = qstate->qinfo.qclass;
			lookup_qinfo = &qinfo_tmp;
			continue;
		}
		break;
	}

	if(verbosity >= VERB_ALGO)
		log_dns_msg("Serve expired lookup", &qstate->qinfo, msg->rep);

	for(r = mstate->reply_list; r; r = r->next) {
		struct timeval old;
		timeval_subtract(&old, mstate->s.env->now_tv, &r->start_time);
		if(mstate->s.env->cfg->discard_timeout != 0 &&
			((int)old.tv_sec)*1000+((int)old.tv_usec)/1000 >
			mstate->s.env->cfg->discard_timeout) {
			/* Drop the reply, it is too old */
			/* briefly set the reply_list to NULL, so that the
			 * tcp req info cleanup routine that calls the mesh
			 * to deregister the meshstate for it is not done
			 * because the list is NULL and also accounting is not
			 * done there, but instead we do that here. */
			struct mesh_reply* reply_list = mstate->reply_list;
			verbose(VERB_ALGO, "drop reply, it is older than discard-timeout");
			infra_wait_limit_dec(mstate->s.env->infra_cache,
				&r->query_reply, mstate->s.env->cfg);
			mstate->reply_list = NULL;
			comm_point_drop_reply(&r->query_reply);
			mstate->reply_list = reply_list;
			mstate->s.env->mesh->stats_dropped++;
			continue;
		}

		i++;
		tv = r->start_time;

		/* If address info is returned, it means the action should be an
		* 'inform' variant and the information should be logged. */
		if(actinfo.addrinfo) {
			respip_inform_print(&actinfo, r->qname,
				qstate->qinfo.qtype, qstate->qinfo.qclass,
				r->local_alias, &r->query_reply.client_addr,
				r->query_reply.client_addrlen);
		}

		/* Add EDE Stale Answer (RCF8914). Ignore global ede as this is
		 * warning instead of an error */
		if (r->edns.edns_present && qstate->env->cfg->ede_serve_expired &&
			qstate->env->cfg->ede) {
			edns_opt_list_append_ede(&r->edns.opt_list_out,
				mstate->s.region, LDNS_EDE_STALE_ANSWER, NULL);
		}

		r_buffer = r->query_reply.c->buffer;
		if(r->query_reply.c->tcp_req_info)
			r_buffer = r->query_reply.c->tcp_req_info->spool_buffer;
		mesh_send_reply(mstate, LDNS_RCODE_NOERROR, msg->rep,
			r, r_buffer, prev, prev_buffer);
		if(r->query_reply.c->tcp_req_info)
			tcp_req_info_remove_mesh_state(r->query_reply.c->tcp_req_info, mstate);
		infra_wait_limit_dec(mstate->s.env->infra_cache,
			&r->query_reply, mstate->s.env->cfg);
		prev = r;
		prev_buffer = r_buffer;
	}
	/* Account for each reply sent. */
	if(i > 0) {
		mesh->ans_expired += i;
		if(actinfo.addrinfo && qstate->env->cfg->stat_extended &&
			actinfo.rpz_used) {
			if(actinfo.rpz_disabled)
				qstate->env->mesh->rpz_action[RPZ_DISABLED_ACTION] += i;
			if(actinfo.rpz_cname_override)
				qstate->env->mesh->rpz_action[RPZ_CNAME_OVERRIDE_ACTION] += i;
			else
				qstate->env->mesh->rpz_action[
					respip_action_to_rpz_action(actinfo.action)] += i;
		}
	}

	/* Mesh area accounting */
	if(mstate->reply_list) {
		mstate->reply_list = NULL;
		if(!mstate->reply_list && !mstate->cb_list) {
			log_assert(mesh->num_reply_states > 0);
			mesh->num_reply_states--;
			if(mstate->super_set.count == 0) {
				mesh->num_detached_states++;
			}
		}
	}

	while((c = mstate->cb_list) != NULL) {
		/* take this cb off the list; so that the list can be
		 * changed, eg. by adds from the callback routine */
		if(!mstate->reply_list && mstate->cb_list && !c->next) {
			/* was a reply state, not anymore */
			log_assert(qstate->env->mesh->num_reply_states > 0);
			qstate->env->mesh->num_reply_states--;
		}
		mstate->cb_list = c->next;
		if(!mstate->reply_list && !mstate->cb_list &&
			mstate->super_set.count == 0)
			qstate->env->mesh->num_detached_states++;
		mesh_do_callback(mstate, LDNS_RCODE_NOERROR, msg->rep, c, &tv);
	}
}

void
mesh_respond_serve_expired(struct mesh_state* mstate)
{
	if(!mstate->s.serve_expired_data)
		mesh_serve_expired_init(mstate, -1);
	mesh_serve_expired_callback(mstate);
}

int mesh_jostle_exceeded(struct mesh_area* mesh)
{
	if(mesh->all.count < mesh->max_reply_states)
		return 0;
	return 1;
}