summaryrefslogtreecommitdiffstats
path: root/dnsdist-web.cc
blob: 000579e4b603b4eb84938e8231117a3d1f4df2f5 (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
/*
 * This file is part of PowerDNS or dnsdist.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <boost/format.hpp>
#include <sstream>
#include <sys/time.h>
#include <sys/resource.h>
#include <thread>

#include "ext/json11/json11.hpp"
#include <yahttp/yahttp.hpp>

#include "base64.hh"
#include "connection-management.hh"
#include "dnsdist.hh"
#include "dnsdist-dynblocks.hh"
#include "dnsdist-healthchecks.hh"
#include "dnsdist-metrics.hh"
#include "dnsdist-prometheus.hh"
#include "dnsdist-rings.hh"
#include "dnsdist-web.hh"
#include "dolog.hh"
#include "gettime.hh"
#include "threadname.hh"
#include "sstuff.hh"

struct WebserverConfig
{
  WebserverConfig()
  {
    acl.toMasks("127.0.0.1, ::1");
  }

  NetmaskGroup acl;
  std::unique_ptr<CredentialsHolder> password;
  std::unique_ptr<CredentialsHolder> apiKey;
  boost::optional<std::unordered_map<std::string, std::string> > customHeaders;
  bool apiRequiresAuthentication{true};
  bool dashboardRequiresAuthentication{true};
  bool statsRequireAuthentication{true};
};

bool g_apiReadWrite{false};
LockGuarded<WebserverConfig> g_webserverConfig;
std::string g_apiConfigDirectory;

static ConcurrentConnectionManager s_connManager(100);

std::string getWebserverConfig()
{
  ostringstream out;

  {
    auto config = g_webserverConfig.lock();
    out << "Current web server configuration:" << endl;
    out << "ACL: " << config->acl.toString() << endl;
    out << "Custom headers: ";
    if (config->customHeaders) {
      out << endl;
      for (const auto& header : *config->customHeaders) {
        out << " - " << header.first << ": " << header.second << endl;
      }
    }
    else {
      out << "None" << endl;
    }
    out << "API requires authentication: " << (config->apiRequiresAuthentication ? "yes" : "no") << endl;
    out << "Dashboard requires authentication: " << (config->dashboardRequiresAuthentication ? "yes" : "no") << endl;
    out << "Statistics require authentication: " << (config->statsRequireAuthentication ? "yes" : "no") << endl;
    out << "Password: " << (config->password ? "set" : "unset") << endl;
    out << "API key: " << (config->apiKey ? "set" : "unset") << endl;
  }
  out << "API writable: " << (g_apiReadWrite ? "yes" : "no") << endl;
  out << "API configuration directory: " << g_apiConfigDirectory << endl;
  out << "Maximum concurrent connections: " << s_connManager.getMaxConcurrentConnections() << endl;

  return out.str();
}

class WebClientConnection
{
public:
  WebClientConnection(const ComboAddress& client, int fd): d_client(client), d_socket(fd)
  {
    if (!s_connManager.registerConnection()) {
      throw std::runtime_error("Too many concurrent web client connections");
    }
  }
  WebClientConnection(WebClientConnection&& rhs): d_client(rhs.d_client), d_socket(std::move(rhs.d_socket))
  {
  }

  WebClientConnection(const WebClientConnection&) = delete;
  WebClientConnection& operator=(const WebClientConnection&) = delete;

  ~WebClientConnection()
  {
    if (d_socket.getHandle() != -1) {
      s_connManager.releaseConnection();
    }
  }

  const Socket& getSocket() const
  {
    return d_socket;
  }

  const ComboAddress& getClient() const
  {
    return d_client;
  }

private:
  ComboAddress d_client;
  Socket d_socket;
};

#ifndef DISABLE_PROMETHEUS
static MetricDefinitionStorage s_metricDefinitions;

std::map<std::string, MetricDefinition> MetricDefinitionStorage::metrics{
  { "responses",                             MetricDefinition(PrometheusMetricType::counter, "Number of responses received from backends") },
  { "servfail-responses",                    MetricDefinition(PrometheusMetricType::counter, "Number of SERVFAIL answers received from backends") },
  { "queries",                               MetricDefinition(PrometheusMetricType::counter, "Number of received queries")},
  { "frontend-nxdomain",                     MetricDefinition(PrometheusMetricType::counter, "Number of NXDomain answers sent to clients")},
  { "frontend-servfail",                     MetricDefinition(PrometheusMetricType::counter, "Number of SERVFAIL answers sent to clients")},
  { "frontend-noerror",                      MetricDefinition(PrometheusMetricType::counter, "Number of NoError answers sent to clients")},
  { "acl-drops",                             MetricDefinition(PrometheusMetricType::counter, "Number of packets dropped because of the ACL")},
  { "rule-drop",                             MetricDefinition(PrometheusMetricType::counter, "Number of queries dropped because of a rule")},
  { "rule-nxdomain",                         MetricDefinition(PrometheusMetricType::counter, "Number of NXDomain answers returned because of a rule")},
  { "rule-refused",                          MetricDefinition(PrometheusMetricType::counter, "Number of Refused answers returned because of a rule")},
  { "rule-servfail",                         MetricDefinition(PrometheusMetricType::counter, "Number of SERVFAIL answers received because of a rule")},
  { "rule-truncated",                        MetricDefinition(PrometheusMetricType::counter, "Number of truncated answers returned because of a rule")},
  { "self-answered",                         MetricDefinition(PrometheusMetricType::counter, "Number of self-answered responses")},
  { "downstream-timeouts",                   MetricDefinition(PrometheusMetricType::counter, "Number of queries not answered in time by a backend")},
  { "downstream-send-errors",                MetricDefinition(PrometheusMetricType::counter, "Number of errors when sending a query to a backend")},
  { "trunc-failures",                        MetricDefinition(PrometheusMetricType::counter, "Number of errors encountered while truncating an answer")},
  { "no-policy",                             MetricDefinition(PrometheusMetricType::counter, "Number of queries dropped because no server was available")},
  { "latency0-1",                            MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in less than 1ms")},
  { "latency1-10",                           MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in 1-10 ms")},
  { "latency10-50",                          MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in 10-50 ms")},
  { "latency50-100",                         MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in 50-100 ms")},
  { "latency100-1000",                       MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in 100-1000 ms")},
  { "latency-slow",                          MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in more than 1 second")},
  { "latency-avg100",                        MetricDefinition(PrometheusMetricType::gauge,   "Average response latency in microseconds of the last 100 packets")},
  { "latency-avg1000",                       MetricDefinition(PrometheusMetricType::gauge,   "Average response latency in microseconds of the last 1000 packets")},
  { "latency-avg10000",                      MetricDefinition(PrometheusMetricType::gauge,   "Average response latency in microseconds of the last 10000 packets")},
  { "latency-avg1000000",                    MetricDefinition(PrometheusMetricType::gauge,   "Average response latency in microseconds of the last 1000000 packets")},
  { "latency-tcp-avg100",                    MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 100 packets received over TCP")},
  { "latency-tcp-avg1000",                   MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 1000 packets received over TCP")},
  { "latency-tcp-avg10000",                  MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 10000 packets received over TCP")},
  { "latency-tcp-avg1000000",                MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 1000000 packets received over TCP")},
  { "latency-dot-avg100",                    MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 100 packets received over DoT")},
  { "latency-dot-avg1000",                   MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 1000 packets received over DoT")},
  { "latency-dot-avg10000",                  MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 10000 packets received over DoT")},
  { "latency-dot-avg1000000",                MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 1000000 packets received over DoT")},
  { "latency-doh-avg100",                    MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 100 packets received over DoH")},
  { "latency-doh-avg1000",                   MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 1000 packets received over DoH")},
  { "latency-doh-avg10000",                  MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 10000 packets received over DoH")},
  { "latency-doh-avg1000000",                MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 1000000 packets received over DoH")},
  { "latency-doq-avg100",                    MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 100 packets received over DoQ")},
  { "latency-doq-avg1000",                   MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 1000 packets received over DoQ")},
  { "latency-doq-avg10000",                  MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 10000 packets received over DoQ")},
  { "latency-doq-avg1000000",                MetricDefinition(PrometheusMetricType::gauge,   "Average response latency, in microseconds, of the last 1000000 packets received over DoQ")},
  { "uptime",                                MetricDefinition(PrometheusMetricType::gauge,   "Uptime of the dnsdist process in seconds")},
  { "real-memory-usage",                     MetricDefinition(PrometheusMetricType::gauge,   "Current memory usage in bytes")},
  { "noncompliant-queries",                  MetricDefinition(PrometheusMetricType::counter, "Number of queries dropped as non-compliant")},
  { "noncompliant-responses",                MetricDefinition(PrometheusMetricType::counter, "Number of answers from a backend dropped as non-compliant")},
  { "rdqueries",                             MetricDefinition(PrometheusMetricType::counter, "Number of received queries with the recursion desired bit set")},
  { "empty-queries",                         MetricDefinition(PrometheusMetricType::counter, "Number of empty queries received from clients")},
  { "cache-hits",                            MetricDefinition(PrometheusMetricType::counter, "Number of times an answer was retrieved from cache")},
  { "cache-misses",                          MetricDefinition(PrometheusMetricType::counter, "Number of times an answer not found in the cache")},
  { "cpu-iowait",                            MetricDefinition(PrometheusMetricType::counter, "Time waiting for I/O to complete by the whole system, in units of USER_HZ")},
  { "cpu-user-msec",                         MetricDefinition(PrometheusMetricType::counter, "Milliseconds spent by dnsdist in the user state")},
  { "cpu-steal",                             MetricDefinition(PrometheusMetricType::counter, "Stolen time, which is the time spent by the whole system in other operating systems when running in a virtualized environment, in units of USER_HZ")},
  { "cpu-sys-msec",                          MetricDefinition(PrometheusMetricType::counter, "Milliseconds spent by dnsdist in the system state")},
  { "fd-usage",                              MetricDefinition(PrometheusMetricType::gauge,   "Number of currently used file descriptors")},
  { "dyn-blocked",                           MetricDefinition(PrometheusMetricType::counter, "Number of queries dropped because of a dynamic block")},
  { "dyn-block-nmg-size",                    MetricDefinition(PrometheusMetricType::gauge,   "Number of dynamic blocks entries") },
  { "security-status",                       MetricDefinition(PrometheusMetricType::gauge,   "Security status of this software. 0=unknown, 1=OK, 2=upgrade recommended, 3=upgrade mandatory") },
  { "doh-query-pipe-full",                   MetricDefinition(PrometheusMetricType::counter, "Number of DoH queries dropped because the internal pipe used to distribute queries was full") },
  { "doh-response-pipe-full",                MetricDefinition(PrometheusMetricType::counter, "Number of DoH responses dropped because the internal pipe used to distribute responses was full") },
  { "outgoing-doh-query-pipe-full",          MetricDefinition(PrometheusMetricType::counter, "Number of outgoing DoH queries dropped because the internal pipe used to distribute queries was full") },
  { "tcp-query-pipe-full",                   MetricDefinition(PrometheusMetricType::counter, "Number of TCP queries dropped because the internal pipe used to distribute queries was full") },
  { "tcp-cross-protocol-query-pipe-full",    MetricDefinition(PrometheusMetricType::counter, "Number of TCP cross-protocol queries dropped because the internal pipe used to distribute queries was full") },
  { "tcp-cross-protocol-response-pipe-full", MetricDefinition(PrometheusMetricType::counter, "Number of TCP cross-protocol responses dropped because the internal pipe used to distribute queries was full") },
  { "udp-in-errors",                         MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp InErrors") },
  { "udp-noport-errors",                     MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp NoPorts") },
  { "udp-recvbuf-errors",                    MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp RcvbufErrors") },
  { "udp-sndbuf-errors",                     MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp SndbufErrors") },
  { "udp-in-csum-errors",                    MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp InCsumErrors") },
  { "udp6-in-errors",                        MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp6 Udp6InErrors") },
  { "udp6-recvbuf-errors",                   MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp6 Udp6RcvbufErrors") },
  { "udp6-sndbuf-errors",                    MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp6 Udp6SndbufErrors") },
  { "udp6-noport-errors",                    MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp6 Udp6NoPorts") },
  { "udp6-in-csum-errors",                   MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp6 Udp6InCsumErrors") },
  { "tcp-listen-overflows",                  MetricDefinition(PrometheusMetricType::counter, "From /proc/net/netstat ListenOverflows") },
  { "proxy-protocol-invalid",                MetricDefinition(PrometheusMetricType::counter, "Number of queries dropped because of an invalid Proxy Protocol header") },
};
#endif /* DISABLE_PROMETHEUS */

bool addMetricDefinition(const dnsdist::prometheus::PrometheusMetricDefinition& def) {
#ifndef DISABLE_PROMETHEUS
  return MetricDefinitionStorage::addMetricDefinition(def);
#else
  return true;
#endif /* DISABLE_PROMETHEUS */
}

#ifndef DISABLE_WEB_CONFIG
static bool apiWriteConfigFile(const string& filebasename, const string& content)
{
  if (!g_apiReadWrite) {
    warnlog("Not writing content to %s since the API is read-only", filebasename);
    return false;
  }

  if (g_apiConfigDirectory.empty()) {
    vinfolog("Not writing content to %s since the API configuration directory is not set", filebasename);
    return false;
  }

  string filename = g_apiConfigDirectory + "/" + filebasename + ".conf";
  ofstream ofconf(filename.c_str());
  if (!ofconf) {
    errlog("Could not open configuration fragment file '%s' for writing: %s", filename, stringerror());
    return false;
  }
  ofconf << "-- Generated by the REST API, DO NOT EDIT" << endl;
  ofconf << content << endl;
  ofconf.close();
  return true;
}

static void apiSaveACL(const NetmaskGroup& nmg)
{
  auto aclEntries = nmg.toStringVector();

  string acl;
  for (const auto& entry : aclEntries) {
    if (!acl.empty()) {
      acl += ", ";
    }
    acl += "\"" + entry + "\"";
  }

  string content = "setACL({" + acl + "})";
  apiWriteConfigFile("acl", content);
}
#endif /* DISABLE_WEB_CONFIG */

static bool checkAPIKey(const YaHTTP::Request& req, const std::unique_ptr<CredentialsHolder>& apiKey)
{
  if (!apiKey) {
    return false;
  }

  const auto header = req.headers.find("x-api-key");
  if (header != req.headers.end()) {
    return apiKey->matches(header->second);
  }

  return false;
}

static bool checkWebPassword(const YaHTTP::Request& req, const std::unique_ptr<CredentialsHolder>& password, bool dashboardRequiresAuthentication)
{
  if (!dashboardRequiresAuthentication) {
    return true;
  }

  static const char basicStr[] = "basic ";

  const auto header = req.headers.find("authorization");

  if (header != req.headers.end() && toLower(header->second).find(basicStr) == 0) {
    string cookie = header->second.substr(sizeof(basicStr) - 1);

    string plain;
    B64Decode(cookie, plain);

    vector<string> cparts;
    stringtok(cparts, plain, ":");

    if (cparts.size() == 2) {
      if (password) {
        return password->matches(cparts.at(1));
      }
      return true;
    }
  }

  return false;
}

static bool isAnAPIRequest(const YaHTTP::Request& req)
{
  return req.url.path.find("/api/") == 0;
}

static bool isAnAPIRequestAllowedWithWebAuth(const YaHTTP::Request& req)
{
  return req.url.path == "/api/v1/servers/localhost";
}

static bool isAStatsRequest(const YaHTTP::Request& req)
{
  return req.url.path == "/jsonstat" || req.url.path == "/metrics";
}

static bool handleAuthorization(const YaHTTP::Request& req)
{
  auto config = g_webserverConfig.lock();

  if (isAStatsRequest(req)) {
    if (config->statsRequireAuthentication) {
      /* Access to the stats is allowed for both API and Web users */
      return checkAPIKey(req, config->apiKey) || checkWebPassword(req, config->password, config->dashboardRequiresAuthentication);
    }
    return true;
  }

  if (isAnAPIRequest(req)) {
    /* Access to the API requires a valid API key */
    if (!config->apiRequiresAuthentication  || checkAPIKey(req, config->apiKey)) {
      return true;
    }

    return isAnAPIRequestAllowedWithWebAuth(req) && checkWebPassword(req, config->password, config->dashboardRequiresAuthentication);
  }

  return checkWebPassword(req, config->password, config->dashboardRequiresAuthentication);
}

static bool isMethodAllowed(const YaHTTP::Request& req)
{
  if (req.method == "GET") {
    return true;
  }
  if (req.method == "PUT" && g_apiReadWrite) {
    if (req.url.path == "/api/v1/servers/localhost/config/allow-from") {
      return true;
    }
  }
#ifndef DISABLE_WEB_CACHE_MANAGEMENT
  if (req.method == "DELETE") {
    if (req.url.path == "/api/v1/cache") {
      return true;
    }
  }
#endif /* DISABLE_WEB_CACHE_MANAGEMENT */
  return false;
}

static bool isClientAllowedByACL(const ComboAddress& remote)
{
  return g_webserverConfig.lock()->acl.match(remote);
}

static void handleCORS(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  const auto origin = req.headers.find("Origin");
  if (origin != req.headers.end()) {
    if (req.method == "OPTIONS") {
      /* Pre-flight request */
      if (g_apiReadWrite) {
        resp.headers["Access-Control-Allow-Methods"] = "GET, PUT";
      }
      else {
        resp.headers["Access-Control-Allow-Methods"] = "GET";
      }
      resp.headers["Access-Control-Allow-Headers"] = "Authorization, X-API-Key";
    }

    resp.headers["Access-Control-Allow-Origin"] = origin->second;

    if (isAStatsRequest(req) || isAnAPIRequestAllowedWithWebAuth(req)) {
      resp.headers["Access-Control-Allow-Credentials"] = "true";
    }
  }
}

static void addSecurityHeaders(YaHTTP::Response& resp, const boost::optional<std::unordered_map<std::string, std::string> >& customHeaders)
{
  static const std::vector<std::pair<std::string, std::string> > headers = {
    { "X-Content-Type-Options", "nosniff" },
    { "X-Frame-Options", "deny" },
    { "X-Permitted-Cross-Domain-Policies", "none" },
    { "X-XSS-Protection", "1; mode=block" },
    { "Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'" },
  };

  for (const auto& h : headers) {
    if (customHeaders) {
      const auto& custom = customHeaders->find(h.first);
      if (custom != customHeaders->end()) {
        continue;
      }
    }
    resp.headers[h.first] = h.second;
  }
}

static void addCustomHeaders(YaHTTP::Response& resp, const boost::optional<std::unordered_map<std::string, std::string> >& customHeaders)
{
  if (!customHeaders)
    return;

  for (const auto& c : *customHeaders) {
    if (!c.second.empty()) {
      resp.headers[c.first] = c.second;
    }
  }
}

template<typename T>
static json11::Json::array someResponseRulesToJson(GlobalStateHolder<vector<T>>* someResponseRules)
{
  using namespace json11;
  Json::array responseRules;
  int num=0;
  auto localResponseRules = someResponseRules->getLocal();
  responseRules.reserve(localResponseRules->size());
  for (const auto& a : *localResponseRules) {
    responseRules.push_back(Json::object{
        {"id", num++},
        {"creationOrder", (double)a.d_creationOrder},
        {"uuid", boost::uuids::to_string(a.d_id)},
        {"name", a.d_name},
        {"matches", (double)a.d_rule->d_matches},
        {"rule", a.d_rule->toString()},
        {"action", a.d_action->toString()},
      });
  }
  return responseRules;
}

#ifndef DISABLE_PROMETHEUS
template<typename T>
static void addRulesToPrometheusOutput(std::ostringstream& output, GlobalStateHolder<vector<T> >& rules)
{
  auto localRules = rules.getLocal();
  for (const auto& entry : *localRules) {
    std::string id = !entry.d_name.empty() ? entry.d_name : boost::uuids::to_string(entry.d_id);
    output << "dnsdist_rule_hits{id=\"" << id << "\"} " << entry.d_rule->d_matches << "\n";
  }
}

static void handlePrometheus(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  handleCORS(req, resp);
  resp.status = 200;

  std::ostringstream output;
  static const std::set<std::string> metricBlacklist = { "special-memory-usage", "latency-count", "latency-sum" };
  {
    auto entries = dnsdist::metrics::g_stats.entries.read_lock();
    std::unordered_set<std::string> helpAndTypeSent;
    for (const auto& entry : *entries) {
      const auto& metricName = entry.d_name;

      if (metricBlacklist.count(metricName) != 0) {
        continue;
      }

      MetricDefinition metricDetails;
      if (!s_metricDefinitions.getMetricDetails(metricName, metricDetails)) {
        vinfolog("Do not have metric details for %s", metricName);
        continue;
      }

      const std::string prometheusTypeName = s_metricDefinitions.getPrometheusStringMetricType(metricDetails.prometheusType);
      if (prometheusTypeName.empty()) {
        vinfolog("Unknown Prometheus type for %s", metricName);
        continue;
      }

      // Prometheus suggest using '_' instead of '-'
      std::string prometheusMetricName;
      if (metricDetails.customName.empty()) {
        prometheusMetricName = "dnsdist_" + boost::replace_all_copy(metricName, "-", "_");
      }
      else {
        prometheusMetricName = metricDetails.customName;
      }

      // for these we have the help and types encoded in the sources
      // but we need to be careful about labels in custom metrics
      std::string helpName = prometheusMetricName.substr(0, prometheusMetricName.find('{'));
      if (helpAndTypeSent.count(helpName) == 0) {
        helpAndTypeSent.insert(helpName);
        output << "# HELP " << helpName << " " << metricDetails.description << "\n";
        output << "# TYPE " << helpName << " " << prometheusTypeName << "\n";
      }
      output << prometheusMetricName << " ";

      if (const auto& val = std::get_if<pdns::stat_t*>(&entry.d_value)) {
        output << (*val)->load();
      }
      else if (const auto& adval = std::get_if<pdns::stat_t_trait<double>*>(&entry.d_value)) {
        output << (*adval)->load();
      }
      else if (const auto& dval = std::get_if<double*>(&entry.d_value)) {
        output << **dval;
      }
      else if (const auto& func = std::get_if<dnsdist::metrics::Stats::statfunction_t>(&entry.d_value)) {
        output << (*func)(entry.d_name);
      }

      output << "\n";
    }
  }

  // Latency histogram buckets
  output << "# HELP dnsdist_latency Histogram of responses by latency (in milliseconds)\n";
  output << "# TYPE dnsdist_latency histogram\n";
  uint64_t latency_amounts = dnsdist::metrics::g_stats.latency0_1;
  output << "dnsdist_latency_bucket{le=\"1\"} " << latency_amounts << "\n";
  latency_amounts += dnsdist::metrics::g_stats.latency1_10;
  output << "dnsdist_latency_bucket{le=\"10\"} " << latency_amounts << "\n";
  latency_amounts += dnsdist::metrics::g_stats.latency10_50;
  output << "dnsdist_latency_bucket{le=\"50\"} " << latency_amounts << "\n";
  latency_amounts += dnsdist::metrics::g_stats.latency50_100;
  output << "dnsdist_latency_bucket{le=\"100\"} " << latency_amounts << "\n";
  latency_amounts += dnsdist::metrics::g_stats.latency100_1000;
  output << "dnsdist_latency_bucket{le=\"1000\"} " << latency_amounts << "\n";
  latency_amounts += dnsdist::metrics::g_stats.latencySlow; // Should be the same as latency_count
  output << "dnsdist_latency_bucket{le=\"+Inf\"} " << latency_amounts << "\n";
  output << "dnsdist_latency_sum " << dnsdist::metrics::g_stats.latencySum << "\n";
  output << "dnsdist_latency_count " << dnsdist::metrics::g_stats.latencyCount << "\n";

  auto states = g_dstates.getLocal();
  const string statesbase = "dnsdist_server_";

  output << "# HELP " << statesbase << "status "                          << "Whether this backend is up (1) or down (0)"                                           << "\n";
  output << "# TYPE " << statesbase << "status "                          << "gauge"                                                                                << "\n";
  output << "# HELP " << statesbase << "queries "                         << "Amount of queries relayed to server"                                                  << "\n";
  output << "# TYPE " << statesbase << "queries "                         << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "responses "                       << "Amount of responses received from this server"                                        << "\n";
  output << "# TYPE " << statesbase << "responses "                       << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "noncompliantresponses "           << "Amount of non-compliant responses received from this server"                          << "\n";
  output << "# TYPE " << statesbase << "noncompliantresponses "           << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "drops "                           << "Amount of queries not answered by server"                                             << "\n";
  output << "# TYPE " << statesbase << "drops "                           << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "latency "                         << "Server's latency when answering questions in milliseconds"                            << "\n";
  output << "# TYPE " << statesbase << "latency "                         << "gauge"                                                                                << "\n";
  output << "# HELP " << statesbase << "senderrors "                      << "Total number of OS send errors while relaying queries"                                << "\n";
  output << "# TYPE " << statesbase << "senderrors "                      << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "outstanding "                     << "Current number of queries that are waiting for a backend response"                    << "\n";
  output << "# TYPE " << statesbase << "outstanding "                     << "gauge"                                                                                << "\n";
  output << "# HELP " << statesbase << "order "                           << "The order in which this server is picked"                                             << "\n";
  output << "# TYPE " << statesbase << "order "                           << "gauge"                                                                                << "\n";
  output << "# HELP " << statesbase << "weight "                          << "The weight within the order in which this server is picked"                           << "\n";
  output << "# TYPE " << statesbase << "weight "                          << "gauge"                                                                                << "\n";
  output << "# HELP " << statesbase << "tcpdiedsendingquery "             << "The number of TCP I/O errors while sending the query"                                 << "\n";
  output << "# TYPE " << statesbase << "tcpdiedsendingquery "             << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "tcpdiedreadingresponse "          << "The number of TCP I/O errors while reading the response"                              << "\n";
  output << "# TYPE " << statesbase << "tcpdiedreadingresponse "          << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "tcpgaveup "                       << "The number of TCP connections failing after too many attempts"                        << "\n";
  output << "# TYPE " << statesbase << "tcpgaveup "                       << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "tcpconnecttimeouts "              << "The number of TCP connect timeouts"                                                   << "\n";
  output << "# TYPE " << statesbase << "tcpconnecttimeouts "              << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "tcpreadtimeouts "                 << "The number of TCP read timeouts"                                                      << "\n";
  output << "# TYPE " << statesbase << "tcpreadtimeouts "                 << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "tcpwritetimeouts "                << "The number of TCP write timeouts"                                                     << "\n";
  output << "# TYPE " << statesbase << "tcpwritetimeouts "                << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "tcpcurrentconnections "           << "The number of current TCP connections"                                                << "\n";
  output << "# TYPE " << statesbase << "tcpcurrentconnections "           << "gauge"                                                                                << "\n";
  output << "# HELP " << statesbase << "tcpmaxconcurrentconnections "     << "The maximum number of concurrent TCP connections"                                     << "\n";
  output << "# TYPE " << statesbase << "tcpmaxconcurrentconnections "     << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "tcptoomanyconcurrentconnections " << "Number of times we had to enforce the maximum number of concurrent TCP connections"   << "\n";
  output << "# TYPE " << statesbase << "tcptoomanyconcurrentconnections " << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "tcpnewconnections "               << "The number of established TCP connections in total"                                   << "\n";
  output << "# TYPE " << statesbase << "tcpnewconnections "               << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "tcpreusedconnections "            << "The number of times a TCP connection has been reused"                                 << "\n";
  output << "# TYPE " << statesbase << "tcpreusedconnections "            << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "tcpavgqueriesperconn "            << "The average number of queries per TCP connection"                                     << "\n";
  output << "# TYPE " << statesbase << "tcpavgqueriesperconn "            << "gauge"                                                                                << "\n";
  output << "# HELP " << statesbase << "tcpavgconnduration "              << "The average duration of a TCP connection (ms)"                                        << "\n";
  output << "# TYPE " << statesbase << "tcpavgconnduration "              << "gauge"                                                                                << "\n";
  output << "# HELP " << statesbase << "tlsresumptions "                  << "The number of times a TLS session has been resumed"                                   << "\n";
  output << "# TYPE " << statesbase << "tlsresumptions "                  << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "tcplatency "                      << "Server's latency when answering TCP questions in milliseconds"                        << "\n";
  output << "# TYPE " << statesbase << "tcplatency "                      << "gauge"                                                                                << "\n";
  output << "# HELP " << statesbase << "healthcheckfailures "             << "Number of health check attempts that failed (total)"                                  << "\n";
  output << "# TYPE " << statesbase << "healthcheckfailures "             << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "healthcheckfailuresparsing "      << "Number of health check attempts where the response could not be parsed"               << "\n";
  output << "# TYPE " << statesbase << "healthcheckfailuresparsing "      << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "healthcheckfailurestimeout "      << "Number of health check attempts where the response did not arrive in time"            << "\n";
  output << "# TYPE " << statesbase << "healthcheckfailurestimeout "      << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "healthcheckfailuresnetwork "      << "Number of health check attempts that experienced a network issue"                     << "\n";
  output << "# TYPE " << statesbase << "healthcheckfailuresnetwork "      << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "healthcheckfailuresmismatch "     << "Number of health check attempts where the response did not match the query"           << "\n";
  output << "# TYPE " << statesbase << "healthcheckfailuresmismatch "     << "counter"                                                                              << "\n";
  output << "# HELP " << statesbase << "healthcheckfailuresinvalid "      << "Number of health check attempts where the DNS response was invalid"                   << "\n";
  output << "# TYPE " << statesbase << "healthcheckfailuresinvalid "      << "counter"                                                                              << "\n";

  for (const auto& state : *states) {
    string serverName;

    if (state->getName().empty()) {
      serverName = state->d_config.remote.toStringWithPort();
    }
    else {
      serverName = state->getName();
    }

    boost::replace_all(serverName, ".", "_");

    const std::string label = boost::str(boost::format("{server=\"%1%\",address=\"%2%\"}")
                                         % serverName % state->d_config.remote.toStringWithPort());

    output << statesbase << "status"                           << label << " " << (state->isUp() ? "1" : "0")            << "\n";
    output << statesbase << "queries"                          << label << " " << state->queries.load()                  << "\n";
    output << statesbase << "responses"                        << label << " " << state->responses.load()                << "\n";
    output << statesbase << "noncompliantresponses"            << label << " " << state->nonCompliantResponses.load()    << "\n";
    output << statesbase << "drops"                            << label << " " << state->reuseds.load()                  << "\n";
    if (state->isUp()) {
      output << statesbase << "latency"                        << label << " " << state->latencyUsec/1000.0              << "\n";
      output << statesbase << "tcplatency"                     << label << " " << state->latencyUsecTCP/1000.0           << "\n";
    }
    output << statesbase << "senderrors"                       << label << " " << state->sendErrors.load()               << "\n";
    output << statesbase << "outstanding"                      << label << " " << state->outstanding.load()              << "\n";
    output << statesbase << "order"                            << label << " " << state->d_config.order                  << "\n";
    output << statesbase << "weight"                           << label << " " << state->d_config.d_weight               << "\n";
    output << statesbase << "tcpdiedsendingquery"              << label << " " << state->tcpDiedSendingQuery             << "\n";
    output << statesbase << "tcpdiedreadingresponse"           << label << " " << state->tcpDiedReadingResponse          << "\n";
    output << statesbase << "tcpgaveup"                        << label << " " << state->tcpGaveUp                       << "\n";
    output << statesbase << "tcpreadtimeouts"                  << label << " " << state->tcpReadTimeouts                 << "\n";
    output << statesbase << "tcpwritetimeouts"                 << label << " " << state->tcpWriteTimeouts                << "\n";
    output << statesbase << "tcpconnecttimeouts"               << label << " " << state->tcpConnectTimeouts              << "\n";
    output << statesbase << "tcpcurrentconnections"            << label << " " << state->tcpCurrentConnections           << "\n";
    output << statesbase << "tcpmaxconcurrentconnections"      << label << " " << state->tcpMaxConcurrentConnections     << "\n";
    output << statesbase << "tcptoomanyconcurrentconnections"  << label << " " << state->tcpTooManyConcurrentConnections << "\n";
    output << statesbase << "tcpnewconnections"                << label << " " << state->tcpNewConnections               << "\n";
    output << statesbase << "tcpreusedconnections"             << label << " " << state->tcpReusedConnections            << "\n";
    output << statesbase << "tcpavgqueriesperconn"             << label << " " << state->tcpAvgQueriesPerConnection      << "\n";
    output << statesbase << "tcpavgconnduration"               << label << " " << state->tcpAvgConnectionDuration        << "\n";
    output << statesbase << "tlsresumptions"                   << label << " " << state->tlsResumptions                  << "\n";
    output << statesbase << "healthcheckfailures"              << label << " " << state->d_healthCheckMetrics.d_failures << "\n";
    output << statesbase << "healthcheckfailuresparsing"       << label << " " << state->d_healthCheckMetrics.d_parseErrors << "\n";
    output << statesbase << "healthcheckfailurestimeout"       << label << " " << state->d_healthCheckMetrics.d_timeOuts << "\n";
    output << statesbase << "healthcheckfailuresnetwork"       << label << " " << state->d_healthCheckMetrics.d_networkErrors << "\n";
    output << statesbase << "healthcheckfailuresmismatch"      << label << " " << state->d_healthCheckMetrics.d_mismatchErrors << "\n";
    output << statesbase << "healthcheckfailuresinvalid"        << label << " " << state->d_healthCheckMetrics.d_invalidResponseErrors << "\n";
  }

  const string frontsbase = "dnsdist_frontend_";
  output << "# HELP " << frontsbase << "queries " << "Amount of queries received by this frontend" << "\n";
  output << "# TYPE " << frontsbase << "queries " << "counter" << "\n";
  output << "# HELP " << frontsbase << "noncompliantqueries " << "Amount of non-compliant queries received by this frontend" << "\n";
  output << "# TYPE " << frontsbase << "noncompliantqueries " << "counter" << "\n";
  output << "# HELP " << frontsbase << "responses " << "Amount of responses sent by this frontend" << "\n";
  output << "# TYPE " << frontsbase << "responses " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tcpdiedreadingquery " << "Amount of TCP connections terminated while reading the query from the client" << "\n";
  output << "# TYPE " << frontsbase << "tcpdiedreadingquery " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tcpdiedsendingresponse " << "Amount of TCP connections terminated while sending a response to the client" << "\n";
  output << "# TYPE " << frontsbase << "tcpdiedsendingresponse " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tcpgaveup " << "Amount of TCP connections terminated after too many attempts to get a connection to the backend" << "\n";
  output << "# TYPE " << frontsbase << "tcpgaveup " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tcpclienttimeouts " << "Amount of TCP connections terminated by a timeout while reading from the client" << "\n";
  output << "# TYPE " << frontsbase << "tcpclienttimeouts " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tcpdownstreamtimeouts " << "Amount of TCP connections terminated by a timeout while reading from the backend" << "\n";
  output << "# TYPE " << frontsbase << "tcpdownstreamtimeouts " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tcpcurrentconnections " << "Amount of current incoming TCP connections from clients" << "\n";
  output << "# TYPE " << frontsbase << "tcpcurrentconnections " << "gauge" << "\n";
  output << "# HELP " << frontsbase << "tcpmaxconcurrentconnections " << "Maximum number of concurrent incoming TCP connections from clients" << "\n";
  output << "# TYPE " << frontsbase << "tcpmaxconcurrentconnections " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tcpavgqueriesperconnection " << "The average number of queries per TCP connection" << "\n";
  output << "# TYPE " << frontsbase << "tcpavgqueriesperconnection " << "gauge" << "\n";
  output << "# HELP " << frontsbase << "tcpavgconnectionduration " << "The average duration of a TCP connection (ms)" << "\n";
  output << "# TYPE " << frontsbase << "tcpavgconnectionduration " << "gauge" << "\n";
  output << "# HELP " << frontsbase << "tlsqueries " << "Number of queries received by dnsdist over TLS, by TLS version" << "\n";
  output << "# TYPE " << frontsbase << "tlsqueries " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tlsnewsessions " << "Amount of new TLS sessions negotiated" << "\n";
  output << "# TYPE " << frontsbase << "tlsnewsessions " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tlsresumptions " << "Amount of TLS sessions resumed" << "\n";
  output << "# TYPE " << frontsbase << "tlsresumptions " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tlsunknownticketkeys " << "Amount of attempts to resume TLS session from an unknown key (possibly expired)" << "\n";
  output << "# TYPE " << frontsbase << "tlsunknownticketkeys " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tlsinactiveticketkeys " << "Amount of TLS sessions resumed from an inactive key" << "\n";
  output << "# TYPE " << frontsbase << "tlsinactiveticketkeys " << "counter" << "\n";
  output << "# HELP " << frontsbase << "tlshandshakefailures " << "Amount of TLS handshake failures" << "\n";
  output << "# TYPE " << frontsbase << "tlshandshakefailures " << "counter" << "\n";

  std::map<std::string,uint64_t> frontendDuplicates;
  for (const auto& front : g_frontends) {
    if (front->udpFD == -1 && front->tcpFD == -1)
      continue;

    const string frontName = front->local.toStringWithPort();
    const string proto = front->getType();
    const string fullName = frontName + "_" + proto;
    uint64_t threadNumber = 0;
    auto dupPair = frontendDuplicates.emplace(fullName, 1);
    if (!dupPair.second) {
      threadNumber = dupPair.first->second;
      ++(dupPair.first->second);
    }
    const std::string label = boost::str(boost::format("{frontend=\"%1%\",proto=\"%2%\",thread=\"%3%\"} ")
                                         % frontName % proto % threadNumber);

    output << frontsbase << "queries" << label << front->queries.load() << "\n";
    output << frontsbase << "noncompliantqueries" << label << front->nonCompliantQueries.load() << "\n";
    output << frontsbase << "responses" << label << front->responses.load() << "\n";
    if (front->isTCP()) {
      output << frontsbase << "tcpdiedreadingquery" << label << front->tcpDiedReadingQuery.load() << "\n";
      output << frontsbase << "tcpdiedsendingresponse" << label << front->tcpDiedSendingResponse.load() << "\n";
      output << frontsbase << "tcpgaveup" << label << front->tcpGaveUp.load() << "\n";
      output << frontsbase << "tcpclienttimeouts" << label << front->tcpClientTimeouts.load() << "\n";
      output << frontsbase << "tcpdownstreamtimeouts" << label << front->tcpDownstreamTimeouts.load() << "\n";
      output << frontsbase << "tcpcurrentconnections" << label << front->tcpCurrentConnections.load() << "\n";
      output << frontsbase << "tcpmaxconcurrentconnections" << label << front->tcpMaxConcurrentConnections.load() << "\n";
      output << frontsbase << "tcpavgqueriesperconnection" << label << front->tcpAvgQueriesPerConnection.load() << "\n";
      output << frontsbase << "tcpavgconnectionduration" << label << front->tcpAvgConnectionDuration.load() << "\n";
      if (front->hasTLS()) {
        output << frontsbase << "tlsnewsessions" << label << front->tlsNewSessions.load() << "\n";
        output << frontsbase << "tlsresumptions" << label << front->tlsResumptions.load() << "\n";
        output << frontsbase << "tlsunknownticketkeys" << label << front->tlsUnknownTicketKey.load() << "\n";
        output << frontsbase << "tlsinactiveticketkeys" << label << front->tlsInactiveTicketKey.load() << "\n";

        output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",tls=\"tls10\"} " << front->tls10queries.load() << "\n";
        output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",tls=\"tls11\"} " << front->tls11queries.load() << "\n";
        output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",tls=\"tls12\"} " << front->tls12queries.load() << "\n";
        output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",tls=\"tls13\"} " << front->tls13queries.load() << "\n";
        output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",tls=\"unknown\"} " << front->tlsUnknownqueries.load() << "\n";

        const TLSErrorCounters* errorCounters = nullptr;
        if (front->tlsFrontend != nullptr) {
          errorCounters = &front->tlsFrontend->d_tlsCounters;
        }
        else if (front->dohFrontend != nullptr) {
          errorCounters = &front->dohFrontend->d_tlsContext.d_tlsCounters;
        }

        if (errorCounters != nullptr) {
          output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"dhKeyTooSmall\"} " << errorCounters->d_dhKeyTooSmall << "\n";
          output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"inappropriateFallBack\"} " << errorCounters->d_inappropriateFallBack << "\n";
          output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"noSharedCipher\"} " << errorCounters->d_noSharedCipher << "\n";
          output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"unknownCipherType\"} " << errorCounters->d_unknownCipherType << "\n";
          output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"unknownKeyExchangeType\"} " << errorCounters->d_unknownKeyExchangeType << "\n";
          output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"unknownProtocol\"} " << errorCounters->d_unknownProtocol << "\n";
          output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"unsupportedEC\"} " << errorCounters->d_unsupportedEC << "\n";
          output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"unsupportedProtocol\"} " << errorCounters->d_unsupportedProtocol << "\n";
        }
      }
    }
  }

  output << "# HELP " << frontsbase << "http_connects " << "Number of DoH TCP connections established to this frontend" << "\n";
  output << "# TYPE " << frontsbase << "http_connects " << "counter" << "\n";

  output << "# HELP " << frontsbase << "doh_http_method_queries " << "Number of DoH queries received by dnsdist, by HTTP method" << "\n";
  output << "# TYPE " << frontsbase << "doh_http_method_queries " << "counter" << "\n";

  output << "# HELP " << frontsbase << "doh_http_version_queries " << "Number of DoH queries received by dnsdist, by HTTP version" << "\n";
  output << "# TYPE " << frontsbase << "doh_http_version_queries " << "counter" << "\n";

  output << "# HELP " << frontsbase << "doh_bad_requests " << "Number of requests that could not be converted to a DNS query" << "\n";
  output << "# TYPE " << frontsbase << "doh_bad_requests " << "counter" << "\n";

  output << "# HELP " << frontsbase << "doh_responses " << "Number of responses sent, by type" << "\n";
  output << "# TYPE " << frontsbase << "doh_responses " << "counter" << "\n";

  output << "# HELP " << frontsbase << "doh_version_status_responses " << "Number of requests that could not be converted to a DNS query" << "\n";
  output << "# TYPE " << frontsbase << "doh_version_status_responses " << "counter" << "\n";

#ifdef HAVE_DNS_OVER_HTTPS
  std::map<std::string,uint64_t> dohFrontendDuplicates;
  for(const auto& doh : g_dohlocals) {
    const string frontName = doh->d_tlsContext.d_addr.toStringWithPort();
    uint64_t threadNumber = 0;
    auto dupPair = frontendDuplicates.emplace(frontName, 1);
    if (!dupPair.second) {
      threadNumber = dupPair.first->second;
      ++(dupPair.first->second);
    }
    const std::string addrlabel = boost::str(boost::format("frontend=\"%1%\",thread=\"%2%\"") % frontName % threadNumber);
    const std::string label = "{" + addrlabel + "} ";

    output << frontsbase << "http_connects" << label << doh->d_httpconnects << "\n";
    output << frontsbase << "doh_http_method_queries{method=\"get\"," << addrlabel << "} " << doh->d_getqueries << "\n";
    output << frontsbase << "doh_http_method_queries{method=\"post\"," << addrlabel << "} " << doh->d_postqueries << "\n";

    output << frontsbase << "doh_http_version_queries{version=\"1\"," << addrlabel << "} " << doh->d_http1Stats.d_nbQueries << "\n";
    output << frontsbase << "doh_http_version_queries{version=\"2\"," << addrlabel << "} " << doh->d_http2Stats.d_nbQueries << "\n";

    output << frontsbase << "doh_bad_requests{" << addrlabel << "} " << doh->d_badrequests << "\n";

    output << frontsbase << "doh_responses{type=\"error\"," << addrlabel << "} " << doh->d_errorresponses << "\n";
    output << frontsbase << "doh_responses{type=\"redirect\"," << addrlabel << "} " << doh->d_redirectresponses << "\n";
    output << frontsbase << "doh_responses{type=\"valid\"," << addrlabel << "} " << doh->d_validresponses << "\n";

    output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"200\"," << addrlabel << "} " << doh->d_http1Stats.d_nb200Responses << "\n";
    output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"400\"," << addrlabel << "} " << doh->d_http1Stats.d_nb400Responses << "\n";
    output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"403\"," << addrlabel << "} " << doh->d_http1Stats.d_nb403Responses << "\n";
    output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"500\"," << addrlabel << "} " << doh->d_http1Stats.d_nb500Responses << "\n";
    output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"502\"," << addrlabel << "} " << doh->d_http1Stats.d_nb502Responses << "\n";
    output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"other\"," << addrlabel << "} " << doh->d_http1Stats.d_nbOtherResponses << "\n";
    output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"200\"," << addrlabel << "} " << doh->d_http2Stats.d_nb200Responses << "\n";
    output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"400\"," << addrlabel << "} " << doh->d_http2Stats.d_nb400Responses << "\n";
    output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"403\"," << addrlabel << "} " << doh->d_http2Stats.d_nb403Responses << "\n";
    output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"500\"," << addrlabel << "} " << doh->d_http2Stats.d_nb500Responses << "\n";
    output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"502\"," << addrlabel << "} " << doh->d_http2Stats.d_nb502Responses << "\n";
    output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"other\"," << addrlabel << "} " << doh->d_http2Stats.d_nbOtherResponses << "\n";
  }
#endif /* HAVE_DNS_OVER_HTTPS */

  auto localPools = g_pools.getLocal();
  const string cachebase = "dnsdist_pool_";
  output << "# HELP dnsdist_pool_servers " << "Number of servers in that pool" << "\n";
  output << "# TYPE dnsdist_pool_servers " << "gauge" << "\n";
  output << "# HELP dnsdist_pool_active_servers " << "Number of available servers in that pool" << "\n";
  output << "# TYPE dnsdist_pool_active_servers " << "gauge" << "\n";

  output << "# HELP dnsdist_pool_cache_size " << "Maximum number of entries that this cache can hold" << "\n";
  output << "# TYPE dnsdist_pool_cache_size " << "gauge" << "\n";
  output << "# HELP dnsdist_pool_cache_entries " << "Number of entries currently present in that cache" << "\n";
  output << "# TYPE dnsdist_pool_cache_entries " << "gauge" << "\n";
  output << "# HELP dnsdist_pool_cache_hits " << "Number of hits from that cache" << "\n";
  output << "# TYPE dnsdist_pool_cache_hits " << "counter" << "\n";
  output << "# HELP dnsdist_pool_cache_misses " << "Number of misses from that cache" << "\n";
  output << "# TYPE dnsdist_pool_cache_misses " << "counter" << "\n";
  output << "# HELP dnsdist_pool_cache_deferred_inserts " << "Number of insertions into that cache skipped because it was already locked" << "\n";
  output << "# TYPE dnsdist_pool_cache_deferred_inserts " << "counter" << "\n";
  output << "# HELP dnsdist_pool_cache_deferred_lookups " << "Number of lookups into that cache skipped because it was already locked" << "\n";
  output << "# TYPE dnsdist_pool_cache_deferred_lookups " << "counter" << "\n";
  output << "# HELP dnsdist_pool_cache_lookup_collisions " << "Number of lookups into that cache that triggered a collision (same hash but different entry)" << "\n";
  output << "# TYPE dnsdist_pool_cache_lookup_collisions " << "counter" << "\n";
  output << "# HELP dnsdist_pool_cache_insert_collisions " << "Number of insertions into that cache that triggered a collision (same hash but different entry)" << "\n";
  output << "# TYPE dnsdist_pool_cache_insert_collisions " << "counter" << "\n";
  output << "# HELP dnsdist_pool_cache_ttl_too_shorts " << "Number of insertions into that cache skipped because the TTL of the answer was not long enough" << "\n";
  output << "# TYPE dnsdist_pool_cache_ttl_too_shorts " << "counter" << "\n";
  output << "# HELP dnsdist_pool_cache_cleanup_count_total " << "Number of times the cache has been scanned to remove expired entries, if any" << "\n";
  output << "# TYPE dnsdist_pool_cache_cleanup_count_total " << "counter" << "\n";

  for (const auto& entry : *localPools) {
    string poolName = entry.first;

    if (poolName.empty()) {
      poolName = "_default_";
    }
    const string label = "{pool=\"" + poolName + "\"}";
    const std::shared_ptr<ServerPool> pool = entry.second;
    output << "dnsdist_pool_servers" << label << " " << pool->countServers(false) << "\n";
    output << "dnsdist_pool_active_servers" << label << " " << pool->countServers(true) << "\n";

    if (pool->packetCache != nullptr) {
      const auto& cache = pool->packetCache;

      output << cachebase << "cache_size"              <<label << " " << cache->getMaxEntries()       << "\n";
      output << cachebase << "cache_entries"           <<label << " " << cache->getEntriesCount()     << "\n";
      output << cachebase << "cache_hits"              <<label << " " << cache->getHits()             << "\n";
      output << cachebase << "cache_misses"            <<label << " " << cache->getMisses()           << "\n";
      output << cachebase << "cache_deferred_inserts"  <<label << " " << cache->getDeferredInserts()  << "\n";
      output << cachebase << "cache_deferred_lookups"  <<label << " " << cache->getDeferredLookups()  << "\n";
      output << cachebase << "cache_lookup_collisions" <<label << " " << cache->getLookupCollisions() << "\n";
      output << cachebase << "cache_insert_collisions" <<label << " " << cache->getInsertCollisions() << "\n";
      output << cachebase << "cache_ttl_too_shorts"    <<label << " " << cache->getTTLTooShorts()     << "\n";
      output << cachebase << "cache_cleanup_count_total"     <<label << " " << cache->getCleanupCount()     << "\n";
    }
  }

  output << "# HELP dnsdist_rule_hits " << "Number of hits of that rule" << "\n";
  output << "# TYPE dnsdist_rule_hits " << "counter" << "\n";
  addRulesToPrometheusOutput(output, g_ruleactions);
  addRulesToPrometheusOutput(output, g_respruleactions);
  addRulesToPrometheusOutput(output, g_cachehitrespruleactions);
  addRulesToPrometheusOutput(output, g_cacheInsertedRespRuleActions);
  addRulesToPrometheusOutput(output, g_selfansweredrespruleactions);

#ifndef DISABLE_DYNBLOCKS
  output << "# HELP dnsdist_dynblocks_nmg_top_offenders_hits_per_second " << "Number of hits per second blocked by Dynamic Blocks (netmasks) for the top offenders, averaged over the last 60s" << "\n";
  output << "# TYPE dnsdist_dynblocks_nmg_top_offenders_hits_per_second " << "gauge" << "\n";
  auto topNetmasksByReason = DynBlockMaintenance::getHitsForTopNetmasks();
  for (const auto& entry : topNetmasksByReason) {
    for (const auto& netmask : entry.second) {
      output << "dnsdist_dynblocks_nmg_top_offenders_hits_per_second{reason=\"" << entry.first << "\",netmask=\"" << netmask.first.toString() << "\"} " << netmask.second << "\n";
    }
  }

  output << "# HELP dnsdist_dynblocks_smt_top_offenders_hits_per_second " << "Number of this per second blocked by Dynamic Blocks (suffixes) for the top offenders, averaged over the last 60s" << "\n";
  output << "# TYPE dnsdist_dynblocks_smt_top_offenders_hits_per_second " << "gauge" << "\n";
  auto topSuffixesByReason = DynBlockMaintenance::getHitsForTopSuffixes();
  for (const auto& entry : topSuffixesByReason) {
    for (const auto& suffix : entry.second) {
      output << "dnsdist_dynblocks_smt_top_offenders_hits_per_second{reason=\"" << entry.first << "\",suffix=\"" << suffix.first.toString() << "\"} " << suffix.second << "\n";
    }
  }
#endif /* DISABLE_DYNBLOCKS */

  output << "# HELP dnsdist_info " << "Info from dnsdist, value is always 1" << "\n";
  output << "# TYPE dnsdist_info " << "gauge" << "\n";
  output << "dnsdist_info{version=\"" << VERSION << "\"} " << "1" << "\n";

  resp.body = output.str();
  resp.headers["Content-Type"] = "text/plain";
}
#endif /* DISABLE_PROMETHEUS */

using namespace json11;

static void addStatsToJSONObject(Json::object& obj)
{
  auto entries = dnsdist::metrics::g_stats.entries.read_lock();
  for (const auto& entry : *entries) {
    if (entry.d_name == "special-memory-usage") {
      continue; // Too expensive for get-all
    }
    if (const auto& val = std::get_if<pdns::stat_t*>(&entry.d_value)) {
      obj.emplace(entry.d_name, (double)(*val)->load());
    } else if (const auto& adval = std::get_if<pdns::stat_t_trait<double>*>(&entry.d_value)) {
      obj.emplace(entry.d_name, (*adval)->load());
    } else if (const auto& dval = std::get_if<double*>(&entry.d_value)) {
      obj.emplace(entry.d_name, (**dval));
    } else if (const auto& func = std::get_if<dnsdist::metrics::Stats::statfunction_t>(&entry.d_value)) {
      obj.emplace(entry.d_name, (double)(*func)(entry.d_name));
    }
  }
}

#ifndef DISABLE_BUILTIN_HTML
static void handleJSONStats(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  handleCORS(req, resp);
  resp.status = 200;

  if (req.getvars.count("command") == 0) {
    resp.status = 404;
    return;
  }

  const string& command = req.getvars.at("command");

  if (command == "stats") {
    auto obj=Json::object {
      { "packetcache-hits", 0},
      { "packetcache-misses", 0},
      { "over-capacity-drops", 0 },
      { "too-old-drops", 0 },
      { "server-policy", g_policy.getLocal()->getName()}
    };

    addStatsToJSONObject(obj);

    Json my_json = obj;
    resp.body = my_json.dump();
    resp.headers["Content-Type"] = "application/json";
  }
  else if (command == "dynblocklist") {
    Json::object obj;
#ifndef DISABLE_DYNBLOCKS
    auto nmg = g_dynblockNMG.getLocal();
    struct timespec now;
    gettime(&now);
    for (const auto& entry: *nmg) {
      if (!(now < entry.second.until)) {
        continue;
      }
      uint64_t counter = entry.second.blocks;
      if (entry.second.bpf && g_defaultBPFFilter) {
        counter += g_defaultBPFFilter->getHits(entry.first.getNetwork());
      }
      Json::object thing{
        {"reason", entry.second.reason},
        {"seconds", static_cast<double>(entry.second.until.tv_sec - now.tv_sec)},
        {"blocks", static_cast<double>(counter)},
        {"action", DNSAction::typeToString(entry.second.action != DNSAction::Action::None ? entry.second.action : g_dynBlockAction)},
        {"warning", entry.second.warning},
        {"ebpf", entry.second.bpf}
      };
      obj.emplace(entry.first.toString(), thing);
    }

    auto smt = g_dynblockSMT.getLocal();
    smt->visit([&now,&obj](const SuffixMatchTree<DynBlock>& node) {
      if (!(now < node.d_value.until)) {
        return;
      }
      string dom("empty");
      if (!node.d_value.domain.empty()) {
        dom = node.d_value.domain.toString();
      }
      Json::object thing{
        {"reason", node.d_value.reason},
        {"seconds", static_cast<double>(node.d_value.until.tv_sec - now.tv_sec)},
        {"blocks", static_cast<double>(node.d_value.blocks)},
        {"action", DNSAction::typeToString(node.d_value.action != DNSAction::Action::None ? node.d_value.action : g_dynBlockAction)},
        {"ebpf", node.d_value.bpf}
      };
      obj.emplace(dom, thing);
    });
#endif /* DISABLE_DYNBLOCKS */
    Json my_json = obj;
    resp.body = my_json.dump();
    resp.headers["Content-Type"] = "application/json";
  }
  else if (command == "ebpfblocklist") {
    Json::object obj;
#ifdef HAVE_EBPF
    struct timespec now;
    gettime(&now);
    for (const auto& dynbpf : g_dynBPFFilters) {
      std::vector<std::tuple<ComboAddress, uint64_t, struct timespec> > addrStats = dynbpf->getAddrStats();
      for (const auto& entry : addrStats) {
        Json::object thing
          {
            {"seconds", (double)(std::get<2>(entry).tv_sec - now.tv_sec)},
            {"blocks", (double)(std::get<1>(entry))}
          };
        obj.emplace(std::get<0>(entry).toString(), thing );
      }
    }
    if (g_defaultBPFFilter) {
      auto nmg = g_dynblockNMG.getLocal();
      for (const auto& entry: *nmg) {
        if (!(now < entry.second.until) || !entry.second.bpf) {
          continue;
        }
        uint64_t counter = entry.second.blocks + g_defaultBPFFilter->getHits(entry.first.getNetwork());
        Json::object thing{
          {"reason", entry.second.reason},
          {"seconds", static_cast<double>(entry.second.until.tv_sec - now.tv_sec)},
          {"blocks", static_cast<double>(counter)},
          {"action", DNSAction::typeToString(entry.second.action != DNSAction::Action::None ? entry.second.action : g_dynBlockAction)},
          {"warning", entry.second.warning},
        };
        obj.emplace(entry.first.toString(), thing);
      }
    }
#endif /* HAVE_EBPF */
    Json my_json = obj;
    resp.body = my_json.dump();
    resp.headers["Content-Type"] = "application/json";
  }
  else {
    resp.status = 404;
  }
}
#endif /* DISABLE_BUILTIN_HTML */

static void addServerToJSON(Json::array& servers, int id, const std::shared_ptr<DownstreamState>& a)
{
  string status;
  if (a->d_config.availability == DownstreamState::Availability::Up) {
    status = "UP";
  }
  else if (a->d_config.availability == DownstreamState::Availability::Down) {
    status = "DOWN";
  }
  else {
    status = (a->upStatus ? "up" : "down");
  }

  Json::array pools;
  pools.reserve(a->d_config.pools.size());
  for (const auto& p: a->d_config.pools) {
    pools.push_back(p);
  }

  Json::object server {
    {"id", id},
    {"name", a->getName()},
    {"address", a->d_config.remote.toStringWithPort()},
    {"state", status},
    {"protocol", a->getProtocol().toPrettyString()},
    {"qps", (double)a->queryLoad},
    {"qpsLimit", (double)a->qps.getRate()},
    {"outstanding", (double)a->outstanding},
    {"reuseds", (double)a->reuseds},
    {"weight", (double)a->d_config.d_weight},
    {"order", (double)a->d_config.order},
    {"pools", std::move(pools)},
    {"latency", (double)(a->latencyUsec/1000.0)},
    {"queries", (double)a->queries},
    {"responses", (double)a->responses},
    {"nonCompliantResponses", (double)a->nonCompliantResponses},
    {"sendErrors", (double)a->sendErrors},
    {"tcpDiedSendingQuery", (double)a->tcpDiedSendingQuery},
    {"tcpDiedReadingResponse", (double)a->tcpDiedReadingResponse},
    {"tcpGaveUp", (double)a->tcpGaveUp},
    {"tcpConnectTimeouts", (double)a->tcpConnectTimeouts},
    {"tcpReadTimeouts", (double)a->tcpReadTimeouts},
    {"tcpWriteTimeouts", (double)a->tcpWriteTimeouts},
    {"tcpCurrentConnections", (double)a->tcpCurrentConnections},
    {"tcpMaxConcurrentConnections", (double)a->tcpMaxConcurrentConnections},
    {"tcpTooManyConcurrentConnections", (double)a->tcpTooManyConcurrentConnections},
    {"tcpNewConnections", (double)a->tcpNewConnections},
    {"tcpReusedConnections", (double)a->tcpReusedConnections},
    {"tcpAvgQueriesPerConnection", (double)a->tcpAvgQueriesPerConnection},
    {"tcpAvgConnectionDuration", (double)a->tcpAvgConnectionDuration},
    {"tlsResumptions", (double)a->tlsResumptions},
    {"tcpLatency", (double)(a->latencyUsecTCP/1000.0)},
    {"healthCheckFailures", (double)(a->d_healthCheckMetrics.d_failures)},
    {"healthCheckFailuresParsing", (double)(a->d_healthCheckMetrics.d_parseErrors)},
    {"healthCheckFailuresTimeout", (double)(a->d_healthCheckMetrics.d_timeOuts)},
    {"healthCheckFailuresNetwork", (double)(a->d_healthCheckMetrics.d_networkErrors)},
    {"healthCheckFailuresMismatch", (double)(a->d_healthCheckMetrics.d_mismatchErrors)},
    {"healthCheckFailuresInvalid", (double)(a->d_healthCheckMetrics.d_invalidResponseErrors)},
    {"dropRate", (double)a->dropRate}
  };

  /* sending a latency for a DOWN server doesn't make sense */
  if (a->d_config.availability == DownstreamState::Availability::Down) {
    server["latency"] = nullptr;
    server["tcpLatency"] = nullptr;
  }

  servers.push_back(std::move(server));
}

static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  handleCORS(req, resp);
  resp.status = 200;

  int num = 0;

  Json::array servers;
  {
    auto localServers = g_dstates.getLocal();
    servers.reserve(localServers->size());
    for (const auto& a : *localServers) {
      addServerToJSON(servers, num++, a);
    }
  }

  Json::array frontends;
  num = 0;
  frontends.reserve(g_frontends.size());
  for (const auto& front : g_frontends) {
    if (front->udpFD == -1 && front->tcpFD == -1)
      continue;
    Json::object frontend {
      { "id", num++ },
      { "address", front->local.toStringWithPort() },
      { "udp", front->udpFD >= 0 },
      { "tcp", front->tcpFD >= 0 },
      { "type", front->getType() },
      { "queries", (double) front->queries.load() },
      { "nonCompliantQueries", (double) front->nonCompliantQueries.load() },
      { "responses", (double) front->responses.load() },
      { "tcpDiedReadingQuery", (double) front->tcpDiedReadingQuery.load() },
      { "tcpDiedSendingResponse", (double) front->tcpDiedSendingResponse.load() },
      { "tcpGaveUp", (double) front->tcpGaveUp.load() },
      { "tcpClientTimeouts", (double) front->tcpClientTimeouts },
      { "tcpDownstreamTimeouts", (double) front->tcpDownstreamTimeouts },
      { "tcpCurrentConnections", (double) front->tcpCurrentConnections },
      { "tcpMaxConcurrentConnections", (double) front->tcpMaxConcurrentConnections },
      { "tcpAvgQueriesPerConnection", (double) front->tcpAvgQueriesPerConnection },
      { "tcpAvgConnectionDuration", (double) front->tcpAvgConnectionDuration },
      { "tlsNewSessions", (double) front->tlsNewSessions },
      { "tlsResumptions", (double) front->tlsResumptions },
      { "tlsUnknownTicketKey", (double) front->tlsUnknownTicketKey },
      { "tlsInactiveTicketKey", (double) front->tlsInactiveTicketKey },
      { "tls10Queries", (double) front->tls10queries },
      { "tls11Queries", (double) front->tls11queries },
      { "tls12Queries", (double) front->tls12queries },
      { "tls13Queries", (double) front->tls13queries },
      { "tlsUnknownQueries", (double) front->tlsUnknownqueries },
    };
    const TLSErrorCounters* errorCounters = nullptr;
    if (front->tlsFrontend != nullptr) {
      errorCounters = &front->tlsFrontend->d_tlsCounters;
    }
    else if (front->dohFrontend != nullptr) {
      errorCounters = &front->dohFrontend->d_tlsContext.d_tlsCounters;
    }
    if (errorCounters != nullptr) {
      frontend["tlsHandshakeFailuresDHKeyTooSmall"] = (double)errorCounters->d_dhKeyTooSmall;
      frontend["tlsHandshakeFailuresInappropriateFallBack"] = (double)errorCounters->d_inappropriateFallBack;
      frontend["tlsHandshakeFailuresNoSharedCipher"] = (double)errorCounters->d_noSharedCipher;
      frontend["tlsHandshakeFailuresUnknownCipher"] = (double)errorCounters->d_unknownCipherType;
      frontend["tlsHandshakeFailuresUnknownKeyExchangeType"] = (double)errorCounters->d_unknownKeyExchangeType;
      frontend["tlsHandshakeFailuresUnknownProtocol"] = (double)errorCounters->d_unknownProtocol;
      frontend["tlsHandshakeFailuresUnsupportedEC"] = (double)errorCounters->d_unsupportedEC;
      frontend["tlsHandshakeFailuresUnsupportedProtocol"] = (double)errorCounters->d_unsupportedProtocol;
    }
    frontends.push_back(std::move(frontend));
  }

  Json::array dohs;
#ifdef HAVE_DNS_OVER_HTTPS
  {
    dohs.reserve(g_dohlocals.size());
    num = 0;
    for (const auto& doh : g_dohlocals) {
      dohs.emplace_back(Json::object{
        { "id", num++ },
        { "address", doh->d_tlsContext.d_addr.toStringWithPort() },
        { "http-connects", (double) doh->d_httpconnects },
        { "http1-queries", (double) doh->d_http1Stats.d_nbQueries },
        { "http2-queries", (double) doh->d_http2Stats.d_nbQueries },
        { "http1-200-responses", (double) doh->d_http1Stats.d_nb200Responses },
        { "http2-200-responses", (double) doh->d_http2Stats.d_nb200Responses },
        { "http1-400-responses", (double) doh->d_http1Stats.d_nb400Responses },
        { "http2-400-responses", (double) doh->d_http2Stats.d_nb400Responses },
        { "http1-403-responses", (double) doh->d_http1Stats.d_nb403Responses },
        { "http2-403-responses", (double) doh->d_http2Stats.d_nb403Responses },
        { "http1-500-responses", (double) doh->d_http1Stats.d_nb500Responses },
        { "http2-500-responses", (double) doh->d_http2Stats.d_nb500Responses },
        { "http1-502-responses", (double) doh->d_http1Stats.d_nb502Responses },
        { "http2-502-responses", (double) doh->d_http2Stats.d_nb502Responses },
        { "http1-other-responses", (double) doh->d_http1Stats.d_nbOtherResponses },
        { "http2-other-responses", (double) doh->d_http2Stats.d_nbOtherResponses },
        { "get-queries", (double) doh->d_getqueries },
        { "post-queries", (double) doh->d_postqueries },
        { "bad-requests", (double) doh->d_badrequests },
        { "error-responses", (double) doh->d_errorresponses },
        { "redirect-responses", (double) doh->d_redirectresponses },
        { "valid-responses", (double) doh->d_validresponses }
      });
    }
  }
#endif /* HAVE_DNS_OVER_HTTPS */

  Json::array pools;
  {
    auto localPools = g_pools.getLocal();
    num = 0;
    pools.reserve(localPools->size());
    for (const auto& pool : *localPools) {
      const auto& cache = pool.second->packetCache;
      Json::object entry {
        { "id", num++ },
        { "name", pool.first },
        { "serversCount", (double) pool.second->countServers(false) },
        { "cacheSize", (double) (cache ? cache->getMaxEntries() : 0) },
        { "cacheEntries", (double) (cache ? cache->getEntriesCount() : 0) },
        { "cacheHits", (double) (cache ? cache->getHits() : 0) },
        { "cacheMisses", (double) (cache ? cache->getMisses() : 0) },
        { "cacheDeferredInserts", (double) (cache ? cache->getDeferredInserts() : 0) },
        { "cacheDeferredLookups", (double) (cache ? cache->getDeferredLookups() : 0) },
        { "cacheLookupCollisions", (double) (cache ? cache->getLookupCollisions() : 0) },
        { "cacheInsertCollisions", (double) (cache ? cache->getInsertCollisions() : 0) },
        { "cacheTTLTooShorts", (double) (cache ? cache->getTTLTooShorts() : 0) },
        { "cacheCleanupCount", (double) (cache ? cache->getCleanupCount() : 0) }
      };
      pools.push_back(std::move(entry));
    }
  }

  Json::array rules;
  /* unfortunately DNSActions have getStats(),
     and DNSResponseActions do not. */
  {
    auto localRules = g_ruleactions.getLocal();
    num = 0;
    rules.reserve(localRules->size());
    for (const auto& a : *localRules) {
      Json::object rule{
        {"id", num++},
        {"creationOrder", (double)a.d_creationOrder},
        {"uuid", boost::uuids::to_string(a.d_id)},
        {"name", a.d_name},
        {"matches", (double)a.d_rule->d_matches},
        {"rule", a.d_rule->toString()},
        {"action", a.d_action->toString()},
        {"action-stats", a.d_action->getStats()}
      };
      rules.push_back(std::move(rule));
    }
  }
  auto responseRules = someResponseRulesToJson(&g_respruleactions);
  auto cacheHitResponseRules = someResponseRulesToJson(&g_cachehitrespruleactions);
  auto cacheInsertedResponseRules = someResponseRulesToJson(&g_cacheInsertedRespRuleActions);
  auto selfAnsweredResponseRules = someResponseRulesToJson(&g_selfansweredrespruleactions);

  string acl;
  {
    auto aclEntries = g_ACL.getLocal()->toStringVector();

    for (const auto& entry : aclEntries) {
      if (!acl.empty()) {
        acl += ", ";
      }
      acl += entry;
    }
  }

  string localaddressesStr;
  {
    std::set<std::string> localaddresses;
    for (const auto& front : g_frontends) {
      localaddresses.insert(front->local.toStringWithPort());
    }
    for (const auto& addr : localaddresses) {
      if (!localaddressesStr.empty()) {
        localaddressesStr += ", ";
      }
      localaddressesStr += addr;
    }
  }

  Json::object stats;
  addStatsToJSONObject(stats);

  Json responseObject(Json::object({
    { "daemon_type", "dnsdist" },
    { "version", VERSION },
    { "servers", std::move(servers) },
    { "frontends", std::move(frontends) },
    { "pools", std::move(pools) },
    { "rules", std::move(rules) },
    { "response-rules", std::move(responseRules) },
    { "cache-hit-response-rules", std::move(cacheHitResponseRules) },
    { "cache-inserted-response-rules", std::move(cacheInsertedResponseRules) },
    { "self-answered-response-rules", std::move(selfAnsweredResponseRules) },
    { "acl", std::move(acl) },
    { "local", std::move(localaddressesStr) },
    { "dohFrontends", std::move(dohs) },
    { "statistics", std::move(stats) }
        }));

  resp.headers["Content-Type"] = "application/json";
  resp.body = responseObject.dump();
}

static void handlePoolStats(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  handleCORS(req, resp);
  const auto poolName = req.getvars.find("name");
  if (poolName == req.getvars.end()) {
    resp.status = 400;
    return;
  }

  resp.status = 200;
  Json::array doc;

  auto localPools = g_pools.getLocal();
  const auto poolIt = localPools->find(poolName->second);
  if (poolIt == localPools->end()) {
    resp.status = 404;
    return;
  }

  const auto& pool = poolIt->second;
  const auto& cache = pool->packetCache;
  Json::object entry {
    { "name", poolName->second },
    { "serversCount", (double) pool->countServers(false) },
    { "cacheSize", (double) (cache ? cache->getMaxEntries() : 0) },
    { "cacheEntries", (double) (cache ? cache->getEntriesCount() : 0) },
    { "cacheHits", (double) (cache ? cache->getHits() : 0) },
    { "cacheMisses", (double) (cache ? cache->getMisses() : 0) },
    { "cacheDeferredInserts", (double) (cache ? cache->getDeferredInserts() : 0) },
    { "cacheDeferredLookups", (double) (cache ? cache->getDeferredLookups() : 0) },
    { "cacheLookupCollisions", (double) (cache ? cache->getLookupCollisions() : 0) },
    { "cacheInsertCollisions", (double) (cache ? cache->getInsertCollisions() : 0) },
    { "cacheTTLTooShorts", (double) (cache ? cache->getTTLTooShorts() : 0) },
    { "cacheCleanupCount", (double) (cache ? cache->getCleanupCount() : 0) }
  };

  Json::array servers;
  int num = 0;
  for (const auto& a : *pool->getServers()) {
    addServerToJSON(servers, num, a.second);
    num++;
  }

  resp.headers["Content-Type"] = "application/json";
  Json my_json = Json::object {
    { "stats", entry },
    { "servers", servers }
  };

  resp.body = my_json.dump();
}

static void handleStatsOnly(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  handleCORS(req, resp);
  resp.status = 200;

  Json::array doc;
  {
    auto entries = dnsdist::metrics::g_stats.entries.read_lock();
    for (const auto& item : *entries) {
      if (item.d_name == "special-memory-usage") {
        continue; // Too expensive for get-all
      }

      if (const auto& val = std::get_if<pdns::stat_t*>(&item.d_value)) {
        doc.push_back(Json::object {
            { "type", "StatisticItem" },
            { "name", item.d_name },
            { "value", (double)(*val)->load() }
          });
      }
      else if (const auto& adval = std::get_if<pdns::stat_t_trait<double>*>(&item.d_value)) {
        doc.push_back(Json::object {
            { "type", "StatisticItem" },
            { "name", item.d_name },
            { "value", (*adval)->load() }
          });
      }
      else if (const auto& dval = std::get_if<double*>(&item.d_value)) {
        doc.push_back(Json::object {
            { "type", "StatisticItem" },
            { "name", item.d_name },
            { "value", (**dval) }
          });
      }
      else if (const auto& func = std::get_if<dnsdist::metrics::Stats::statfunction_t>(&item.d_value)) {
        doc.push_back(Json::object {
            { "type", "StatisticItem" },
            { "name", item.d_name },
            { "value", (double)(*func)(item.d_name) }
          });
      }
    }
  }
  Json my_json = doc;
  resp.body = my_json.dump();
  resp.headers["Content-Type"] = "application/json";
}

#ifndef DISABLE_WEB_CONFIG
static void handleConfigDump(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  handleCORS(req, resp);
  resp.status = 200;

  Json::array doc;
  typedef boost::variant<bool, double, std::string> configentry_t;
  std::vector<std::pair<std::string, configentry_t> > configEntries {
    { "acl", g_ACL.getLocal()->toString() },
    { "allow-empty-response", g_allowEmptyResponse },
    { "control-socket", g_serverControl.toStringWithPort() },
    { "ecs-override", g_ECSOverride },
    { "ecs-source-prefix-v4", (double) g_ECSSourcePrefixV4 },
    { "ecs-source-prefix-v6", (double)  g_ECSSourcePrefixV6 },
    { "fixup-case", g_fixupCase },
    { "max-outstanding", (double) g_maxOutstanding },
    { "server-policy", g_policy.getLocal()->getName() },
    { "stale-cache-entries-ttl", (double) g_staleCacheEntriesTTL },
    { "tcp-recv-timeout", (double) g_tcpRecvTimeout },
    { "tcp-send-timeout", (double) g_tcpSendTimeout },
    { "truncate-tc", g_truncateTC },
    { "verbose", g_verbose },
    { "verbose-health-checks", g_verboseHealthChecks }
  };
  for(const auto& item : configEntries) {
    if (const auto& bval = boost::get<bool>(&item.second)) {
      doc.push_back(Json::object {
          { "type", "ConfigSetting" },
          { "name", item.first },
          { "value", *bval }
        });
    }
    else if (const auto& sval = boost::get<string>(&item.second)) {
      doc.push_back(Json::object {
          { "type", "ConfigSetting" },
          { "name", item.first },
          { "value", *sval }
        });
    }
    else if (const auto& dval = boost::get<double>(&item.second)) {
      doc.push_back(Json::object {
          { "type", "ConfigSetting" },
          { "name", item.first },
          { "value", *dval }
        });
    }
  }
  Json my_json = doc;
  resp.body = my_json.dump();
  resp.headers["Content-Type"] = "application/json";
}

static void handleAllowFrom(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  handleCORS(req, resp);

  resp.headers["Content-Type"] = "application/json";
  resp.status = 200;

  if (req.method == "PUT") {
    std::string err;
    Json doc = Json::parse(req.body, err);

    if (!doc.is_null()) {
      NetmaskGroup nmg;
      auto aclList = doc["value"];
      if (aclList.is_array()) {

        for (const auto& value : aclList.array_items()) {
          try {
            nmg.addMask(value.string_value());
          } catch (NetmaskException &e) {
            resp.status = 400;
            break;
          }
        }

        if (resp.status == 200) {
          infolog("Updating the ACL via the API to %s", nmg.toString());
          g_ACL.setState(nmg);
          apiSaveACL(nmg);
        }
      }
      else {
        resp.status = 400;
      }
    }
    else {
      resp.status = 400;
    }
  }
  if (resp.status == 200) {
    auto aclEntries = g_ACL.getLocal()->toStringVector();

    Json::object obj{
      { "type", "ConfigSetting" },
      { "name", "allow-from" },
      { "value", aclEntries }
    };
    Json my_json = obj;
    resp.body = my_json.dump();
  }
}
#endif /* DISABLE_WEB_CONFIG */

#ifndef DISABLE_WEB_CACHE_MANAGEMENT
static void handleCacheManagement(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  handleCORS(req, resp);

  resp.headers["Content-Type"] = "application/json";
  resp.status = 200;

  if (req.method != "DELETE") {
    resp.status = 400;
    Json::object obj{
      { "status", "denied" },
      { "error", "invalid method" }
    };
    resp.body = Json(obj).dump();
    return;
  }

  const auto poolName = req.getvars.find("pool");
  const auto expungeName = req.getvars.find("name");
  const auto expungeType = req.getvars.find("type");
  const auto suffix = req.getvars.find("suffix");
  if (poolName == req.getvars.end() || expungeName == req.getvars.end()) {
    resp.status = 400;
    Json::object obj{
      { "status", "denied" },
      { "error", "missing 'pool' or 'name' parameter" },
    };
    resp.body = Json(obj).dump();
    return;
  }

  DNSName name;
  QType type(QType::ANY);
  try {
    name = DNSName(expungeName->second);
  }
  catch (const std::exception& e) {
    resp.status = 400;
    Json::object obj{
      { "status", "error" },
      { "error", "unable to parse the requested name" },
    };
    resp.body = Json(obj).dump();
    return;
  }
  if (expungeType != req.getvars.end()) {
    type = QType::chartocode(expungeType->second.c_str());
  }

  std::shared_ptr<ServerPool> pool;
  try {
    pool = getPool(g_pools.getCopy(), poolName->second);
  }
  catch (const std::exception& e) {
    resp.status = 404;
    Json::object obj{
      { "status", "not found" },
      { "error", "the requested pool does not exist" },
    };
    resp.body = Json(obj).dump();
    return;
  }

  auto cache = pool->getCache();
  if (cache == nullptr) {
    resp.status = 404;
    Json::object obj{
      { "status", "not found" },
      { "error", "there is no cache associated with the requested pool" },
    };
    resp.body = Json(obj).dump();
    return;
  }

  auto removed = cache->expungeByName(name, type.getCode(), suffix != req.getvars.end());

  Json::object obj{
      { "status", "purged" },
      { "count", std::to_string(removed) }
    };
  resp.body = Json(obj).dump();
}
#endif /* DISABLE_WEB_CACHE_MANAGEMENT */

template<typename T> static void addRingEntryToList(const struct timespec& now, Json::array& list, const T& entry)
{
  constexpr bool response = std::is_same_v<T, Rings::Response>;
  Json::object tmp{
    { "age", static_cast<double>(DiffTime(entry.when, now)) },
    { "id", ntohs(entry.dh.id) },
    { "name", entry.name.toString() },
    { "requestor", entry.requestor.toStringWithPort() },
    { "size", static_cast<int>(entry.size) },
    { "qtype", entry.qtype },
    { "protocol", entry.protocol.toString() },
    { "rd", static_cast<bool>(entry.dh.rd) },
  };
  if constexpr (!response) {
#if defined(DNSDIST_RINGS_WITH_MACADDRESS)
    tmp.emplace("mac", entry.hasmac ? std::string(reinterpret_cast<const char*>(entry.macaddress.data()), entry.macaddress.size()) : std::string());
#endif
  }
  else {
    tmp.emplace("latency", static_cast<double>(entry.usec));
    tmp.emplace("rcode", static_cast<uint8_t>(entry.dh.rcode));
    tmp.emplace("tc", static_cast<bool>(entry.dh.tc));
    tmp.emplace("aa", static_cast<bool>(entry.dh.aa));
    tmp.emplace("answers", ntohs(entry.dh.ancount));
    auto server = entry.ds.toStringWithPort();
    tmp.emplace("backend", server != "0.0.0.0:0" ? std::move(server) : "Cache");
  }
  list.push_back(std::move(tmp));
}

static void handleRings(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  handleCORS(req, resp);

  std::optional<size_t> maxNumberOfQueries{std::nullopt};
  std::optional<size_t> maxNumberOfResponses{std::nullopt};

  const auto maxQueries = req.getvars.find("maxQueries");
  if (maxQueries != req.getvars.end()) {
    try {
      maxNumberOfQueries = pdns::checked_stoi<size_t>(maxQueries->second);
    }
    catch (const std::exception& exp) {
      vinfolog("Error parsing the 'maxQueries' value from rings HTTP GET query: %s", exp.what());
    }
  }

  const auto maxResponses = req.getvars.find("maxResponses");
  if (maxResponses != req.getvars.end()) {
    try {
      maxNumberOfResponses = pdns::checked_stoi<size_t>(maxResponses->second);
    }
    catch (const std::exception& exp) {
      vinfolog("Error parsing the 'maxResponses' value from rings HTTP GET query: %s", exp.what());
    }
  }

  resp.status = 200;

  Json::object doc;
  size_t numberOfQueries = 0;
  size_t numberOfResponses = 0;
  Json::array queries;
  Json::array responses;
  struct timespec now
  {
  };
  gettime(&now);

  for (const auto& shard : g_rings.d_shards) {
    if (!maxNumberOfQueries || numberOfQueries < *maxNumberOfQueries) {
      auto queryRing = shard->queryRing.lock();
      for (const auto& entry : *queryRing) {
        addRingEntryToList(now, queries, entry);
        numberOfQueries++;
        if (maxNumberOfQueries && numberOfQueries >= *maxNumberOfQueries) {
          break;
        }
      }
    }
    if (!maxNumberOfResponses || numberOfResponses < *maxNumberOfResponses) {
      auto responseRing = shard->respRing.lock();
      for (const auto& entry : *responseRing) {
        addRingEntryToList(now, responses, entry);
        numberOfResponses++;
        if (maxNumberOfResponses && numberOfResponses >= *maxNumberOfResponses) {
          break;
        }
      }
    }
  }
  doc.emplace("queries", std::move(queries));
  doc.emplace("responses", std::move(responses));
  Json my_json = doc;
  resp.body = my_json.dump();
  resp.headers["Content-Type"] = "application/json";
}

using WebHandler = std::function<void(const YaHTTP::Request&, YaHTTP::Response&)>;
struct WebHandlerContext
{
  WebHandler d_handler;
  bool d_isLua{false};
};

static SharedLockGuarded<std::unordered_map<std::string, WebHandlerContext>> s_webHandlers;

void registerWebHandler(const std::string& endpoint, WebHandler handler, bool isLua = false);

void registerWebHandler(const std::string& endpoint, WebHandler handler, bool isLua)
{
  auto handlers = s_webHandlers.write_lock();
  (*handlers)[endpoint] = WebHandlerContext{std::move(handler), isLua};
}

void clearWebHandlers()
{
  s_webHandlers.write_lock()->clear();
}

#ifndef DISABLE_BUILTIN_HTML
#include "htmlfiles.h"

static void redirectToIndex(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  const string charset = "; charset=utf-8";
  resp.body.assign(s_urlmap.at("index.html"));
  resp.headers["Content-Type"] = "text/html" + charset;
  resp.status = 200;
}

static void handleBuiltInFiles(const YaHTTP::Request& req, YaHTTP::Response& resp)
{
  if (req.url.path.empty() || !s_urlmap.count(req.url.path.c_str()+1)) {
    resp.status = 404;
    return;
  }

  resp.body.assign(s_urlmap.at(req.url.path.c_str()+1));

  vector<string> parts;
  stringtok(parts, req.url.path, ".");
  static const std::unordered_map<std::string, std::string> contentTypeMap = {
    { "html", "text/html" },
    { "css", "text/css" },
    { "js", "application/javascript" },
    { "png", "image/png" },
  };

  const auto& it = contentTypeMap.find(parts.back());
  if (it != contentTypeMap.end()) {
    const string charset = "; charset=utf-8";
    resp.headers["Content-Type"] = it->second + charset;
  }

  resp.status = 200;
}
#endif /* DISABLE_BUILTIN_HTML */

void registerBuiltInWebHandlers()
{
#ifndef DISABLE_BUILTIN_HTML
  registerWebHandler("/jsonstat", handleJSONStats);
#endif /* DISABLE_BUILTIN_HTML */
#ifndef DISABLE_PROMETHEUS
  registerWebHandler("/metrics", handlePrometheus);
#endif /* DISABLE_PROMETHEUS */
  registerWebHandler("/api/v1/servers/localhost", handleStats);
  registerWebHandler("/api/v1/servers/localhost/pool", handlePoolStats);
  registerWebHandler("/api/v1/servers/localhost/statistics", handleStatsOnly);
  registerWebHandler("/api/v1/servers/localhost/rings", handleRings);
#ifndef DISABLE_WEB_CONFIG
  registerWebHandler("/api/v1/servers/localhost/config", handleConfigDump);
  registerWebHandler("/api/v1/servers/localhost/config/allow-from", handleAllowFrom);
#endif /* DISABLE_WEB_CONFIG */
#ifndef DISABLE_WEB_CACHE_MANAGEMENT
  registerWebHandler("/api/v1/cache", handleCacheManagement);
#endif /* DISABLE_WEB_CACHE_MANAGEMENT */
#ifndef DISABLE_BUILTIN_HTML
  registerWebHandler("/", redirectToIndex);

  for (const auto& path : s_urlmap) {
    registerWebHandler("/" + path.first, handleBuiltInFiles);
  }
#endif /* DISABLE_BUILTIN_HTML */
}

static void connectionThread(WebClientConnection&& conn)
{
  setThreadName("dnsdist/webConn");

  vinfolog("Webserver handling connection from %s", conn.getClient().toStringWithPort());

  try {
    YaHTTP::AsyncRequestLoader yarl;
    YaHTTP::Request req;
    bool finished = false;

    yarl.initialize(&req);
    while (!finished) {
      int bytes;
      char buf[1024];
      bytes = read(conn.getSocket().getHandle(), buf, sizeof(buf));
      if (bytes > 0) {
        string data = string(buf, bytes);
        finished = yarl.feed(data);
      } else {
        // read error OR EOF
        break;
      }
    }
    yarl.finalize();

    req.getvars.erase("_"); // jQuery cache buster

    YaHTTP::Response resp;
    resp.version = req.version;

    {
      auto config = g_webserverConfig.lock();

      addCustomHeaders(resp, config->customHeaders);
      addSecurityHeaders(resp, config->customHeaders);
    }
    /* indicate that the connection will be closed after completion of the response */
    resp.headers["Connection"] = "close";

    /* no need to send back the API key if any */
    resp.headers.erase("X-API-Key");

    if (req.method == "OPTIONS") {
      /* the OPTIONS method should not require auth, otherwise it breaks CORS */
      handleCORS(req, resp);
      resp.status = 200;
    }
    else if (!handleAuthorization(req)) {
      YaHTTP::strstr_map_t::iterator header = req.headers.find("authorization");
      if (header != req.headers.end()) {
        vinfolog("HTTP Request \"%s\" from %s: Web Authentication failed", req.url.path, conn.getClient().toStringWithPort());
      }
      resp.status = 401;
      resp.body = "<h1>Unauthorized</h1>";
      resp.headers["WWW-Authenticate"] = "basic realm=\"PowerDNS\"";
    }
    else if (!isMethodAllowed(req)) {
      resp.status = 405;
    }
    else {
      std::optional<WebHandlerContext> handlerCtx{std::nullopt};
      {
        auto handlers = s_webHandlers.read_lock();
        const auto webHandlersIt = handlers->find(req.url.path);
        if (webHandlersIt != handlers->end()) {
          handlerCtx = webHandlersIt->second;
        }
      }

      if (handlerCtx) {
        if (handlerCtx->d_isLua) {
          auto lua = g_lua.lock();
          handlerCtx->d_handler(req, resp);
        }
        else {
          handlerCtx->d_handler(req, resp);
        }
      }
      else {
        resp.status = 404;
      }
    }

    std::ostringstream ofs;
    ofs << resp;
    string done = ofs.str();
    writen2(conn.getSocket().getHandle(), done.c_str(), done.size());
  }
  catch (const YaHTTP::ParseError& e) {
    vinfolog("Webserver thread died with parse error exception while processing a request from %s: %s", conn.getClient().toStringWithPort(), e.what());
  }
  catch (const std::exception& e) {
    vinfolog("Webserver thread died with exception while processing a request from %s: %s", conn.getClient().toStringWithPort(), e.what());
  }
  catch (...) {
    vinfolog("Webserver thread died with exception while processing a request from %s", conn.getClient().toStringWithPort());
  }
}

void setWebserverAPIKey(std::unique_ptr<CredentialsHolder>&& apiKey)
{
  auto config = g_webserverConfig.lock();

  if (apiKey) {
    config->apiKey = std::move(apiKey);
  } else {
    config->apiKey.reset();
  }
}

void setWebserverPassword(std::unique_ptr<CredentialsHolder>&& password)
{
  g_webserverConfig.lock()->password = std::move(password);
}

void setWebserverACL(const std::string& acl)
{
  NetmaskGroup newACL;
  newACL.toMasks(acl);

  g_webserverConfig.lock()->acl = std::move(newACL);
}

void setWebserverCustomHeaders(const boost::optional<std::unordered_map<std::string, std::string> > customHeaders)
{
  g_webserverConfig.lock()->customHeaders = customHeaders;
}

void setWebserverStatsRequireAuthentication(bool require)
{
  g_webserverConfig.lock()->statsRequireAuthentication = require;
}

void setWebserverAPIRequiresAuthentication(bool require)
{
  g_webserverConfig.lock()->apiRequiresAuthentication = require;
}

void setWebserverDashboardRequiresAuthentication(bool require)
{
  g_webserverConfig.lock()->dashboardRequiresAuthentication = require;
}

void setWebserverMaxConcurrentConnections(size_t max)
{
  s_connManager.setMaxConcurrentConnections(max);
}

void dnsdistWebserverThread(int sock, const ComboAddress& local)
{
  setThreadName("dnsdist/webserv");
  infolog("Webserver launched on %s", local.toStringWithPort());

  {
    auto config = g_webserverConfig.lock();
    if (!config->password && config->dashboardRequiresAuthentication) {
      warnlog("Webserver launched on %s without a password set!", local.toStringWithPort());
    }
  }

  for (;;) {
    try {
      ComboAddress remote(local);
      int fd = SAccept(sock, remote);

      if (!isClientAllowedByACL(remote)) {
        vinfolog("Connection to webserver from client %s is not allowed, closing", remote.toStringWithPort());
        close(fd);
        continue;
      }

      WebClientConnection conn(remote, fd);
      vinfolog("Got a connection to the webserver from %s", remote.toStringWithPort());

      std::thread t(connectionThread, std::move(conn));
      t.detach();
    }
    catch (const std::exception& e) {
      vinfolog("Had an error accepting new webserver connection: %s", e.what());
    }
  }
}