From e9d1fcab50db8d1a4c766aca345e66d803882341 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 11:08:30 +0100 Subject: [PATCH 01/25] dnsdist: Remove symbolic links for dnsdist-specific files --- pdns/dnsdistdist/dnsdist-cache.cc | 1 - pdns/dnsdistdist/dnsdist-cache.hh | 1 - pdns/dnsdistdist/dnsdist-carbon.cc | 1 - pdns/dnsdistdist/dnsdist-console.cc | 1 - pdns/dnsdistdist/dnsdist-console.hh | 1 - pdns/dnsdistdist/dnsdist-dnscrypt.cc | 1 - pdns/dnsdistdist/dnsdist-doh-common.hh | 1 - pdns/dnsdistdist/dnsdist-dynblocks.hh | 1 - pdns/dnsdistdist/dnsdist-dynbpf.cc | 1 - pdns/dnsdistdist/dnsdist-dynbpf.hh | 1 - pdns/dnsdistdist/dnsdist-ecs.cc | 1 - pdns/dnsdistdist/dnsdist-ecs.hh | 1 - pdns/dnsdistdist/dnsdist-idstate.hh | 1 - pdns/dnsdistdist/dnsdist-lbpolicies.hh | 1 - pdns/dnsdistdist/dnsdist-lua-actions.cc | 1 - pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc | 1 - pdns/dnsdistdist/dnsdist-lua-bindings.cc | 1 - pdns/dnsdistdist/dnsdist-lua-inspection.cc | 1 - pdns/dnsdistdist/dnsdist-lua-rules.cc | 1 - pdns/dnsdistdist/dnsdist-lua-vars.cc | 1 - pdns/dnsdistdist/dnsdist-lua.cc | 1 - pdns/dnsdistdist/dnsdist-lua.hh | 1 - pdns/dnsdistdist/dnsdist-protobuf.cc | 1 - pdns/dnsdistdist/dnsdist-protobuf.hh | 1 - pdns/dnsdistdist/dnsdist-protocols.cc | 1 - pdns/dnsdistdist/dnsdist-protocols.hh | 1 - pdns/dnsdistdist/dnsdist-rings.cc | 1 - pdns/dnsdistdist/dnsdist-rings.hh | 1 - pdns/dnsdistdist/dnsdist-snmp.cc | 1 - pdns/dnsdistdist/dnsdist-snmp.hh | 1 - pdns/dnsdistdist/dnsdist-tcp.cc | 1 - pdns/dnsdistdist/dnsdist-web.cc | 1 - pdns/dnsdistdist/dnsdist-xpf.cc | 1 - pdns/dnsdistdist/dnsdist-xpf.hh | 1 - pdns/dnsdistdist/dnsdist.cc | 1 - pdns/dnsdistdist/dnsdist.hh | 1 - pdns/dnsdistdist/test-dnsdist_cc.cc | 1 - pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc | 1 - 38 files changed, 38 deletions(-) delete mode 120000 pdns/dnsdistdist/dnsdist-cache.cc delete mode 120000 pdns/dnsdistdist/dnsdist-cache.hh delete mode 120000 pdns/dnsdistdist/dnsdist-carbon.cc delete mode 120000 pdns/dnsdistdist/dnsdist-console.cc delete mode 120000 pdns/dnsdistdist/dnsdist-console.hh delete mode 120000 pdns/dnsdistdist/dnsdist-dnscrypt.cc delete mode 120000 pdns/dnsdistdist/dnsdist-doh-common.hh delete mode 120000 pdns/dnsdistdist/dnsdist-dynblocks.hh delete mode 120000 pdns/dnsdistdist/dnsdist-dynbpf.cc delete mode 120000 pdns/dnsdistdist/dnsdist-dynbpf.hh delete mode 120000 pdns/dnsdistdist/dnsdist-ecs.cc delete mode 120000 pdns/dnsdistdist/dnsdist-ecs.hh delete mode 120000 pdns/dnsdistdist/dnsdist-idstate.hh delete mode 120000 pdns/dnsdistdist/dnsdist-lbpolicies.hh delete mode 120000 pdns/dnsdistdist/dnsdist-lua-actions.cc delete mode 120000 pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc delete mode 120000 pdns/dnsdistdist/dnsdist-lua-bindings.cc delete mode 120000 pdns/dnsdistdist/dnsdist-lua-inspection.cc delete mode 120000 pdns/dnsdistdist/dnsdist-lua-rules.cc delete mode 120000 pdns/dnsdistdist/dnsdist-lua-vars.cc delete mode 120000 pdns/dnsdistdist/dnsdist-lua.cc delete mode 120000 pdns/dnsdistdist/dnsdist-lua.hh delete mode 120000 pdns/dnsdistdist/dnsdist-protobuf.cc delete mode 120000 pdns/dnsdistdist/dnsdist-protobuf.hh delete mode 120000 pdns/dnsdistdist/dnsdist-protocols.cc delete mode 120000 pdns/dnsdistdist/dnsdist-protocols.hh delete mode 120000 pdns/dnsdistdist/dnsdist-rings.cc delete mode 120000 pdns/dnsdistdist/dnsdist-rings.hh delete mode 120000 pdns/dnsdistdist/dnsdist-snmp.cc delete mode 120000 pdns/dnsdistdist/dnsdist-snmp.hh delete mode 120000 pdns/dnsdistdist/dnsdist-tcp.cc delete mode 120000 pdns/dnsdistdist/dnsdist-web.cc delete mode 120000 pdns/dnsdistdist/dnsdist-xpf.cc delete mode 120000 pdns/dnsdistdist/dnsdist-xpf.hh delete mode 120000 pdns/dnsdistdist/dnsdist.cc delete mode 120000 pdns/dnsdistdist/dnsdist.hh delete mode 120000 pdns/dnsdistdist/test-dnsdist_cc.cc delete mode 120000 pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc diff --git a/pdns/dnsdistdist/dnsdist-cache.cc b/pdns/dnsdistdist/dnsdist-cache.cc deleted file mode 120000 index 9730d7198b60..000000000000 --- a/pdns/dnsdistdist/dnsdist-cache.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-cache.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-cache.hh b/pdns/dnsdistdist/dnsdist-cache.hh deleted file mode 120000 index 84794d806927..000000000000 --- a/pdns/dnsdistdist/dnsdist-cache.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-cache.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-carbon.cc b/pdns/dnsdistdist/dnsdist-carbon.cc deleted file mode 120000 index dce7a30b311e..000000000000 --- a/pdns/dnsdistdist/dnsdist-carbon.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-carbon.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-console.cc b/pdns/dnsdistdist/dnsdist-console.cc deleted file mode 120000 index 402fcdc9d8c2..000000000000 --- a/pdns/dnsdistdist/dnsdist-console.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-console.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-console.hh b/pdns/dnsdistdist/dnsdist-console.hh deleted file mode 120000 index c92b2ad52737..000000000000 --- a/pdns/dnsdistdist/dnsdist-console.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-console.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-dnscrypt.cc b/pdns/dnsdistdist/dnsdist-dnscrypt.cc deleted file mode 120000 index 9f90566bff04..000000000000 --- a/pdns/dnsdistdist/dnsdist-dnscrypt.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-dnscrypt.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-doh-common.hh b/pdns/dnsdistdist/dnsdist-doh-common.hh deleted file mode 120000 index 56920844943f..000000000000 --- a/pdns/dnsdistdist/dnsdist-doh-common.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-doh-common.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-dynblocks.hh b/pdns/dnsdistdist/dnsdist-dynblocks.hh deleted file mode 120000 index 73fa1f7f19f3..000000000000 --- a/pdns/dnsdistdist/dnsdist-dynblocks.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-dynblocks.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-dynbpf.cc b/pdns/dnsdistdist/dnsdist-dynbpf.cc deleted file mode 120000 index 6463b56fc709..000000000000 --- a/pdns/dnsdistdist/dnsdist-dynbpf.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-dynbpf.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-dynbpf.hh b/pdns/dnsdistdist/dnsdist-dynbpf.hh deleted file mode 120000 index 9ac055ffc735..000000000000 --- a/pdns/dnsdistdist/dnsdist-dynbpf.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-dynbpf.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-ecs.cc b/pdns/dnsdistdist/dnsdist-ecs.cc deleted file mode 120000 index 9bf0156b00d1..000000000000 --- a/pdns/dnsdistdist/dnsdist-ecs.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-ecs.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-ecs.hh b/pdns/dnsdistdist/dnsdist-ecs.hh deleted file mode 120000 index bbd2156b59e4..000000000000 --- a/pdns/dnsdistdist/dnsdist-ecs.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-ecs.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-idstate.hh b/pdns/dnsdistdist/dnsdist-idstate.hh deleted file mode 120000 index 44f6de43450b..000000000000 --- a/pdns/dnsdistdist/dnsdist-idstate.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-idstate.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-lbpolicies.hh b/pdns/dnsdistdist/dnsdist-lbpolicies.hh deleted file mode 120000 index 020353fc0d8a..000000000000 --- a/pdns/dnsdistdist/dnsdist-lbpolicies.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-lbpolicies.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-lua-actions.cc b/pdns/dnsdistdist/dnsdist-lua-actions.cc deleted file mode 120000 index 7ad46192b336..000000000000 --- a/pdns/dnsdistdist/dnsdist-lua-actions.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-lua-actions.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc b/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc deleted file mode 120000 index 93b217138edc..000000000000 --- a/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-lua-bindings-dnsquestion.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-lua-bindings.cc b/pdns/dnsdistdist/dnsdist-lua-bindings.cc deleted file mode 120000 index 014a4be27466..000000000000 --- a/pdns/dnsdistdist/dnsdist-lua-bindings.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-lua-bindings.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-lua-inspection.cc b/pdns/dnsdistdist/dnsdist-lua-inspection.cc deleted file mode 120000 index ae053d658a0f..000000000000 --- a/pdns/dnsdistdist/dnsdist-lua-inspection.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-lua-inspection.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-lua-rules.cc b/pdns/dnsdistdist/dnsdist-lua-rules.cc deleted file mode 120000 index d01f6e223220..000000000000 --- a/pdns/dnsdistdist/dnsdist-lua-rules.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-lua-rules.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-lua-vars.cc b/pdns/dnsdistdist/dnsdist-lua-vars.cc deleted file mode 120000 index ed3c358ea43e..000000000000 --- a/pdns/dnsdistdist/dnsdist-lua-vars.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-lua-vars.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-lua.cc b/pdns/dnsdistdist/dnsdist-lua.cc deleted file mode 120000 index d3eb31e6bad7..000000000000 --- a/pdns/dnsdistdist/dnsdist-lua.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-lua.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-lua.hh b/pdns/dnsdistdist/dnsdist-lua.hh deleted file mode 120000 index fab25c4c0c94..000000000000 --- a/pdns/dnsdistdist/dnsdist-lua.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-lua.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-protobuf.cc b/pdns/dnsdistdist/dnsdist-protobuf.cc deleted file mode 120000 index a10089548ebf..000000000000 --- a/pdns/dnsdistdist/dnsdist-protobuf.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-protobuf.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-protobuf.hh b/pdns/dnsdistdist/dnsdist-protobuf.hh deleted file mode 120000 index dd11fbf3db31..000000000000 --- a/pdns/dnsdistdist/dnsdist-protobuf.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-protobuf.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-protocols.cc b/pdns/dnsdistdist/dnsdist-protocols.cc deleted file mode 120000 index eb08cd3869eb..000000000000 --- a/pdns/dnsdistdist/dnsdist-protocols.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-protocols.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-protocols.hh b/pdns/dnsdistdist/dnsdist-protocols.hh deleted file mode 120000 index cb9d2fd79c7b..000000000000 --- a/pdns/dnsdistdist/dnsdist-protocols.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-protocols.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-rings.cc b/pdns/dnsdistdist/dnsdist-rings.cc deleted file mode 120000 index d6e222bea4a4..000000000000 --- a/pdns/dnsdistdist/dnsdist-rings.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-rings.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-rings.hh b/pdns/dnsdistdist/dnsdist-rings.hh deleted file mode 120000 index 4c33d6dbb173..000000000000 --- a/pdns/dnsdistdist/dnsdist-rings.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-rings.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-snmp.cc b/pdns/dnsdistdist/dnsdist-snmp.cc deleted file mode 120000 index 49f9feda64e6..000000000000 --- a/pdns/dnsdistdist/dnsdist-snmp.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-snmp.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-snmp.hh b/pdns/dnsdistdist/dnsdist-snmp.hh deleted file mode 120000 index ffa4710635e2..000000000000 --- a/pdns/dnsdistdist/dnsdist-snmp.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-snmp.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-tcp.cc b/pdns/dnsdistdist/dnsdist-tcp.cc deleted file mode 120000 index 58e398a5a0b3..000000000000 --- a/pdns/dnsdistdist/dnsdist-tcp.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-tcp.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-web.cc b/pdns/dnsdistdist/dnsdist-web.cc deleted file mode 120000 index 062182f6d4ee..000000000000 --- a/pdns/dnsdistdist/dnsdist-web.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-web.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-xpf.cc b/pdns/dnsdistdist/dnsdist-xpf.cc deleted file mode 120000 index 66fd88d61623..000000000000 --- a/pdns/dnsdistdist/dnsdist-xpf.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-xpf.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist-xpf.hh b/pdns/dnsdistdist/dnsdist-xpf.hh deleted file mode 120000 index c2b75e2df4ef..000000000000 --- a/pdns/dnsdistdist/dnsdist-xpf.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist-xpf.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist.cc b/pdns/dnsdistdist/dnsdist.cc deleted file mode 120000 index dc104b27f9f1..000000000000 --- a/pdns/dnsdistdist/dnsdist.cc +++ /dev/null @@ -1 +0,0 @@ -../dnsdist.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/dnsdist.hh b/pdns/dnsdistdist/dnsdist.hh deleted file mode 120000 index 2a87e4f9d67d..000000000000 --- a/pdns/dnsdistdist/dnsdist.hh +++ /dev/null @@ -1 +0,0 @@ -../dnsdist.hh \ No newline at end of file diff --git a/pdns/dnsdistdist/test-dnsdist_cc.cc b/pdns/dnsdistdist/test-dnsdist_cc.cc deleted file mode 120000 index ae06da2233d4..000000000000 --- a/pdns/dnsdistdist/test-dnsdist_cc.cc +++ /dev/null @@ -1 +0,0 @@ -../test-dnsdist_cc.cc \ No newline at end of file diff --git a/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc b/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc deleted file mode 120000 index dde3be0e38d4..000000000000 --- a/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc +++ /dev/null @@ -1 +0,0 @@ -../test-dnsdistpacketcache_cc.cc \ No newline at end of file From 9b1ac0cda17da08bd3d4731ce3a3b3325ae0ed74 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 11:09:14 +0100 Subject: [PATCH 02/25] dnsdist: Move dnsdist-specific files --- pdns/{ => dnsdistdist}/dnsdist-cache.cc | 0 pdns/{ => dnsdistdist}/dnsdist-cache.hh | 0 pdns/{ => dnsdistdist}/dnsdist-carbon.cc | 0 pdns/{ => dnsdistdist}/dnsdist-console.cc | 0 pdns/{ => dnsdistdist}/dnsdist-console.hh | 0 pdns/{ => dnsdistdist}/dnsdist-dnscrypt.cc | 0 pdns/{ => dnsdistdist}/dnsdist-doh-common.hh | 0 pdns/{ => dnsdistdist}/dnsdist-dynblocks.hh | 0 pdns/{ => dnsdistdist}/dnsdist-dynbpf.cc | 0 pdns/{ => dnsdistdist}/dnsdist-dynbpf.hh | 0 pdns/{ => dnsdistdist}/dnsdist-ecs.cc | 0 pdns/{ => dnsdistdist}/dnsdist-ecs.hh | 0 pdns/{ => dnsdistdist}/dnsdist-idstate.hh | 0 pdns/{ => dnsdistdist}/dnsdist-lbpolicies.hh | 0 pdns/{ => dnsdistdist}/dnsdist-lua-actions.cc | 0 pdns/{ => dnsdistdist}/dnsdist-lua-bindings-dnsquestion.cc | 0 pdns/{ => dnsdistdist}/dnsdist-lua-bindings.cc | 0 pdns/{ => dnsdistdist}/dnsdist-lua-inspection.cc | 0 pdns/{ => dnsdistdist}/dnsdist-lua-rules.cc | 0 pdns/{ => dnsdistdist}/dnsdist-lua-vars.cc | 0 pdns/{ => dnsdistdist}/dnsdist-lua.cc | 0 pdns/{ => dnsdistdist}/dnsdist-lua.hh | 0 pdns/{ => dnsdistdist}/dnsdist-protobuf.cc | 0 pdns/{ => dnsdistdist}/dnsdist-protobuf.hh | 0 pdns/{ => dnsdistdist}/dnsdist-protocols.cc | 0 pdns/{ => dnsdistdist}/dnsdist-protocols.hh | 0 pdns/{ => dnsdistdist}/dnsdist-rings.cc | 0 pdns/{ => dnsdistdist}/dnsdist-rings.hh | 0 pdns/{ => dnsdistdist}/dnsdist-snmp.cc | 0 pdns/{ => dnsdistdist}/dnsdist-snmp.hh | 0 pdns/{ => dnsdistdist}/dnsdist-tcp.cc | 0 pdns/{ => dnsdistdist}/dnsdist-web.cc | 0 pdns/{ => dnsdistdist}/dnsdist-xpf.cc | 0 pdns/{ => dnsdistdist}/dnsdist-xpf.hh | 0 pdns/{ => dnsdistdist}/dnsdist.cc | 0 pdns/{ => dnsdistdist}/dnsdist.hh | 0 pdns/{ => dnsdistdist}/test-dnsdist_cc.cc | 0 pdns/{ => dnsdistdist}/test-dnsdistpacketcache_cc.cc | 0 38 files changed, 0 insertions(+), 0 deletions(-) rename pdns/{ => dnsdistdist}/dnsdist-cache.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-cache.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-carbon.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-console.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-console.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-dnscrypt.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-doh-common.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-dynblocks.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-dynbpf.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-dynbpf.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-ecs.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-ecs.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-idstate.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-lbpolicies.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-lua-actions.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-lua-bindings-dnsquestion.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-lua-bindings.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-lua-inspection.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-lua-rules.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-lua-vars.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-lua.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-lua.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-protobuf.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-protobuf.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-protocols.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-protocols.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-rings.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-rings.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-snmp.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-snmp.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist-tcp.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-web.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-xpf.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist-xpf.hh (100%) rename pdns/{ => dnsdistdist}/dnsdist.cc (100%) rename pdns/{ => dnsdistdist}/dnsdist.hh (100%) rename pdns/{ => dnsdistdist}/test-dnsdist_cc.cc (100%) rename pdns/{ => dnsdistdist}/test-dnsdistpacketcache_cc.cc (100%) diff --git a/pdns/dnsdist-cache.cc b/pdns/dnsdistdist/dnsdist-cache.cc similarity index 100% rename from pdns/dnsdist-cache.cc rename to pdns/dnsdistdist/dnsdist-cache.cc diff --git a/pdns/dnsdist-cache.hh b/pdns/dnsdistdist/dnsdist-cache.hh similarity index 100% rename from pdns/dnsdist-cache.hh rename to pdns/dnsdistdist/dnsdist-cache.hh diff --git a/pdns/dnsdist-carbon.cc b/pdns/dnsdistdist/dnsdist-carbon.cc similarity index 100% rename from pdns/dnsdist-carbon.cc rename to pdns/dnsdistdist/dnsdist-carbon.cc diff --git a/pdns/dnsdist-console.cc b/pdns/dnsdistdist/dnsdist-console.cc similarity index 100% rename from pdns/dnsdist-console.cc rename to pdns/dnsdistdist/dnsdist-console.cc diff --git a/pdns/dnsdist-console.hh b/pdns/dnsdistdist/dnsdist-console.hh similarity index 100% rename from pdns/dnsdist-console.hh rename to pdns/dnsdistdist/dnsdist-console.hh diff --git a/pdns/dnsdist-dnscrypt.cc b/pdns/dnsdistdist/dnsdist-dnscrypt.cc similarity index 100% rename from pdns/dnsdist-dnscrypt.cc rename to pdns/dnsdistdist/dnsdist-dnscrypt.cc diff --git a/pdns/dnsdist-doh-common.hh b/pdns/dnsdistdist/dnsdist-doh-common.hh similarity index 100% rename from pdns/dnsdist-doh-common.hh rename to pdns/dnsdistdist/dnsdist-doh-common.hh diff --git a/pdns/dnsdist-dynblocks.hh b/pdns/dnsdistdist/dnsdist-dynblocks.hh similarity index 100% rename from pdns/dnsdist-dynblocks.hh rename to pdns/dnsdistdist/dnsdist-dynblocks.hh diff --git a/pdns/dnsdist-dynbpf.cc b/pdns/dnsdistdist/dnsdist-dynbpf.cc similarity index 100% rename from pdns/dnsdist-dynbpf.cc rename to pdns/dnsdistdist/dnsdist-dynbpf.cc diff --git a/pdns/dnsdist-dynbpf.hh b/pdns/dnsdistdist/dnsdist-dynbpf.hh similarity index 100% rename from pdns/dnsdist-dynbpf.hh rename to pdns/dnsdistdist/dnsdist-dynbpf.hh diff --git a/pdns/dnsdist-ecs.cc b/pdns/dnsdistdist/dnsdist-ecs.cc similarity index 100% rename from pdns/dnsdist-ecs.cc rename to pdns/dnsdistdist/dnsdist-ecs.cc diff --git a/pdns/dnsdist-ecs.hh b/pdns/dnsdistdist/dnsdist-ecs.hh similarity index 100% rename from pdns/dnsdist-ecs.hh rename to pdns/dnsdistdist/dnsdist-ecs.hh diff --git a/pdns/dnsdist-idstate.hh b/pdns/dnsdistdist/dnsdist-idstate.hh similarity index 100% rename from pdns/dnsdist-idstate.hh rename to pdns/dnsdistdist/dnsdist-idstate.hh diff --git a/pdns/dnsdist-lbpolicies.hh b/pdns/dnsdistdist/dnsdist-lbpolicies.hh similarity index 100% rename from pdns/dnsdist-lbpolicies.hh rename to pdns/dnsdistdist/dnsdist-lbpolicies.hh diff --git a/pdns/dnsdist-lua-actions.cc b/pdns/dnsdistdist/dnsdist-lua-actions.cc similarity index 100% rename from pdns/dnsdist-lua-actions.cc rename to pdns/dnsdistdist/dnsdist-lua-actions.cc diff --git a/pdns/dnsdist-lua-bindings-dnsquestion.cc b/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc similarity index 100% rename from pdns/dnsdist-lua-bindings-dnsquestion.cc rename to pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc diff --git a/pdns/dnsdist-lua-bindings.cc b/pdns/dnsdistdist/dnsdist-lua-bindings.cc similarity index 100% rename from pdns/dnsdist-lua-bindings.cc rename to pdns/dnsdistdist/dnsdist-lua-bindings.cc diff --git a/pdns/dnsdist-lua-inspection.cc b/pdns/dnsdistdist/dnsdist-lua-inspection.cc similarity index 100% rename from pdns/dnsdist-lua-inspection.cc rename to pdns/dnsdistdist/dnsdist-lua-inspection.cc diff --git a/pdns/dnsdist-lua-rules.cc b/pdns/dnsdistdist/dnsdist-lua-rules.cc similarity index 100% rename from pdns/dnsdist-lua-rules.cc rename to pdns/dnsdistdist/dnsdist-lua-rules.cc diff --git a/pdns/dnsdist-lua-vars.cc b/pdns/dnsdistdist/dnsdist-lua-vars.cc similarity index 100% rename from pdns/dnsdist-lua-vars.cc rename to pdns/dnsdistdist/dnsdist-lua-vars.cc diff --git a/pdns/dnsdist-lua.cc b/pdns/dnsdistdist/dnsdist-lua.cc similarity index 100% rename from pdns/dnsdist-lua.cc rename to pdns/dnsdistdist/dnsdist-lua.cc diff --git a/pdns/dnsdist-lua.hh b/pdns/dnsdistdist/dnsdist-lua.hh similarity index 100% rename from pdns/dnsdist-lua.hh rename to pdns/dnsdistdist/dnsdist-lua.hh diff --git a/pdns/dnsdist-protobuf.cc b/pdns/dnsdistdist/dnsdist-protobuf.cc similarity index 100% rename from pdns/dnsdist-protobuf.cc rename to pdns/dnsdistdist/dnsdist-protobuf.cc diff --git a/pdns/dnsdist-protobuf.hh b/pdns/dnsdistdist/dnsdist-protobuf.hh similarity index 100% rename from pdns/dnsdist-protobuf.hh rename to pdns/dnsdistdist/dnsdist-protobuf.hh diff --git a/pdns/dnsdist-protocols.cc b/pdns/dnsdistdist/dnsdist-protocols.cc similarity index 100% rename from pdns/dnsdist-protocols.cc rename to pdns/dnsdistdist/dnsdist-protocols.cc diff --git a/pdns/dnsdist-protocols.hh b/pdns/dnsdistdist/dnsdist-protocols.hh similarity index 100% rename from pdns/dnsdist-protocols.hh rename to pdns/dnsdistdist/dnsdist-protocols.hh diff --git a/pdns/dnsdist-rings.cc b/pdns/dnsdistdist/dnsdist-rings.cc similarity index 100% rename from pdns/dnsdist-rings.cc rename to pdns/dnsdistdist/dnsdist-rings.cc diff --git a/pdns/dnsdist-rings.hh b/pdns/dnsdistdist/dnsdist-rings.hh similarity index 100% rename from pdns/dnsdist-rings.hh rename to pdns/dnsdistdist/dnsdist-rings.hh diff --git a/pdns/dnsdist-snmp.cc b/pdns/dnsdistdist/dnsdist-snmp.cc similarity index 100% rename from pdns/dnsdist-snmp.cc rename to pdns/dnsdistdist/dnsdist-snmp.cc diff --git a/pdns/dnsdist-snmp.hh b/pdns/dnsdistdist/dnsdist-snmp.hh similarity index 100% rename from pdns/dnsdist-snmp.hh rename to pdns/dnsdistdist/dnsdist-snmp.hh diff --git a/pdns/dnsdist-tcp.cc b/pdns/dnsdistdist/dnsdist-tcp.cc similarity index 100% rename from pdns/dnsdist-tcp.cc rename to pdns/dnsdistdist/dnsdist-tcp.cc diff --git a/pdns/dnsdist-web.cc b/pdns/dnsdistdist/dnsdist-web.cc similarity index 100% rename from pdns/dnsdist-web.cc rename to pdns/dnsdistdist/dnsdist-web.cc diff --git a/pdns/dnsdist-xpf.cc b/pdns/dnsdistdist/dnsdist-xpf.cc similarity index 100% rename from pdns/dnsdist-xpf.cc rename to pdns/dnsdistdist/dnsdist-xpf.cc diff --git a/pdns/dnsdist-xpf.hh b/pdns/dnsdistdist/dnsdist-xpf.hh similarity index 100% rename from pdns/dnsdist-xpf.hh rename to pdns/dnsdistdist/dnsdist-xpf.hh diff --git a/pdns/dnsdist.cc b/pdns/dnsdistdist/dnsdist.cc similarity index 100% rename from pdns/dnsdist.cc rename to pdns/dnsdistdist/dnsdist.cc diff --git a/pdns/dnsdist.hh b/pdns/dnsdistdist/dnsdist.hh similarity index 100% rename from pdns/dnsdist.hh rename to pdns/dnsdistdist/dnsdist.hh diff --git a/pdns/test-dnsdist_cc.cc b/pdns/dnsdistdist/test-dnsdist_cc.cc similarity index 100% rename from pdns/test-dnsdist_cc.cc rename to pdns/dnsdistdist/test-dnsdist_cc.cc diff --git a/pdns/test-dnsdistpacketcache_cc.cc b/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc similarity index 100% rename from pdns/test-dnsdistpacketcache_cc.cc rename to pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc From 086114d52965c6d0334f46617c2964ff71db2642 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 11:17:46 +0100 Subject: [PATCH 03/25] dnsdist: Format moved files --- .not-formatted | 27 - pdns/dnsdistdist/dnsdist-cache.cc | 33 +- pdns/dnsdistdist/dnsdist-cache.hh | 11 +- pdns/dnsdistdist/dnsdist-console.cc | 869 ++++++------- pdns/dnsdistdist/dnsdist-console.hh | 8 +- pdns/dnsdistdist/dnsdist-dynbpf.cc | 8 +- pdns/dnsdistdist/dnsdist-dynbpf.hh | 19 +- pdns/dnsdistdist/dnsdist-ecs.cc | 146 ++- pdns/dnsdistdist/dnsdist-ecs.hh | 9 +- pdns/dnsdistdist/dnsdist-lbpolicies.hh | 15 +- .../dnsdist-lua-bindings-dnsquestion.cc | 631 ++++----- pdns/dnsdistdist/dnsdist-lua-bindings.cc | 929 ++++++------- pdns/dnsdistdist/dnsdist-lua-inspection.cc | 1147 ++++++++--------- pdns/dnsdistdist/dnsdist-lua-rules.cc | 476 +++---- pdns/dnsdistdist/dnsdist-lua-vars.cc | 97 +- pdns/dnsdistdist/dnsdist-lua.hh | 50 +- pdns/dnsdistdist/dnsdist-rings.cc | 42 +- pdns/dnsdistdist/dnsdist-rings.hh | 10 +- pdns/dnsdistdist/dnsdist-snmp.cc | 182 ++- pdns/dnsdistdist/dnsdist-snmp.hh | 4 +- pdns/dnsdistdist/dnsdist-web.cc | 640 +++++---- pdns/dnsdistdist/dnsdist-xpf.cc | 2 +- pdns/dnsdistdist/dnsdist-xpf.hh | 1 - pdns/dnsdistdist/dnsdist.cc | 577 ++++----- pdns/dnsdistdist/dnsdist.hh | 195 ++- pdns/dnsdistdist/test-dnsdist_cc.cc | 151 ++- pdns/dnsdistdist/test-dnsdistnghttp2-in_cc.cc | 10 +- .../dnsdistdist/test-dnsdistpacketcache_cc.cc | 118 +- 28 files changed, 3221 insertions(+), 3186 deletions(-) diff --git a/.not-formatted b/.not-formatted index 759460e7fd5b..050ad15f107f 100644 --- a/.not-formatted +++ b/.not-formatted @@ -36,31 +36,6 @@ ./pdns/dnscrypt.cc ./pdns/dnscrypt.hh ./pdns/dnsdemog.cc -./pdns/dnsdist-cache.cc -./pdns/dnsdist-cache.hh -./pdns/dnsdist-console.cc -./pdns/dnsdist-console.hh -./pdns/dnsdist-dynbpf.cc -./pdns/dnsdist-dynbpf.hh -./pdns/dnsdist-ecs.cc -./pdns/dnsdist-ecs.hh -./pdns/dnsdist-lbpolicies.hh -./pdns/dnsdist-lua-bindings-dnsquestion.cc -./pdns/dnsdist-lua-bindings.cc -./pdns/dnsdist-lua-inspection.cc -./pdns/dnsdist-lua-rules.cc -./pdns/dnsdist-lua-vars.cc -./pdns/dnsdist-lua.hh -./pdns/dnsdist-rings.cc -./pdns/dnsdist-rings.hh -./pdns/dnsdist-snmp.cc -./pdns/dnsdist-snmp.hh -./pdns/dnsdist-tcp.cc -./pdns/dnsdist-web.cc -./pdns/dnsdist-xpf.cc -./pdns/dnsdist-xpf.hh -./pdns/dnsdist.cc -./pdns/dnsdist.hh ./pdns/dnsdistdist/connection-management.hh ./pdns/dnsdistdist/dnsdist-backend.cc ./pdns/dnsdistdist/dnsdist-kvs.cc @@ -232,8 +207,6 @@ ./pdns/test-common.hh ./pdns/test-distributor_hh.cc ./pdns/test-dnscrypt_cc.cc -./pdns/test-dnsdist_cc.cc -./pdns/test-dnsdistpacketcache_cc.cc ./pdns/test-dnsname_cc.cc ./pdns/test-dnsparser_cc.cc ./pdns/test-dnsparser_hh.cc diff --git a/pdns/dnsdistdist/dnsdist-cache.cc b/pdns/dnsdistdist/dnsdist-cache.cc index c3b0e75ef68d..62d84b7d631b 100644 --- a/pdns/dnsdistdist/dnsdist-cache.cc +++ b/pdns/dnsdistdist/dnsdist-cache.cc @@ -29,7 +29,8 @@ #include "ednssubnet.hh" #include "packetcache.hh" -DNSDistPacketCache::DNSDistPacketCache(size_t maxEntries, uint32_t maxTTL, uint32_t minTTL, uint32_t tempFailureTTL, uint32_t maxNegativeTTL, uint32_t staleTTL, bool dontAge, uint32_t shards, bool deferrableInsertLock, bool parseECS): d_maxEntries(maxEntries), d_shardCount(shards), d_maxTTL(maxTTL), d_tempFailureTTL(tempFailureTTL), d_maxNegativeTTL(maxNegativeTTL), d_minTTL(minTTL), d_staleTTL(staleTTL), d_dontAge(dontAge), d_deferrableInsertLock(deferrableInsertLock), d_parseECS(parseECS) +DNSDistPacketCache::DNSDistPacketCache(size_t maxEntries, uint32_t maxTTL, uint32_t minTTL, uint32_t tempFailureTTL, uint32_t maxNegativeTTL, uint32_t staleTTL, bool dontAge, uint32_t shards, bool deferrableInsertLock, bool parseECS) : + d_maxEntries(maxEntries), d_shardCount(shards), d_maxTTL(maxTTL), d_tempFailureTTL(tempFailureTTL), d_maxNegativeTTL(maxNegativeTTL), d_minTTL(minTTL), d_staleTTL(staleTTL), d_dontAge(dontAge), d_deferrableInsertLock(deferrableInsertLock), d_parseECS(parseECS) { if (d_maxEntries == 0) { throw std::runtime_error("Trying to create a 0-sized packet-cache"); @@ -83,14 +84,14 @@ bool DNSDistPacketCache::cachedValueMatches(const CacheValue& cachedValue, uint1 return true; } -void DNSDistPacketCache::insertLocked(CacheShard& shard, std::unordered_map& map, uint32_t key, CacheValue& newValue) +void DNSDistPacketCache::insertLocked(CacheShard& shard, std::unordered_map& map, uint32_t key, CacheValue& newValue) { /* check again now that we hold the lock to prevent a race */ if (map.size() >= (d_maxEntries / d_shardCount)) { return; } - std::unordered_map::iterator it; + std::unordered_map::iterator it; bool result; std::tie(it, result) = map.insert({key, newValue}); @@ -227,7 +228,7 @@ bool DNSDistPacketCache::get(DNSQuestion& dq, uint16_t queryId, uint32_t* keyOut return false; } - std::unordered_map::const_iterator it = map->find(key); + std::unordered_map::const_iterator it = map->find(key); if (it == map->end()) { if (recordMiss) { ++d_misses; @@ -298,7 +299,7 @@ bool DNSDistPacketCache::get(DNSQuestion& dq, uint16_t queryId, uint32_t* keyOut if (!stale) { // coverity[store_truncates_time_t] dnsheader_aligned dh_aligned(response.data()); - ageDNSPacket(reinterpret_cast(&response[0]), response.size(), age, dh_aligned); + ageDNSPacket(reinterpret_cast(&response[0]), response.size(), age, dh_aligned); } else { editDNSPacketTTL(reinterpret_cast(&response[0]), response.size(), @@ -330,7 +331,7 @@ size_t DNSDistPacketCache::purgeExpired(size_t upTo, const time_t now) size_t toRemove = map->size() - maxPerShard; - for (auto it = map->begin(); toRemove > 0 && it != map->end(); ) { + for (auto it = map->begin(); toRemove > 0 && it != map->end();) { const CacheValue& value = it->second; if (value.validity <= now) { @@ -338,7 +339,8 @@ size_t DNSDistPacketCache::purgeExpired(size_t upTo, const time_t now) --toRemove; --shard.d_entriesCount; ++removed; - } else { + } + else { ++it; } } @@ -393,14 +395,15 @@ size_t DNSDistPacketCache::expungeByName(const DNSName& name, uint16_t qtype, bo for (auto& shard : d_shards) { auto map = shard.d_map.write_lock(); - for(auto it = map->begin(); it != map->end(); ) { + for (auto it = map->begin(); it != map->end();) { const CacheValue& value = it->second; if ((value.qname == name || (suffixMatch && value.qname.isPartOf(name))) && (qtype == QType::ANY || qtype == value.qtype)) { it = map->erase(it); --shard.d_entriesCount; ++removed; - } else { + } + else { ++it; } } @@ -411,7 +414,7 @@ size_t DNSDistPacketCache::expungeByName(const DNSName& name, uint16_t qtype, bo bool DNSDistPacketCache::isFull() { - return (getSize() >= d_maxEntries); + return (getSize() >= d_maxEntries); } uint64_t DNSDistPacketCache::getSize() @@ -435,11 +438,11 @@ uint32_t DNSDistPacketCache::getKey(const DNSName::string_t& qname, size_t qname uint32_t result = 0; /* skip the query ID */ if (packet.size() < sizeof(dnsheader)) { - throw std::range_error("Computing packet cache key for an invalid packet size (" + std::to_string(packet.size()) +")"); + throw std::range_error("Computing packet cache key for an invalid packet size (" + std::to_string(packet.size()) + ")"); } result = burtle(&packet.at(2), sizeof(dnsheader) - 2, result); - result = burtleCI((const unsigned char*) qname.c_str(), qname.length(), result); + result = burtleCI((const unsigned char*)qname.c_str(), qname.length(), result); if (packet.size() < sizeof(dnsheader) + qnameWireLength) { throw std::range_error("Computing packet cache key for an invalid packet (" + std::to_string(packet.size()) + " < " + std::to_string(sizeof(dnsheader) + qnameWireLength) + ")"); } @@ -452,7 +455,7 @@ uint32_t DNSDistPacketCache::getKey(const DNSName::string_t& qname, size_t qname result = burtle(&packet.at(sizeof(dnsheader) + qnameWireLength), packet.size() - (sizeof(dnsheader) + qnameWireLength), result); } } - result = burtle((const unsigned char*) &receivedOverUDP, sizeof(receivedOverUDP), result); + result = burtle((const unsigned char*)&receivedOverUDP, sizeof(receivedOverUDP), result); return result; } @@ -473,7 +476,7 @@ uint64_t DNSDistPacketCache::getEntriesCount() uint64_t DNSDistPacketCache::dump(int fd) { - auto fp = std::unique_ptr(fdopen(dup(fd), "w"), fclose); + auto fp = std::unique_ptr(fdopen(dup(fd), "w"), fclose); if (fp == nullptr) { return 0; } @@ -499,7 +502,7 @@ uint64_t DNSDistPacketCache::dump(int fd) fprintf(fp.get(), "%s %" PRId64 " %s ; rcode %" PRIu8 ", key %" PRIu32 ", length %" PRIu16 ", received over UDP %d, added %" PRId64 "\n", value.qname.toString().c_str(), static_cast(value.validity - now), QType(value.qtype).toString().c_str(), rcode, entry.first, value.len, value.receivedOverUDP, static_cast(value.added)); } - catch(...) { + catch (...) { fprintf(fp.get(), "; error printing '%s'\n", value.qname.empty() ? "EMPTY" : value.qname.toString().c_str()); } } diff --git a/pdns/dnsdistdist/dnsdist-cache.hh b/pdns/dnsdistdist/dnsdist-cache.hh index 95667bd4cd56..3db5e6ab1ff4 100644 --- a/pdns/dnsdistdist/dnsdist-cache.hh +++ b/pdns/dnsdistdist/dnsdist-cache.hh @@ -35,13 +35,13 @@ struct DNSQuestion; class DNSDistPacketCache : boost::noncopyable { public: - DNSDistPacketCache(size_t maxEntries, uint32_t maxTTL=86400, uint32_t minTTL=0, uint32_t tempFailureTTL=60, uint32_t maxNegativeTTL=3600, uint32_t staleTTL=60, bool dontAge=false, uint32_t shards=1, bool deferrableInsertLock=true, bool parseECS=false); + DNSDistPacketCache(size_t maxEntries, uint32_t maxTTL = 86400, uint32_t minTTL = 0, uint32_t tempFailureTTL = 60, uint32_t maxNegativeTTL = 3600, uint32_t staleTTL = 60, bool dontAge = false, uint32_t shards = 1, bool deferrableInsertLock = true, bool parseECS = false); void insert(uint32_t key, const boost::optional& subnet, uint16_t queryFlags, bool dnssecOK, const DNSName& qname, uint16_t qtype, uint16_t qclass, const PacketBuffer& response, bool receivedOverUDP, uint8_t rcode, boost::optional tempFailureTTL); bool get(DNSQuestion& dq, uint16_t queryId, uint32_t* keyOut, boost::optional& subnet, bool dnssecOK, bool receivedOverUDP, uint32_t allowExpired = 0, bool skipAging = false, bool truncatedOK = true, bool recordMiss = true); size_t purgeExpired(size_t upTo, const time_t now); - size_t expunge(size_t upTo=0); - size_t expungeByName(const DNSName& name, uint16_t qtype=QType::ANY, bool suffixMatch=false); + size_t expunge(size_t upTo = 0); + size_t expungeByName(const DNSName& name, uint16_t qtype = QType::ANY, bool suffixMatch = false); bool isFull(); string toString(); uint64_t getSize(); @@ -89,7 +89,6 @@ public: static bool getClientSubnet(const PacketBuffer& packet, size_t qnameWireLength, boost::optional& subnet); private: - struct CacheValue { time_t getTTD() const { return validity; } @@ -121,13 +120,13 @@ private: d_map.write_lock()->reserve(maxSize); } - SharedLockGuarded> d_map; + SharedLockGuarded> d_map; std::atomic d_entriesCount{0}; }; bool cachedValueMatches(const CacheValue& cachedValue, uint16_t queryFlags, const DNSName& qname, uint16_t qtype, uint16_t qclass, bool receivedOverUDP, bool dnssecOK, const boost::optional& subnet) const; uint32_t getShardIndex(uint32_t key) const; - void insertLocked(CacheShard& shard, std::unordered_map& map, uint32_t key, CacheValue& newValue); + void insertLocked(CacheShard& shard, std::unordered_map& map, uint32_t key, CacheValue& newValue); std::vector d_shards; std::unordered_set d_optionsToSkip{EDNSOptionCode::COOKIE}; diff --git a/pdns/dnsdistdist/dnsdist-console.cc b/pdns/dnsdistdist/dnsdist-console.cc index f40abb3446dc..a175cae26156 100644 --- a/pdns/dnsdistdist/dnsdist-console.cc +++ b/pdns/dnsdistdist/dnsdist-console.cc @@ -27,7 +27,7 @@ #include #ifdef HAVE_LIBEDIT -#if defined (__OpenBSD__) || defined(__NetBSD__) +#if defined(__OpenBSD__) || defined(__NetBSD__) // If this is not undeffed, __attribute__ wil be redefined by /usr/include/readline/rlstdc.h #undef __STRICT_ANSI__ #include @@ -47,7 +47,7 @@ #include "threadname.hh" GlobalStateHolder g_consoleACL; -vector > g_confDelta; +vector> g_confDelta; std::string g_consoleKey; bool g_logConsoleConnections{true}; bool g_consoleEnabled{false}; @@ -58,13 +58,15 @@ static ConcurrentConnectionManager s_connManager(100); class ConsoleConnection { public: - ConsoleConnection(const ComboAddress& client, FDWrapper&& fileDesc): d_client(client), d_fileDesc(std::move(fileDesc)) + ConsoleConnection(const ComboAddress& client, FDWrapper&& fileDesc) : + d_client(client), d_fileDesc(std::move(fileDesc)) { if (!s_connManager.registerConnection()) { throw std::runtime_error("Too many concurrent console connections"); } } - ConsoleConnection(ConsoleConnection&& rhs) noexcept: d_client(rhs.d_client), d_fileDesc(std::move(rhs.d_fileDesc)) + ConsoleConnection(ConsoleConnection&& rhs) noexcept : + d_client(rhs.d_client), d_fileDesc(std::move(rhs.d_fileDesc)) { } @@ -111,17 +113,17 @@ static void feedConfigDelta(const std::string& line) } #ifdef HAVE_LIBEDIT -static string historyFile(const bool &ignoreHOME = false) +static string historyFile(const bool& ignoreHOME = false) { string ret; passwd pwd{}; - passwd *result{nullptr}; + passwd* result{nullptr}; std::array buf{}; getpwuid_r(geteuid(), &pwd, buf.data(), buf.size(), &result); // NOLINTNEXTLINE(concurrency-mt-unsafe): we are not modifying the environment - const char *homedir = getenv("HOME"); + const char* homedir = getenv("HOME"); if (result != nullptr) { ret = string(pwd.pw_dir); } @@ -136,7 +138,8 @@ static string historyFile(const bool &ignoreHOME = false) } #endif /* HAVE_LIBEDIT */ -enum class ConsoleCommandResult : uint8_t { +enum class ConsoleCommandResult : uint8_t +{ Valid = 0, ConnectionClosed, TooLarge @@ -166,13 +169,12 @@ static ConsoleCommandResult getMsgLen32(int fileDesc, uint32_t* len) static bool putMsgLen32(int fileDesc, uint32_t len) { - try - { + try { uint32_t raw = htonl(len); size_t ret = writen2(fileDesc, &raw, sizeof raw); return ret == sizeof raw; } - catch(...) { + catch (...) { return false; } } @@ -182,7 +184,7 @@ static ConsoleCommandResult sendMessageToServer(int fileDesc, const std::string& string msg = dnsdist::crypto::authenticated::encryptSym(line, g_consoleKey, writingNonce); const auto msgLen = msg.length(); if (msgLen > std::numeric_limits::max()) { - cerr << "Encrypted message is too long to be sent to the server, "<< std::to_string(msgLen) << " > " << std::numeric_limits::max() << endl; + cerr << "Encrypted message is too long to be sent to the server, " << std::to_string(msgLen) << " > " << std::numeric_limits::max() << endl; return ConsoleCommandResult::TooLarge; } @@ -229,12 +231,12 @@ void doClient(ComboAddress server, const std::string& command) } if (g_verbose) { - cout<<"Connecting to "< "); - rl_bind_key('\t',rl_complete); + rl_bind_key('\t', rl_complete); if (sline == nullptr) { break; } @@ -288,7 +290,7 @@ void doClient(ComboAddress server, const std::string& command) string line(sline); if (!line.empty() && line != lastline) { add_history(sline); - history << sline < getNextConsoleLine(ofstream& history, std::str string line(sline); if (!line.empty() && line != lastline) { add_history(sline); - history << sline <, ClientState*, - std::unordered_map - > - > - >(withReturn ? ("return "+*line) : *line); + std::unordered_map>>>(withReturn ? ("return " + *line) : *line); if (ret) { if (const auto* dsValue = boost::get>(&*ret)) { if (*dsValue) { - cout<<(*dsValue)->getName()<getName() << endl; } } else if (const auto* csValue = boost::get(&*ret)) { if (*csValue != nullptr) { - cout<<(*csValue)->local.toStringWithPort()<local.toStringWithPort() << endl; } } else if (const auto* strValue = boost::get(&*ret)) { - cout<<*strValue< >(&*ret)) { + else if (const auto* mapValue = boost::get>(&*ret)) { using namespace json11; Json::object obj; for (const auto& value : *mapValue) { obj[value.first] = value.second; } Json out = obj; - cout< g_consoleKeywords{ +const std::vector g_consoleKeywords +{ /* keyword, function, parameters, description */ - { "addACL", true, "netmask", "add to the ACL set who can use this server" }, - { "addAction", true, R"(DNS rule, DNS action [, {uuid="UUID", name="name"}])", "add a rule" }, - { "addBPFFilterDynBlocks", true, "addresses, dynbpf[[, seconds=10], msg]", "This is the eBPF equivalent of addDynBlocks(), blocking a set of addresses for (optionally) a number of seconds, using an eBPF dynamic filter" }, - { "addCapabilitiesToRetain", true, "capability or list of capabilities", "Linux capabilities to retain after startup, like CAP_BPF" }, - { "addConsoleACL", true, "netmask", "add a netmask to the console ACL" }, - { "addDNSCryptBind", true, R"('127.0.0.1:8443", "provider name", "/path/to/resolver.cert", "/path/to/resolver.key", {reusePort=false, tcpFastOpenQueueSize=0, interface="", cpus={}})", "listen to incoming DNSCrypt queries on 127.0.0.1 port 8443, with a provider name of `provider name`, using a resolver certificate and associated key stored respectively in the `resolver.cert` and `resolver.key` files. The fifth optional parameter is a table of parameters" }, - { "addDOHLocal", true, "addr, certFile, keyFile [, urls [, vars]]", "listen to incoming DNS over HTTPS queries on the specified address using the specified certificate and key. The last two parameters are tables" }, - { "addDOH3Local", true, "addr, certFile, keyFile [, vars]", "listen to incoming DNS over HTTP/3 queries on the specified address using the specified certificate and key. The last parameter is a table" }, - { "addDOQLocal", true, "addr, certFile, keyFile [, vars]", "listen to incoming DNS over QUIC queries on the specified address using the specified certificate and key. The last parameter is a table" }, - { "addDynamicBlock", true, "address, message[, action [, seconds [, clientIPMask [, clientIPPortMask]]]]", "block the supplied address with message `msg`, for `seconds` seconds (10 by default), applying `action` (default to the one set with `setDynBlocksAction()`)" }, - { "addDynBlocks", true, "addresses, message[, seconds[, action]]", "block the set of addresses with message `msg`, for `seconds` seconds (10 by default), applying `action` (default to the one set with `setDynBlocksAction()`)" }, - { "addDynBlockSMT", true, "names, message[, seconds [, action]]", "block the set of names with message `msg`, for `seconds` seconds (10 by default), applying `action` (default to the one set with `setDynBlocksAction()`)" }, - { "addLocal", true, R"(addr [, {doTCP=true, reusePort=false, tcpFastOpenQueueSize=0, interface="", cpus={}}])", "add `addr` to the list of addresses we listen on" }, - { "addCacheHitResponseAction", true, R"(DNS rule, DNS response action [, {uuid="UUID", name="name"}}])", "add a cache hit response rule" }, - { "addCacheInsertedResponseAction", true, R"(DNS rule, DNS response action [, {uuid="UUID", name="name"}}])", "add a cache inserted response rule" }, - { "addMaintenanceCallback", true, "callback", "register a function to be called as part of the maintenance hook, every second" }, - { "addResponseAction", true, R"(DNS rule, DNS response action [, {uuid="UUID", name="name"}}])", "add a response rule" }, - { "addSelfAnsweredResponseAction", true, R"(DNS rule, DNS response action [, {uuid="UUID", name="name"}}])", "add a self-answered response rule" }, - { "addTLSLocal", true, "addr, certFile(s), keyFile(s) [,params]", "listen to incoming DNS over TLS queries on the specified address using the specified certificate (or list of) and key (or list of). The last parameter is a table" }, - { "AllowAction", true, "", "let these packets go through" }, - { "AllowResponseAction", true, "", "let these packets go through" }, - { "AllRule", true, "", "matches all traffic" }, - { "AndRule", true, "list of DNS rules", "matches if all sub-rules matches" }, - { "benchRule", true, "DNS Rule [, iterations [, suffix]]", "bench the specified DNS rule" }, - { "carbonServer", true, "serverIP, [ourname], [interval]", "report statistics to serverIP using our hostname, or 'ourname' if provided, every 'interval' seconds" }, - { "clearConsoleHistory", true, "", "clear the internal (in-memory) history of console commands" }, - { "clearDynBlocks", true, "", "clear all dynamic blocks" }, - { "clearQueryCounters", true, "", "clears the query counter buffer" }, - { "clearRules", true, "", "remove all current rules" }, - { "controlSocket", true, "addr", "open a control socket on this address / connect to this address in client mode" }, - { "ContinueAction", true, "action", "execute the specified action and continue the processing of the remaining rules, regardless of the return of the action" }, - { "declareMetric", true, "name, type, description [, prometheusName]", "Declare a custom metric" }, - { "decMetric", true, "name", "Decrement a custom metric" }, - { "DelayAction", true, "milliseconds", "delay the response by the specified amount of milliseconds (UDP-only)" }, - { "DelayResponseAction", true, "milliseconds", "delay the response by the specified amount of milliseconds (UDP-only)" }, - { "delta", true, "", "shows all commands entered that changed the configuration" }, - { "DNSSECRule", true, "", "matches queries with the DO bit set" }, - { "DnstapLogAction", true, "identity, FrameStreamLogger [, alterFunction]", "send the contents of this query to a FrameStreamLogger or RemoteLogger as dnstap. `alterFunction` is a callback, receiving a DNSQuestion and a DnstapMessage, that can be used to modify the dnstap message" }, - { "DnstapLogResponseAction", true, "identity, FrameStreamLogger [, alterFunction]", "send the contents of this response to a remote or FrameStreamLogger or RemoteLogger as dnstap. `alterFunction` is a callback, receiving a DNSResponse and a DnstapMessage, that can be used to modify the dnstap message" }, - { "DropAction", true, "", "drop these packets" }, - { "DropResponseAction", true, "", "drop these packets" }, - { "DSTPortRule", true, "port", "matches questions received to the destination port specified" }, - { "dumpStats", true, "", "print all statistics we gather" }, - { "dynBlockRulesGroup", true, "", "return a new DynBlockRulesGroup object" }, - { "EDNSVersionRule", true, "version", "matches queries with the specified EDNS version" }, - { "EDNSOptionRule", true, "optcode", "matches queries with the specified EDNS0 option present" }, - { "ERCodeAction", true, "ercode", "Reply immediately by turning the query into a response with the specified EDNS extended rcode" }, - { "ERCodeRule", true, "rcode", "matches responses with the specified extended rcode (EDNS0)" }, - { "exceedNXDOMAINs", true, "rate, seconds", "get set of addresses that exceed `rate` NXDOMAIN/s over `seconds` seconds" }, - { "exceedQRate", true, "rate, seconds", "get set of address that exceed `rate` queries/s over `seconds` seconds" }, - { "exceedQTypeRate", true, "type, rate, seconds", "get set of address that exceed `rate` queries/s for queries of type `type` over `seconds` seconds" }, - { "exceedRespByterate", true, "rate, seconds", "get set of addresses that exceeded `rate` bytes/s answers over `seconds` seconds" }, - { "exceedServFails", true, "rate, seconds", "get set of addresses that exceed `rate` servfails/s over `seconds` seconds" }, - { "firstAvailable", false, "", "picks the server with the lowest `order` that has not exceeded its QPS limit" }, - { "fixupCase", true, "bool", "if set (default to no), rewrite the first qname of the question part of the answer to match the one from the query. It is only useful when you have a downstream server that messes up the case of the question qname in the answer" }, - { "generateDNSCryptCertificate", true, R"("/path/to/providerPrivate.key", "/path/to/resolver.cert", "/path/to/resolver.key", serial, validFrom, validUntil)", "generate a new resolver private key and related certificate, valid from the `validFrom` timestamp until the `validUntil` one, signed with the provider private key" }, - { "generateDNSCryptProviderKeys", true, R"("/path/to/providerPublic.key", "/path/to/providerPrivate.key")", "generate a new provider keypair" }, - { "getAction", true, "n", "Returns the Action associated with rule n" }, - { "getBind", true, "n", "returns the listener at index n" }, - { "getBindCount", true, "", "returns the number of listeners all kinds" }, - { "getCacheHitResponseRule", true, "selector", "Return the cache-hit response rule corresponding to the selector, if any" }, - { "getCacheInsertedResponseRule", true, "selector", "Return the cache-inserted response rule corresponding to the selector, if any" }, - { "getCurrentTime", true, "", "returns the current time" }, - { "getDynamicBlocks", true, "", "returns a table of the current network-based dynamic blocks" }, - { "getDynamicBlocksSMT", true, "", "returns a table of the current suffix-based dynamic blocks" }, - { "getDNSCryptBind", true, "n", "return the `DNSCryptContext` object corresponding to the bind `n`" }, - { "getDNSCryptBindCount", true, "", "returns the number of DNSCrypt listeners" }, - { "getDOHFrontend", true, "n", "returns the DoH frontend with index n" }, - { "getDOHFrontendCount", true, "", "returns the number of DoH listeners" }, - { "getDOH3Frontend", true, "n", "returns the DoH3 frontend with index n" }, - { "getDOH3FrontendCount", true, "", "returns the number of DoH3 listeners" }, - { "getDOQFrontend", true, "n", "returns the DoQ frontend with index n" }, - { "getDOQFrontendCount", true, "", "returns the number of DoQ listeners" }, - { "getListOfAddressesOfNetworkInterface", true, "itf", "returns the list of addresses configured on a given network interface, as strings" }, - { "getListOfNetworkInterfaces", true, "", "returns the list of network interfaces present on the system, as strings" }, - { "getListOfRangesOfNetworkInterface", true, "itf", "returns the list of network ranges configured on a given network interface, as strings" }, - { "getMACAddress", true, "IP addr", "return the link-level address (MAC) corresponding to the supplied neighbour IP address, if known by the kernel" }, - { "getMetric", true, "name", "Get the value of a custom metric" }, - { "getOutgoingTLSSessionCacheSize", true, "", "returns the number of TLS sessions (for outgoing connections) currently cached" }, - { "getPool", true, "name", "return the pool named `name`, or \"\" for the default pool" }, - { "getPoolServers", true, "pool", "return servers part of this pool" }, - { "getPoolNames", true, "", "returns a table with all the pool names" }, - { "getQueryCounters", true, "[max=10]", "show current buffer of query counters, limited by 'max' if provided" }, - { "getResponseRing", true, "", "return the current content of the response ring" }, - { "getResponseRule", true, "selector", "Return the response rule corresponding to the selector, if any" }, - { "getRespRing", true, "", "return the qname/rcode content of the response ring" }, - { "getRule", true, "selector", "Return the rule corresponding to the selector, if any" }, - { "getSelfAnsweredResponseRule", true, "selector", "Return the self-answered response rule corresponding to the selector, if any" }, - { "getServer", true, "id", "returns server with index 'n' or whose uuid matches if 'id' is an UUID string" }, - { "getServers", true, "", "returns a table with all defined servers" }, - { "getStatisticsCounters", true, "", "returns a map of statistic counters" }, - { "getTopCacheHitResponseRules", true, "[top]", "return the `top` cache-hit response rules" }, - { "getTopCacheInsertedResponseRules", true, "[top]", "return the `top` cache-inserted response rules" }, - { "getTopResponseRules", true, "[top]", "return the `top` response rules" }, - { "getTopRules", true, "[top]", "return the `top` rules" }, - { "getTopSelfAnsweredResponseRules", true, "[top]", "return the `top` self-answered response rules" }, - { "getTLSContext", true, "n", "returns the TLS context with index n" }, - { "getTLSFrontend", true, "n", "returns the TLS frontend with index n" }, - { "getTLSFrontendCount", true, "", "returns the number of DoT listeners" }, - { "getVerbose", true, "", "get whether log messages at the verbose level will be logged" }, - { "grepq", true, R"(Netmask|DNS Name|100ms|{"::1", "powerdns.com", "100ms"} [, n] [,options])", "shows the last n queries and responses matching the specified client address or range (Netmask), or the specified DNS Name, or slower than 100ms" }, - { "hashPassword", true, "password [, workFactor]", "Returns a hashed and salted version of the supplied password, usable with 'setWebserverConfig()'"}, - { "HTTPHeaderRule", true, "name, regex", "matches DoH queries with a HTTP header 'name' whose content matches the regular expression 'regex'"}, - { "HTTPPathRegexRule", true, "regex", "matches DoH queries whose HTTP path matches 'regex'"}, - { "HTTPPathRule", true, "path", "matches DoH queries whose HTTP path is an exact match to 'path'"}, - { "HTTPStatusAction", true, "status, reason, body", "return an HTTP response"}, - { "inClientStartup", true, "", "returns true during console client parsing of configuration" }, - { "includeDirectory", true, "path", "include configuration files from `path`" }, - { "incMetric", true, "name", "Increment a custom metric" }, - { "KeyValueLookupKeyQName", true, "[wireFormat]", "Return a new KeyValueLookupKey object that, when passed to KeyValueStoreLookupAction or KeyValueStoreLookupRule, will return the qname of the query, either in wire format (default) or in plain text if 'wireFormat' is false" }, - { "KeyValueLookupKeySourceIP", true, "[v4Mask [, v6Mask [, includePort]]]", "Return a new KeyValueLookupKey object that, when passed to KeyValueStoreLookupAction or KeyValueStoreLookupRule, will return the (possibly bitmasked) source IP of the client in network byte-order." }, - { "KeyValueLookupKeySuffix", true, "[minLabels [,wireFormat]]", "Return a new KeyValueLookupKey object that, when passed to KeyValueStoreLookupAction or KeyValueStoreLookupRule, will return a vector of keys based on the labels of the qname in DNS wire format or plain text" }, - { "KeyValueLookupKeyTag", true, "tag", "Return a new KeyValueLookupKey object that, when passed to KeyValueStoreLookupAction or KeyValueStoreLookupRule, will return the value of the corresponding tag for this query, if it exists" }, - { "KeyValueStoreLookupAction", true, "kvs, lookupKey, destinationTag", "does a lookup into the key value store referenced by 'kvs' using the key returned by 'lookupKey', and storing the result if any into the tag named 'destinationTag'" }, - { "KeyValueStoreRangeLookupAction", true, "kvs, lookupKey, destinationTag", "does a range-based lookup into the key value store referenced by 'kvs' using the key returned by 'lookupKey', and storing the result if any into the tag named 'destinationTag'" }, - { "KeyValueStoreLookupRule", true, "kvs, lookupKey", "matches queries if the key is found in the specified Key Value store" }, - { "KeyValueStoreRangeLookupRule", true, "kvs, lookupKey", "matches queries if the key is found in the specified Key Value store" }, - { "leastOutstanding", false, "", "Send traffic to downstream server with least outstanding queries, with the lowest 'order', and within that the lowest recent latency"}, + {"addACL", true, "netmask", "add to the ACL set who can use this server"}, + {"addAction", true, R"(DNS rule, DNS action [, {uuid="UUID", name="name"}])", "add a rule"}, + {"addBPFFilterDynBlocks", true, "addresses, dynbpf[[, seconds=10], msg]", "This is the eBPF equivalent of addDynBlocks(), blocking a set of addresses for (optionally) a number of seconds, using an eBPF dynamic filter"}, + {"addCapabilitiesToRetain", true, "capability or list of capabilities", "Linux capabilities to retain after startup, like CAP_BPF"}, + {"addConsoleACL", true, "netmask", "add a netmask to the console ACL"}, + {"addDNSCryptBind", true, R"('127.0.0.1:8443", "provider name", "/path/to/resolver.cert", "/path/to/resolver.key", {reusePort=false, tcpFastOpenQueueSize=0, interface="", cpus={}})", "listen to incoming DNSCrypt queries on 127.0.0.1 port 8443, with a provider name of `provider name`, using a resolver certificate and associated key stored respectively in the `resolver.cert` and `resolver.key` files. The fifth optional parameter is a table of parameters"}, + {"addDOHLocal", true, "addr, certFile, keyFile [, urls [, vars]]", "listen to incoming DNS over HTTPS queries on the specified address using the specified certificate and key. The last two parameters are tables"}, + {"addDOH3Local", true, "addr, certFile, keyFile [, vars]", "listen to incoming DNS over HTTP/3 queries on the specified address using the specified certificate and key. The last parameter is a table"}, + {"addDOQLocal", true, "addr, certFile, keyFile [, vars]", "listen to incoming DNS over QUIC queries on the specified address using the specified certificate and key. The last parameter is a table"}, + {"addDynamicBlock", true, "address, message[, action [, seconds [, clientIPMask [, clientIPPortMask]]]]", "block the supplied address with message `msg`, for `seconds` seconds (10 by default), applying `action` (default to the one set with `setDynBlocksAction()`)"}, + {"addDynBlocks", true, "addresses, message[, seconds[, action]]", "block the set of addresses with message `msg`, for `seconds` seconds (10 by default), applying `action` (default to the one set with `setDynBlocksAction()`)"}, + {"addDynBlockSMT", true, "names, message[, seconds [, action]]", "block the set of names with message `msg`, for `seconds` seconds (10 by default), applying `action` (default to the one set with `setDynBlocksAction()`)"}, + {"addLocal", true, R"(addr [, {doTCP=true, reusePort=false, tcpFastOpenQueueSize=0, interface="", cpus={}}])", "add `addr` to the list of addresses we listen on"}, + {"addCacheHitResponseAction", true, R"(DNS rule, DNS response action [, {uuid="UUID", name="name"}}])", "add a cache hit response rule"}, + {"addCacheInsertedResponseAction", true, R"(DNS rule, DNS response action [, {uuid="UUID", name="name"}}])", "add a cache inserted response rule"}, + {"addMaintenanceCallback", true, "callback", "register a function to be called as part of the maintenance hook, every second"}, + {"addResponseAction", true, R"(DNS rule, DNS response action [, {uuid="UUID", name="name"}}])", "add a response rule"}, + {"addSelfAnsweredResponseAction", true, R"(DNS rule, DNS response action [, {uuid="UUID", name="name"}}])", "add a self-answered response rule"}, + {"addTLSLocal", true, "addr, certFile(s), keyFile(s) [,params]", "listen to incoming DNS over TLS queries on the specified address using the specified certificate (or list of) and key (or list of). The last parameter is a table"}, + {"AllowAction", true, "", "let these packets go through"}, + {"AllowResponseAction", true, "", "let these packets go through"}, + {"AllRule", true, "", "matches all traffic"}, + {"AndRule", true, "list of DNS rules", "matches if all sub-rules matches"}, + {"benchRule", true, "DNS Rule [, iterations [, suffix]]", "bench the specified DNS rule"}, + {"carbonServer", true, "serverIP, [ourname], [interval]", "report statistics to serverIP using our hostname, or 'ourname' if provided, every 'interval' seconds"}, + {"clearConsoleHistory", true, "", "clear the internal (in-memory) history of console commands"}, + {"clearDynBlocks", true, "", "clear all dynamic blocks"}, + {"clearQueryCounters", true, "", "clears the query counter buffer"}, + {"clearRules", true, "", "remove all current rules"}, + {"controlSocket", true, "addr", "open a control socket on this address / connect to this address in client mode"}, + {"ContinueAction", true, "action", "execute the specified action and continue the processing of the remaining rules, regardless of the return of the action"}, + {"declareMetric", true, "name, type, description [, prometheusName]", "Declare a custom metric"}, + {"decMetric", true, "name", "Decrement a custom metric"}, + {"DelayAction", true, "milliseconds", "delay the response by the specified amount of milliseconds (UDP-only)"}, + {"DelayResponseAction", true, "milliseconds", "delay the response by the specified amount of milliseconds (UDP-only)"}, + {"delta", true, "", "shows all commands entered that changed the configuration"}, + {"DNSSECRule", true, "", "matches queries with the DO bit set"}, + {"DnstapLogAction", true, "identity, FrameStreamLogger [, alterFunction]", "send the contents of this query to a FrameStreamLogger or RemoteLogger as dnstap. `alterFunction` is a callback, receiving a DNSQuestion and a DnstapMessage, that can be used to modify the dnstap message"}, + {"DnstapLogResponseAction", true, "identity, FrameStreamLogger [, alterFunction]", "send the contents of this response to a remote or FrameStreamLogger or RemoteLogger as dnstap. `alterFunction` is a callback, receiving a DNSResponse and a DnstapMessage, that can be used to modify the dnstap message"}, + {"DropAction", true, "", "drop these packets"}, + {"DropResponseAction", true, "", "drop these packets"}, + {"DSTPortRule", true, "port", "matches questions received to the destination port specified"}, + {"dumpStats", true, "", "print all statistics we gather"}, + {"dynBlockRulesGroup", true, "", "return a new DynBlockRulesGroup object"}, + {"EDNSVersionRule", true, "version", "matches queries with the specified EDNS version"}, + {"EDNSOptionRule", true, "optcode", "matches queries with the specified EDNS0 option present"}, + {"ERCodeAction", true, "ercode", "Reply immediately by turning the query into a response with the specified EDNS extended rcode"}, + {"ERCodeRule", true, "rcode", "matches responses with the specified extended rcode (EDNS0)"}, + {"exceedNXDOMAINs", true, "rate, seconds", "get set of addresses that exceed `rate` NXDOMAIN/s over `seconds` seconds"}, + {"exceedQRate", true, "rate, seconds", "get set of address that exceed `rate` queries/s over `seconds` seconds"}, + {"exceedQTypeRate", true, "type, rate, seconds", "get set of address that exceed `rate` queries/s for queries of type `type` over `seconds` seconds"}, + {"exceedRespByterate", true, "rate, seconds", "get set of addresses that exceeded `rate` bytes/s answers over `seconds` seconds"}, + {"exceedServFails", true, "rate, seconds", "get set of addresses that exceed `rate` servfails/s over `seconds` seconds"}, + {"firstAvailable", false, "", "picks the server with the lowest `order` that has not exceeded its QPS limit"}, + {"fixupCase", true, "bool", "if set (default to no), rewrite the first qname of the question part of the answer to match the one from the query. It is only useful when you have a downstream server that messes up the case of the question qname in the answer"}, + {"generateDNSCryptCertificate", true, R"("/path/to/providerPrivate.key", "/path/to/resolver.cert", "/path/to/resolver.key", serial, validFrom, validUntil)", "generate a new resolver private key and related certificate, valid from the `validFrom` timestamp until the `validUntil` one, signed with the provider private key"}, + {"generateDNSCryptProviderKeys", true, R"("/path/to/providerPublic.key", "/path/to/providerPrivate.key")", "generate a new provider keypair"}, + {"getAction", true, "n", "Returns the Action associated with rule n"}, + {"getBind", true, "n", "returns the listener at index n"}, + {"getBindCount", true, "", "returns the number of listeners all kinds"}, + {"getCacheHitResponseRule", true, "selector", "Return the cache-hit response rule corresponding to the selector, if any"}, + {"getCacheInsertedResponseRule", true, "selector", "Return the cache-inserted response rule corresponding to the selector, if any"}, + {"getCurrentTime", true, "", "returns the current time"}, + {"getDynamicBlocks", true, "", "returns a table of the current network-based dynamic blocks"}, + {"getDynamicBlocksSMT", true, "", "returns a table of the current suffix-based dynamic blocks"}, + {"getDNSCryptBind", true, "n", "return the `DNSCryptContext` object corresponding to the bind `n`"}, + {"getDNSCryptBindCount", true, "", "returns the number of DNSCrypt listeners"}, + {"getDOHFrontend", true, "n", "returns the DoH frontend with index n"}, + {"getDOHFrontendCount", true, "", "returns the number of DoH listeners"}, + {"getDOH3Frontend", true, "n", "returns the DoH3 frontend with index n"}, + {"getDOH3FrontendCount", true, "", "returns the number of DoH3 listeners"}, + {"getDOQFrontend", true, "n", "returns the DoQ frontend with index n"}, + {"getDOQFrontendCount", true, "", "returns the number of DoQ listeners"}, + {"getListOfAddressesOfNetworkInterface", true, "itf", "returns the list of addresses configured on a given network interface, as strings"}, + {"getListOfNetworkInterfaces", true, "", "returns the list of network interfaces present on the system, as strings"}, + {"getListOfRangesOfNetworkInterface", true, "itf", "returns the list of network ranges configured on a given network interface, as strings"}, + {"getMACAddress", true, "IP addr", "return the link-level address (MAC) corresponding to the supplied neighbour IP address, if known by the kernel"}, + {"getMetric", true, "name", "Get the value of a custom metric"}, + {"getOutgoingTLSSessionCacheSize", true, "", "returns the number of TLS sessions (for outgoing connections) currently cached"}, + {"getPool", true, "name", "return the pool named `name`, or \"\" for the default pool"}, + {"getPoolServers", true, "pool", "return servers part of this pool"}, + {"getPoolNames", true, "", "returns a table with all the pool names"}, + {"getQueryCounters", true, "[max=10]", "show current buffer of query counters, limited by 'max' if provided"}, + {"getResponseRing", true, "", "return the current content of the response ring"}, + {"getResponseRule", true, "selector", "Return the response rule corresponding to the selector, if any"}, + {"getRespRing", true, "", "return the qname/rcode content of the response ring"}, + {"getRule", true, "selector", "Return the rule corresponding to the selector, if any"}, + {"getSelfAnsweredResponseRule", true, "selector", "Return the self-answered response rule corresponding to the selector, if any"}, + {"getServer", true, "id", "returns server with index 'n' or whose uuid matches if 'id' is an UUID string"}, + {"getServers", true, "", "returns a table with all defined servers"}, + {"getStatisticsCounters", true, "", "returns a map of statistic counters"}, + {"getTopCacheHitResponseRules", true, "[top]", "return the `top` cache-hit response rules"}, + {"getTopCacheInsertedResponseRules", true, "[top]", "return the `top` cache-inserted response rules"}, + {"getTopResponseRules", true, "[top]", "return the `top` response rules"}, + {"getTopRules", true, "[top]", "return the `top` rules"}, + {"getTopSelfAnsweredResponseRules", true, "[top]", "return the `top` self-answered response rules"}, + {"getTLSContext", true, "n", "returns the TLS context with index n"}, + {"getTLSFrontend", true, "n", "returns the TLS frontend with index n"}, + {"getTLSFrontendCount", true, "", "returns the number of DoT listeners"}, + {"getVerbose", true, "", "get whether log messages at the verbose level will be logged"}, + {"grepq", true, R"(Netmask|DNS Name|100ms|{"::1", "powerdns.com", "100ms"} [, n] [,options])", "shows the last n queries and responses matching the specified client address or range (Netmask), or the specified DNS Name, or slower than 100ms"}, + {"hashPassword", true, "password [, workFactor]", "Returns a hashed and salted version of the supplied password, usable with 'setWebserverConfig()'"}, + {"HTTPHeaderRule", true, "name, regex", "matches DoH queries with a HTTP header 'name' whose content matches the regular expression 'regex'"}, + {"HTTPPathRegexRule", true, "regex", "matches DoH queries whose HTTP path matches 'regex'"}, + {"HTTPPathRule", true, "path", "matches DoH queries whose HTTP path is an exact match to 'path'"}, + {"HTTPStatusAction", true, "status, reason, body", "return an HTTP response"}, + {"inClientStartup", true, "", "returns true during console client parsing of configuration"}, + {"includeDirectory", true, "path", "include configuration files from `path`"}, + {"incMetric", true, "name", "Increment a custom metric"}, + {"KeyValueLookupKeyQName", true, "[wireFormat]", "Return a new KeyValueLookupKey object that, when passed to KeyValueStoreLookupAction or KeyValueStoreLookupRule, will return the qname of the query, either in wire format (default) or in plain text if 'wireFormat' is false"}, + {"KeyValueLookupKeySourceIP", true, "[v4Mask [, v6Mask [, includePort]]]", "Return a new KeyValueLookupKey object that, when passed to KeyValueStoreLookupAction or KeyValueStoreLookupRule, will return the (possibly bitmasked) source IP of the client in network byte-order."}, + {"KeyValueLookupKeySuffix", true, "[minLabels [,wireFormat]]", "Return a new KeyValueLookupKey object that, when passed to KeyValueStoreLookupAction or KeyValueStoreLookupRule, will return a vector of keys based on the labels of the qname in DNS wire format or plain text"}, + {"KeyValueLookupKeyTag", true, "tag", "Return a new KeyValueLookupKey object that, when passed to KeyValueStoreLookupAction or KeyValueStoreLookupRule, will return the value of the corresponding tag for this query, if it exists"}, + {"KeyValueStoreLookupAction", true, "kvs, lookupKey, destinationTag", "does a lookup into the key value store referenced by 'kvs' using the key returned by 'lookupKey', and storing the result if any into the tag named 'destinationTag'"}, + {"KeyValueStoreRangeLookupAction", true, "kvs, lookupKey, destinationTag", "does a range-based lookup into the key value store referenced by 'kvs' using the key returned by 'lookupKey', and storing the result if any into the tag named 'destinationTag'"}, + {"KeyValueStoreLookupRule", true, "kvs, lookupKey", "matches queries if the key is found in the specified Key Value store"}, + {"KeyValueStoreRangeLookupRule", true, "kvs, lookupKey", "matches queries if the key is found in the specified Key Value store"}, + {"leastOutstanding", false, "", "Send traffic to downstream server with least outstanding queries, with the lowest 'order', and within that the lowest recent latency"}, #if defined(HAVE_LIBSSL) && !defined(HAVE_TLS_PROVIDERS) - { "loadTLSEngine", true, "engineName [, defaultString]", "Load the OpenSSL engine named 'engineName', setting the engine default string to 'defaultString' if supplied"}, + {"loadTLSEngine", true, "engineName [, defaultString]", "Load the OpenSSL engine named 'engineName', setting the engine default string to 'defaultString' if supplied"}, #endif #if defined(HAVE_LIBSSL) && OPENSSL_VERSION_MAJOR >= 3 && defined(HAVE_TLS_PROVIDERS) - { "loadTLSProvider", true, "providerName", "Load the OpenSSL provider named 'providerName'"}, + {"loadTLSProvider", true, "providerName", "Load the OpenSSL provider named 'providerName'"}, #endif - { "LogAction", true, "[filename], [binary], [append], [buffered]", "Log a line for each query, to the specified file if any, to the console (require verbose) otherwise. When logging to a file, the `binary` optional parameter specifies whether we log in binary form (default) or in textual form, the `append` optional parameter specifies whether we open the file for appending or truncate each time (default), and the `buffered` optional parameter specifies whether writes to the file are buffered (default) or not." }, - { "LogResponseAction", true, "[filename], [append], [buffered]", "Log a line for each response, to the specified file if any, to the console (require verbose) otherwise. The `append` optional parameter specifies whether we open the file for appending or truncate each time (default), and the `buffered` optional parameter specifies whether writes to the file are buffered (default) or not." }, - { "LuaAction", true, "function", "Invoke a Lua function that accepts a DNSQuestion" }, - { "LuaFFIAction", true, "function", "Invoke a Lua FFI function that accepts a DNSQuestion" }, - { "LuaFFIPerThreadAction", true, "function", "Invoke a Lua FFI function that accepts a DNSQuestion, with a per-thread Lua context" }, - { "LuaFFIPerThreadResponseAction", true, "function", "Invoke a Lua FFI function that accepts a DNSResponse, with a per-thread Lua context" }, - { "LuaFFIResponseAction", true, "function", "Invoke a Lua FFI function that accepts a DNSResponse" }, - { "LuaFFIRule", true, "function", "Invoke a Lua FFI function that filters DNS questions" }, - { "LuaResponseAction", true, "function", "Invoke a Lua function that accepts a DNSResponse" }, - { "LuaRule", true, "function", "Invoke a Lua function that filters DNS questions" }, + {"LogAction", true, "[filename], [binary], [append], [buffered]", "Log a line for each query, to the specified file if any, to the console (require verbose) otherwise. When logging to a file, the `binary` optional parameter specifies whether we log in binary form (default) or in textual form, the `append` optional parameter specifies whether we open the file for appending or truncate each time (default), and the `buffered` optional parameter specifies whether writes to the file are buffered (default) or not."}, + {"LogResponseAction", true, "[filename], [append], [buffered]", "Log a line for each response, to the specified file if any, to the console (require verbose) otherwise. The `append` optional parameter specifies whether we open the file for appending or truncate each time (default), and the `buffered` optional parameter specifies whether writes to the file are buffered (default) or not."}, + {"LuaAction", true, "function", "Invoke a Lua function that accepts a DNSQuestion"}, + {"LuaFFIAction", true, "function", "Invoke a Lua FFI function that accepts a DNSQuestion"}, + {"LuaFFIPerThreadAction", true, "function", "Invoke a Lua FFI function that accepts a DNSQuestion, with a per-thread Lua context"}, + {"LuaFFIPerThreadResponseAction", true, "function", "Invoke a Lua FFI function that accepts a DNSResponse, with a per-thread Lua context"}, + {"LuaFFIResponseAction", true, "function", "Invoke a Lua FFI function that accepts a DNSResponse"}, + {"LuaFFIRule", true, "function", "Invoke a Lua FFI function that filters DNS questions"}, + {"LuaResponseAction", true, "function", "Invoke a Lua function that accepts a DNSResponse"}, + {"LuaRule", true, "function", "Invoke a Lua function that filters DNS questions"}, #ifdef HAVE_IPCIPHER - { "makeIPCipherKey", true, "password", "generates a 16-byte key that can be used to pseudonymize IP addresses with IP cipher" }, + {"makeIPCipherKey", true, "password", "generates a 16-byte key that can be used to pseudonymize IP addresses with IP cipher"}, #endif /* HAVE_IPCIPHER */ - { "makeKey", true, "", "generate a new server access key, emit configuration line ready for pasting" }, - { "makeRule", true, "rule", "Make a NetmaskGroupRule() or a SuffixMatchNodeRule(), depending on how it is called" } , - { "MaxQPSIPRule", true, "qps, [v4Mask=32 [, v6Mask=64 [, burst=qps [, expiration=300 [, cleanupDelay=60 [, scanFraction=10 [, shards=10]]]]]]]", "matches traffic exceeding the qps limit per subnet" }, - { "MaxQPSRule", true, "qps", "matches traffic **not** exceeding this qps limit" }, - { "mvCacheHitResponseRule", true, "from, to", "move cache hit response rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule" }, - { "mvCacheHitResponseRuleToTop", true, "", "move the last cache hit response rule to the first position" }, - { "mvCacheInsertedResponseRule", true, "from, to", "move cache inserted response rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule" }, - { "mvCacheInsertedResponseRuleToTop", true, "", "move the last cache inserted response rule to the first position" }, - { "mvResponseRule", true, "from, to", "move response rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule" }, - { "mvResponseRuleToTop", true, "", "move the last response rule to the first position" }, - { "mvRule", true, "from, to", "move rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule, in which case the rule will be moved to the last position" }, - { "mvRuleToTop", true, "", "move the last rule to the first position" }, - { "mvSelfAnsweredResponseRule", true, "from, to", "move self-answered response rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule" }, - { "mvSelfAnsweredResponseRuleToTop", true, "", "move the last self-answered response rule to the first position" }, - { "NetmaskGroupRule", true, "nmg[, src]", "Matches traffic from/to the network range specified in nmg. Set the src parameter to false to match nmg against destination address instead of source address. This can be used to differentiate between clients" }, - { "newBPFFilter", true, "{ipv4MaxItems=int, ipv4PinnedPath=string, ipv6MaxItems=int, ipv6PinnedPath=string, cidr4MaxItems=int, cidr4PinnedPath=string, cidr6MaxItems=int, cidr6PinnedPath=string, qnamesMaxItems=int, qnamesPinnedPath=string, external=bool}", "Return a new eBPF socket filter with specified options." }, - { "newCA", true, "address", "Returns a ComboAddress based on `address`" }, + {"makeKey", true, "", "generate a new server access key, emit configuration line ready for pasting"}, + {"makeRule", true, "rule", "Make a NetmaskGroupRule() or a SuffixMatchNodeRule(), depending on how it is called"}, + {"MaxQPSIPRule", true, "qps, [v4Mask=32 [, v6Mask=64 [, burst=qps [, expiration=300 [, cleanupDelay=60 [, scanFraction=10 [, shards=10]]]]]]]", "matches traffic exceeding the qps limit per subnet"}, + {"MaxQPSRule", true, "qps", "matches traffic **not** exceeding this qps limit"}, + {"mvCacheHitResponseRule", true, "from, to", "move cache hit response rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule"}, + {"mvCacheHitResponseRuleToTop", true, "", "move the last cache hit response rule to the first position"}, + {"mvCacheInsertedResponseRule", true, "from, to", "move cache inserted response rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule"}, + {"mvCacheInsertedResponseRuleToTop", true, "", "move the last cache inserted response rule to the first position"}, + {"mvResponseRule", true, "from, to", "move response rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule"}, + {"mvResponseRuleToTop", true, "", "move the last response rule to the first position"}, + {"mvRule", true, "from, to", "move rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule, in which case the rule will be moved to the last position"}, + {"mvRuleToTop", true, "", "move the last rule to the first position"}, + {"mvSelfAnsweredResponseRule", true, "from, to", "move self-answered response rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule"}, + {"mvSelfAnsweredResponseRuleToTop", true, "", "move the last self-answered response rule to the first position"}, + {"NetmaskGroupRule", true, "nmg[, src]", "Matches traffic from/to the network range specified in nmg. Set the src parameter to false to match nmg against destination address instead of source address. This can be used to differentiate between clients"}, + {"newBPFFilter", true, "{ipv4MaxItems=int, ipv4PinnedPath=string, ipv6MaxItems=int, ipv6PinnedPath=string, cidr4MaxItems=int, cidr4PinnedPath=string, cidr6MaxItems=int, cidr6PinnedPath=string, qnamesMaxItems=int, qnamesPinnedPath=string, external=bool}", "Return a new eBPF socket filter with specified options."}, + {"newCA", true, "address", "Returns a ComboAddress based on `address`"}, #ifdef HAVE_CDB - { "newCDBKVStore", true, "fname, refreshDelay", "Return a new KeyValueStore object associated to the corresponding CDB database" }, + {"newCDBKVStore", true, "fname, refreshDelay", "Return a new KeyValueStore object associated to the corresponding CDB database"}, #endif - { "newDNSName", true, "name", "make a DNSName based on this .-terminated name" }, - { "newDNSNameSet", true, "", "returns a new DNSNameSet" }, - { "newDynBPFFilter", true, "bpf", "Return a new dynamic eBPF filter associated to a given BPF Filter" }, - { "newFrameStreamTcpLogger", true, "addr [, options]", "create a FrameStream logger object writing to a TCP address (addr should be ip:port), to use with `DnstapLogAction()` and `DnstapLogResponseAction()`" }, - { "newFrameStreamUnixLogger", true, "socket [, options]", "create a FrameStream logger object writing to a local unix socket, to use with `DnstapLogAction()` and `DnstapLogResponseAction()`" }, + {"newDNSName", true, "name", "make a DNSName based on this .-terminated name"}, + {"newDNSNameSet", true, "", "returns a new DNSNameSet"}, + {"newDynBPFFilter", true, "bpf", "Return a new dynamic eBPF filter associated to a given BPF Filter"}, + {"newFrameStreamTcpLogger", true, "addr [, options]", "create a FrameStream logger object writing to a TCP address (addr should be ip:port), to use with `DnstapLogAction()` and `DnstapLogResponseAction()`"}, + {"newFrameStreamUnixLogger", true, "socket [, options]", "create a FrameStream logger object writing to a local unix socket, to use with `DnstapLogAction()` and `DnstapLogResponseAction()`"}, #ifdef HAVE_LMDB - { "newLMDBKVStore", true, "fname, dbName [, noLock]", "Return a new KeyValueStore object associated to the corresponding LMDB database" }, + {"newLMDBKVStore", true, "fname, dbName [, noLock]", "Return a new KeyValueStore object associated to the corresponding LMDB database"}, #endif - { "newNMG", true, "", "Returns a NetmaskGroup" }, - { "newPacketCache", true, "maxEntries[, maxTTL=86400, minTTL=0, temporaryFailureTTL=60, staleTTL=60, dontAge=false, numberOfShards=1, deferrableInsertLock=true, options={}]", "return a new Packet Cache" }, - { "newQPSLimiter", true, "rate, burst", "configure a QPS limiter with that rate and that burst capacity" }, - { "newRemoteLogger", true, "address:port [, timeout=2, maxQueuedEntries=100, reconnectWaitTime=1]", "create a Remote Logger object, to use with `RemoteLogAction()` and `RemoteLogResponseAction()`" }, - { "newRuleAction", true, R"(DNS rule, DNS action [, {uuid="UUID", name="name"}])", "return a pair of DNS Rule and DNS Action, to be used with `setRules()`" }, - { "newServer", true, R"({address="ip:port", qps=1000, order=1, weight=10, pool="abuse", retries=5, tcpConnectTimeout=5, tcpSendTimeout=30, tcpRecvTimeout=30, checkName="a.root-servers.net.", checkType="A", maxCheckFailures=1, mustResolve=false, useClientSubnet=true, source="address|interface name|address@interface", sockets=1, reconnectOnUp=false})", "instantiate a server" }, - { "newServerPolicy", true, "name, function", "create a policy object from a Lua function" }, - { "newSuffixMatchNode", true, "", "returns a new SuffixMatchNode" }, - { "newSVCRecordParameters", true, "priority, target, mandatoryParams, alpns, noDefaultAlpn [, port [, ech [, ipv4hints [, ipv6hints [, additionalParameters ]]]]]", "return a new SVCRecordParameters object, to use with SpoofSVCAction" }, - { "NegativeAndSOAAction", true, "nxd, zone, ttl, mname, rname, serial, refresh, retry, expire, minimum [, options]", "Turn a query into a NXDomain or NoData answer and sets a SOA record in the additional section" }, - { "NoneAction", true, "", "Does nothing. Subsequent rules are processed after this action" }, - { "NotRule", true, "selector", "Matches the traffic if the selector rule does not match" }, - { "OpcodeRule", true, "code", "Matches queries with opcode code. code can be directly specified as an integer, or one of the built-in DNSOpcodes" }, - { "OrRule", true, "selectors", "Matches the traffic if one or more of the the selectors rules does match" }, - { "PoolAction", true, "poolname [, stop]", "set the packet into the specified pool" }, - { "PoolAvailableRule", true, "poolname", "Check whether a pool has any servers available to handle queries" }, - { "PoolOutstandingRule", true, "poolname, limit", "Check whether a pool has outstanding queries above limit" }, - { "printDNSCryptProviderFingerprint", true, R"("/path/to/providerPublic.key")", "display the fingerprint of the provided resolver public key" }, - { "ProbaRule", true, "probability", "Matches queries with a given probability. 1.0 means always" }, - { "ProxyProtocolValueRule", true, "type [, value]", "matches queries with a specified Proxy Protocol TLV value of that type, optionally matching the content of the option as well" }, - { "QClassRule", true, "qclass", "Matches queries with the specified qclass. class can be specified as an integer or as one of the built-in DNSClass" }, - { "QNameLabelsCountRule", true, "min, max", "matches if the qname has less than `min` or more than `max` labels" }, - { "QNameRule", true, "qname", "matches queries with the specified qname" }, - { "QNameSetRule", true, "set", "Matches if the set contains exact qname" }, - { "QNameWireLengthRule", true, "min, max", "matches if the qname's length on the wire is less than `min` or more than `max` bytes" }, - { "QPSAction", true, "maxqps", "Drop a packet if it does exceed the maxqps queries per second limits. Letting the subsequent rules apply otherwise" }, - { "QPSPoolAction", true, "maxqps, poolname [, stop]", "Send the packet into the specified pool only if it does not exceed the maxqps queries per second limits. Letting the subsequent rules apply otherwise" }, - { "QTypeRule", true, "qtype", "matches queries with the specified qtype" }, - { "RCodeAction", true, "rcode", "Reply immediately by turning the query into a response with the specified rcode" }, - { "RCodeRule", true, "rcode", "matches responses with the specified rcode" }, - { "RDRule", true, "", "Matches queries with the RD flag set" }, - { "RecordsCountRule", true, "section, minCount, maxCount", "Matches if there is at least minCount and at most maxCount records in the section section. section can be specified as an integer or as a DNS Packet Sections" }, - { "RecordsTypeCountRule", true, "section, qtype, minCount, maxCount", "Matches if there is at least minCount and at most maxCount records of type type in the section section" }, - { "RegexRule", true, "regex", "matches the query name against the supplied regex" }, - { "registerDynBPFFilter", true, "DynBPFFilter", "register this dynamic BPF filter into the web interface so that its counters are displayed" }, - { "reloadAllCertificates", true, "", "reload all DNSCrypt and TLS certificates, along with their associated keys" }, - { "RemoteLogAction", true, "RemoteLogger [, alterFunction [, serverID]]", "send the content of this query to a remote logger via Protocol Buffer. `alterFunction` is a callback, receiving a DNSQuestion and a DNSDistProtoBufMessage, that can be used to modify the Protocol Buffer content, for example for anonymization purposes. `serverID` is the server identifier." }, - { "RemoteLogResponseAction", true, "RemoteLogger [,alterFunction [,includeCNAME [, serverID]]]", "send the content of this response to a remote logger via Protocol Buffer. `alterFunction` is the same callback than the one in `RemoteLogAction` and `includeCNAME` indicates whether CNAME records inside the response should be parsed and exported. The default is to only exports A and AAAA records. `serverID` is the server identifier." }, - { "requestTCPStatesDump", true, "", "Request a dump of the TCP states (incoming connections, outgoing connections) during the next scan. Useful for debugging purposes only" }, - { "rmACL", true, "netmask", "remove netmask from ACL" }, - { "rmCacheHitResponseRule", true, "id", "remove cache hit response rule in position 'id', or whose uuid matches if 'id' is an UUID string, or finally whose name matches if 'id' is a string but not a valid UUID" }, - { "rmCacheInsertedResponseRule", true, "id", "remove cache inserted response rule in position 'id', or whose uuid matches if 'id' is an UUID string, or finally whose name matches if 'id' is a string but not a valid UUID" }, - { "rmResponseRule", true, "id", "remove response rule in position 'id', or whose uuid matches if 'id' is an UUID string, or finally whose name matches if 'id' is a string but not a valid UUID" }, - { "rmRule", true, "id", "remove rule in position 'id', or whose uuid matches if 'id' is an UUID string, or finally whose name matches if 'id' is a string but not a valid UUID" }, - { "rmSelfAnsweredResponseRule", true, "id", "remove self-answered response rule in position 'id', or whose uuid matches if 'id' is an UUID string, or finally whose name matches if 'id' is a string but not a valid UUID" }, - { "rmServer", true, "id", "remove server with index 'id' or whose uuid matches if 'id' is an UUID string" }, - { "roundrobin", false, "", "Simple round robin over available servers" }, - { "sendCustomTrap", true, "str", "send a custom `SNMP` trap from Lua, containing the `str` string"}, - { "setACL", true, "{netmask, netmask}", "replace the ACL set with these netmasks. Use `setACL({})` to reset the list, meaning no one can use us" }, - { "setACLFromFile", true, "file", "replace the ACL set with netmasks in this file" }, - { "setAddEDNSToSelfGeneratedResponses", true, "add", "set whether to add EDNS to self-generated responses, provided that the initial query had EDNS" }, - { "setAllowEmptyResponse", true, "allow", "Set to true (defaults to false) to allow empty responses (qdcount=0) with a NoError or NXDomain rcode (default) from backends" }, - { "setAPIWritable", true, "bool, dir", "allow modifications via the API. if `dir` is set, it must be a valid directory where the configuration files will be written by the API" }, - { "setCacheCleaningDelay", true, "num", "Set the interval in seconds between two runs of the cache cleaning algorithm, removing expired entries" }, - { "setCacheCleaningPercentage", true, "num", "Set the percentage of the cache that the cache cleaning algorithm will try to free by removing expired entries. By default (100), all expired entries are remove" }, - { "setConsistentHashingBalancingFactor", true, "factor", "Set the balancing factor for bounded-load consistent hashing" }, - { "setConsoleACL", true, "{netmask, netmask}", "replace the console ACL set with these netmasks" }, - { "setConsoleConnectionsLogging", true, "enabled", "whether to log the opening and closing of console connections" }, - { "setConsoleMaximumConcurrentConnections", true, "max", "Set the maximum number of concurrent console connections" }, - { "setConsoleOutputMaxMsgSize", true, "messageSize", "set console message maximum size in bytes, default is 10 MB" }, - { "setDefaultBPFFilter", true, "filter", "When used at configuration time, the corresponding BPFFilter will be attached to every bind" }, - { "setDoHDownstreamCleanupInterval", true, "interval", "minimum interval in seconds between two cleanups of the idle DoH downstream connections" }, - { "setDoHDownstreamMaxIdleTime", true, "time", "Maximum time in seconds that a downstream DoH connection to a backend might stay idle" }, - { "setDynBlocksAction", true, "action", "set which action is performed when a query is blocked. Only DNSAction.Drop (the default) and DNSAction.Refused are supported" }, - { "setDynBlocksPurgeInterval", true, "sec", "set how often the expired dynamic block entries should be removed" }, - { "setDropEmptyQueries", true, "drop", "Whether to drop empty queries right away instead of sending a NOTIMP response" }, - { "setECSOverride", true, "bool", "whether to override an existing EDNS Client Subnet value in the query" }, - { "setECSSourcePrefixV4", true, "prefix-length", "the EDNS Client Subnet prefix-length used for IPv4 queries" }, - { "setECSSourcePrefixV6", true, "prefix-length", "the EDNS Client Subnet prefix-length used for IPv6 queries" }, - { "setKey", true, "key", "set access key to that key" }, - { "setLocal", true, R"(addr [, {doTCP=true, reusePort=false, tcpFastOpenQueueSize=0, interface="", cpus={}}])", "reset the list of addresses we listen on to this address" }, - { "setMaxCachedDoHConnectionsPerDownstream", true, "max", "Set the maximum number of inactive DoH connections to a backend cached by each worker DoH thread" }, - { "setMaxCachedTCPConnectionsPerDownstream", true, "max", "Set the maximum number of inactive TCP connections to a backend cached by each worker TCP thread" }, - { "setMaxTCPClientThreads", true, "n", "set the maximum of TCP client threads, handling TCP connections" }, - { "setMaxTCPConnectionDuration", true, "n", "set the maximum duration of an incoming TCP connection, in seconds. 0 means unlimited" }, - { "setMaxTCPConnectionsPerClient", true, "n", "set the maximum number of TCP connections per client. 0 means unlimited" }, - { "setMaxTCPQueriesPerConnection", true, "n", "set the maximum number of queries in an incoming TCP connection. 0 means unlimited" }, - { "setMaxTCPQueuedConnections", true, "n", "set the maximum number of TCP connections queued (waiting to be picked up by a client thread)" }, - { "setMaxUDPOutstanding", true, "n", "set the maximum number of outstanding UDP queries to a given backend server. This can only be set at configuration time and defaults to 65535" }, - { "setMetric", true, "name, value", "Set the value of a custom metric to the supplied value" }, - { "setPayloadSizeOnSelfGeneratedAnswers", true, "payloadSize", "set the UDP payload size advertised via EDNS on self-generated responses" }, - { "setPoolServerPolicy", true, "policy, pool", "set the server selection policy for this pool to that policy" }, - { "setPoolServerPolicyLua", true, "name, function, pool", "set the server selection policy for this pool to one named 'name' and provided by 'function'" }, - { "setPoolServerPolicyLuaFFI", true, "name, function, pool", "set the server selection policy for this pool to one named 'name' and provided by 'function'" }, - { "setPoolServerPolicyLuaFFIPerThread", true, "name, code", "set server selection policy for this pool to one named 'name' and returned by the Lua FFI code passed in 'code'" }, - { "setProxyProtocolACL", true, "{netmask, netmask}", "Set the netmasks who are allowed to send Proxy Protocol headers in front of queries/connections" }, - { "setProxyProtocolApplyACLToProxiedClients", true, "apply", "Whether the general ACL should be applied to the source IP address gathered from a Proxy Protocol header, in addition to being first applied to the source address seen by dnsdist" }, - { "setProxyProtocolMaximumPayloadSize", true, "max", "Set the maximum size of a Proxy Protocol payload, in bytes" }, - { "setQueryCount", true, "bool", "set whether queries should be counted" }, - { "setQueryCountFilter", true, "func", "filter queries that would be counted, where `func` is a function with parameter `dq` which decides whether a query should and how it should be counted" }, - { "SetReducedTTLResponseAction", true, "percentage", "Reduce the TTL of records in a response to a given percentage" }, - { "setRingBuffersLockRetries", true, "n", "set the number of attempts to get a non-blocking lock to a ringbuffer shard before blocking" }, - { "setRingBuffersOptions", true, "{ lockRetries=int, recordQueries=true, recordResponses=true }", "set ringbuffer options" }, - { "setRingBuffersSize", true, "n [, numberOfShards]", "set the capacity of the ringbuffers used for live traffic inspection to `n`, and optionally the number of shards to use to `numberOfShards`" }, - { "setRoundRobinFailOnNoServer", true, "value", "By default the roundrobin load-balancing policy will still try to select a backend even if all backends are currently down. Setting this to true will make the policy fail and return that no server is available instead" }, - { "setRules", true, "list of rules", "replace the current rules with the supplied list of pairs of DNS Rules and DNS Actions (see `newRuleAction()`)" }, - { "setSecurityPollInterval", true, "n", "set the security polling interval to `n` seconds" }, - { "setSecurityPollSuffix", true, "suffix", "set the security polling suffix to the specified value" }, - { "setServerPolicy", true, "policy", "set server selection policy to that policy" }, - { "setServerPolicyLua", true, "name, function", "set server selection policy to one named 'name' and provided by 'function'" }, - { "setServerPolicyLuaFFI", true, "name, function", "set server selection policy to one named 'name' and provided by the Lua FFI 'function'" }, - { "setServerPolicyLuaFFIPerThread", true, "name, code", "set server selection policy to one named 'name' and returned by the Lua FFI code passed in 'code'" }, - { "setServFailWhenNoServer", true, "bool", "if set, return a ServFail when no servers are available, instead of the default behaviour of dropping the query" }, - { "setStaleCacheEntriesTTL", true, "n", "allows using cache entries expired for at most n seconds when there is no backend available to answer for a query" }, - { "setStructuredLogging", true, "value [, options]", "set whether log messages should be in structured-logging-like format" }, - { "setSyslogFacility", true, "facility", "set the syslog logging facility to 'facility'. Defaults to LOG_DAEMON" }, - { "setTCPDownstreamCleanupInterval", true, "interval", "minimum interval in seconds between two cleanups of the idle TCP downstream connections" }, - { "setTCPFastOpenKey", true, "string", "TCP Fast Open Key" }, - { "setTCPDownstreamMaxIdleTime", true, "time", "Maximum time in seconds that a downstream TCP connection to a backend might stay idle" }, - { "setTCPInternalPipeBufferSize", true, "size", "Set the size in bytes of the internal buffer of the pipes used internally to distribute connections to TCP (and DoT) workers threads" }, - { "setTCPRecvTimeout", true, "n", "set the read timeout on TCP connections from the client, in seconds" }, - { "setTCPSendTimeout", true, "n", "set the write timeout on TCP connections from the client, in seconds" }, - { "setUDPMultipleMessagesVectorSize", true, "n", "set the size of the vector passed to recvmmsg() to receive UDP messages. Default to 1 which means that the feature is disabled and recvmsg() is used instead" }, - { "setUDPSocketBufferSizes", true, "recv, send", "Set the size of the receive (SO_RCVBUF) and send (SO_SNDBUF) buffers for incoming UDP sockets" }, - { "setUDPTimeout", true, "n", "set the maximum time dnsdist will wait for a response from a backend over UDP, in seconds" }, - { "setVerbose", true, "bool", "set whether log messages at the verbose level will be logged" }, - { "setVerboseHealthChecks", true, "bool", "set whether health check errors will be logged" }, - { "setVerboseLogDestination", true, "destination file", "Set a destination file to write the 'verbose' log messages to, instead of sending them to syslog and/or the standard output" }, - { "setWebserverConfig", true, "[{password=string, apiKey=string, customHeaders, statsRequireAuthentication}]", "Updates webserver configuration" }, - { "setWeightedBalancingFactor", true, "factor", "Set the balancing factor for bounded-load weighted policies (whashed, wrandom)" }, - { "setWHashedPertubation", true, "value", "Set the hash perturbation value to be used in the whashed policy instead of a random one, allowing to have consistent whashed results on different instance" }, - { "show", true, "string", "outputs `string`" }, - { "showACL", true, "", "show our ACL set" }, - { "showBinds", true, "", "show listening addresses (frontends)" }, - { "showCacheHitResponseRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined cache hit response rules, optionally with their UUIDs and optionally truncated to a given width" }, - { "showConsoleACL", true, "", "show our current console ACL set" }, - { "showDNSCryptBinds", true, "", "display the currently configured DNSCrypt binds" }, - { "showDOHFrontends", true, "", "list all the available DOH frontends" }, - { "showDOH3Frontends", true, "", "list all the available DOH3 frontends" }, - { "showDOHResponseCodes", true, "", "show the HTTP response code statistics for the DoH frontends"}, - { "showDOQFrontends", true, "", "list all the available DOQ frontends" }, - { "showDynBlocks", true, "", "show dynamic blocks in force" }, - { "showPools", true, "", "show the available pools" }, - { "showPoolServerPolicy", true, "pool", "show server selection policy for this pool" }, - { "showResponseLatency", true, "", "show a plot of the response time latency distribution" }, - { "showResponseRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined response rules, optionally with their UUIDs and optionally truncated to a given width" }, - { "showRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined rules, optionally with their UUIDs and optionally truncated to a given width" }, - { "showSecurityStatus", true, "", "Show the security status"}, - { "showSelfAnsweredResponseRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined self-answered response rules, optionally with their UUIDs and optionally truncated to a given width" }, - { "showServerPolicy", true, "", "show name of currently operational server selection policy" }, - { "showServers", true, "[{showUUIDs=false}]", "output all servers, optionally with their UUIDs" }, - { "showTCPStats", true, "", "show some statistics regarding TCP" }, - { "showTLSContexts", true, "", "list all the available TLS contexts" }, - { "showTLSErrorCounters", true, "", "show metrics about TLS handshake failures" }, - { "showVersion", true, "", "show the current version" }, - { "showWebserverConfig", true, "", "Show the current webserver configuration" }, - { "shutdown", true, "", "shut down `dnsdist`" }, - { "snmpAgent", true, "enableTraps [, daemonSocket]", "enable `SNMP` support. `enableTraps` is a boolean indicating whether traps should be sent and `daemonSocket` an optional string specifying how to connect to the daemon agent"}, - { "SetAdditionalProxyProtocolValueAction", true, "type, value", "Add a Proxy Protocol TLV value of this type" }, - { "SetDisableECSAction", true, "", "Disable the sending of ECS to the backend. Subsequent rules are processed after this action." }, - { "SetDisableValidationAction", true, "", "set the CD bit in the question, let it go through" }, - { "SetECSAction", true, "v4[, v6]", "Set the ECS prefix and prefix length sent to backends to an arbitrary value" }, - { "SetECSOverrideAction", true, "override", "Whether an existing EDNS Client Subnet value should be overridden (true) or not (false). Subsequent rules are processed after this action" }, - { "SetECSPrefixLengthAction", true, "v4, v6", "Set the ECS prefix length. Subsequent rules are processed after this action" }, - { "SetMacAddrAction", true, "option", "Add the source MAC address to the query as EDNS0 option option. This action is currently only supported on Linux. Subsequent rules are processed after this action" }, - { "SetEDNSOptionAction", true, "option, data", "Add arbitrary EDNS option and data to the query. Subsequent rules are processed after this action" }, - { "SetExtendedDNSErrorAction", true, "infoCode [, extraText]", "Set an Extended DNS Error status that will be added to the response corresponding to the current query. Subsequent rules are processed after this action" }, - { "SetExtendedDNSErrorResponseAction", true, "infoCode [, extraText]", "Set an Extended DNS Error status that will be added to this response. Subsequent rules are processed after this action" }, - { "SetNoRecurseAction", true, "", "strip RD bit from the question, let it go through" }, - { "setOutgoingDoHWorkerThreads", true, "n", "Number of outgoing DoH worker threads" }, - { "SetProxyProtocolValuesAction", true, "values", "Set the Proxy-Protocol values for this queries to 'values'" }, - { "SetSkipCacheAction", true, "", "Don’t lookup the cache for this query, don’t store the answer" }, - { "SetSkipCacheResponseAction", true, "", "Don’t store this response into the cache" }, - { "SetTagAction", true, "name, value", "set the tag named 'name' to the given value" }, - { "SetTagResponseAction", true, "name, value", "set the tag named 'name' to the given value" }, - { "SetTempFailureCacheTTLAction", true, "ttl", "set packetcache TTL for temporary failure replies" }, - { "SNIRule", true, "name", "Create a rule which matches on the incoming TLS SNI value, if any (DoT or DoH)" }, - { "SNMPTrapAction", true, "[reason]", "send an SNMP trap, adding the optional `reason` string as the query description"}, - { "SNMPTrapResponseAction", true, "[reason]", "send an SNMP trap, adding the optional `reason` string as the response description"}, - { "SpoofAction", true, "ip|list of ips [, options]", "forge a response with the specified IPv4 (for an A query) or IPv6 (for an AAAA). If you specify multiple addresses, all that match the query type (A, AAAA or ANY) will get spoofed in" }, - { "SpoofCNAMEAction", true, "cname [, options]", "Forge a response with the specified CNAME value" }, - { "SpoofRawAction", true, "raw|list of raws [, options]", "Forge a response with the specified record data as raw bytes. If you specify multiple raws (it is assumed they match the query type), all will get spoofed in" }, - { "SpoofSVCAction", true, "list of svcParams [, options]", "Forge a response with the specified SVC record data" } , - { "SuffixMatchNodeRule", true, "smn[, quiet]", "Matches based on a group of domain suffixes for rapid testing of membership. Pass true as second parameter to prevent listing of all domains matched" }, - { "TagRule", true, "name [, value]", "matches if the tag named 'name' is present, with the given 'value' matching if any" }, - { "TCAction", true, "", "create answer to query with TC and RD bits set, to move to TCP" }, - { "TCPRule", true, "[tcp]", "Matches question received over TCP if tcp is true, over UDP otherwise" }, - { "TCResponseAction", true, "", "truncate a response" }, - { "TeeAction", true, "remote [, addECS [, local]]", "send copy of query to remote, optionally adding ECS info, optionally set local address" }, - { "testCrypto", true, "", "test of the crypto all works" }, - { "TimedIPSetRule", true, "", "Create a rule which matches a set of IP addresses which expire"}, - { "topBandwidth", true, "top", "show top-`top` clients that consume the most bandwidth over length of ringbuffer" }, - { "topCacheHitResponseRules", true, "[top][, vars]", "show `top` cache-hit response rules" }, - { "topCacheInsertedResponseRules", true, "[top][, vars]", "show `top` cache-inserted response rules" }, - { "topClients", true, "n", "show top-`n` clients sending the most queries over length of ringbuffer" }, - { "topQueries", true, "n[, labels]", "show top 'n' queries, as grouped when optionally cut down to 'labels' labels" }, - { "topResponses", true, "n, kind[, labels]", "show top 'n' responses with RCODE=kind (0=NO Error, 2=ServFail, 3=NXDomain), as grouped when optionally cut down to 'labels' labels" }, - { "topResponseRules", true, "[top][, vars]", "show `top` response rules" }, - { "topRules", true, "[top][, vars]", "show `top` rules" }, - { "topSelfAnsweredResponseRules", true, "[top][, vars]", "show `top` self-answered response rules" }, - { "topSlow", true, "[top][, limit][, labels]", "show `top` queries slower than `limit` milliseconds, grouped by last `labels` labels" }, - { "TrailingDataRule", true, "", "Matches if the query has trailing data" }, - { "truncateTC", true, "bool", "if set (defaults to no starting with dnsdist 1.2.0) truncate TC=1 answers so they are actually empty. Fixes an issue for PowerDNS Authoritative Server 2.9.22. Note: turning this on breaks compatibility with RFC 6891." }, - { "unregisterDynBPFFilter", true, "DynBPFFilter", "unregister this dynamic BPF filter" }, - { "webserver", true, "address:port", "launch a webserver with stats on that address" }, - { "whashed", false, "", "Weighted hashed ('sticky') distribution over available servers, based on the server 'weight' parameter" }, - { "chashed", false, "", "Consistent hashed ('sticky') distribution over available servers, also based on the server 'weight' parameter" }, - { "wrandom", false, "", "Weighted random over available servers, based on the server 'weight' parameter" }, + {"newNMG", true, "", "Returns a NetmaskGroup"}, + {"newPacketCache", true, "maxEntries[, maxTTL=86400, minTTL=0, temporaryFailureTTL=60, staleTTL=60, dontAge=false, numberOfShards=1, deferrableInsertLock=true, options={}]", "return a new Packet Cache"}, + {"newQPSLimiter", true, "rate, burst", "configure a QPS limiter with that rate and that burst capacity"}, + {"newRemoteLogger", true, "address:port [, timeout=2, maxQueuedEntries=100, reconnectWaitTime=1]", "create a Remote Logger object, to use with `RemoteLogAction()` and `RemoteLogResponseAction()`"}, + {"newRuleAction", true, R"(DNS rule, DNS action [, {uuid="UUID", name="name"}])", "return a pair of DNS Rule and DNS Action, to be used with `setRules()`"}, + {"newServer", true, R"({address="ip:port", qps=1000, order=1, weight=10, pool="abuse", retries=5, tcpConnectTimeout=5, tcpSendTimeout=30, tcpRecvTimeout=30, checkName="a.root-servers.net.", checkType="A", maxCheckFailures=1, mustResolve=false, useClientSubnet=true, source="address|interface name|address@interface", sockets=1, reconnectOnUp=false})", "instantiate a server"}, + {"newServerPolicy", true, "name, function", "create a policy object from a Lua function"}, + {"newSuffixMatchNode", true, "", "returns a new SuffixMatchNode"}, + {"newSVCRecordParameters", true, "priority, target, mandatoryParams, alpns, noDefaultAlpn [, port [, ech [, ipv4hints [, ipv6hints [, additionalParameters ]]]]]", "return a new SVCRecordParameters object, to use with SpoofSVCAction"}, + {"NegativeAndSOAAction", true, "nxd, zone, ttl, mname, rname, serial, refresh, retry, expire, minimum [, options]", "Turn a query into a NXDomain or NoData answer and sets a SOA record in the additional section"}, + {"NoneAction", true, "", "Does nothing. Subsequent rules are processed after this action"}, + {"NotRule", true, "selector", "Matches the traffic if the selector rule does not match"}, + {"OpcodeRule", true, "code", "Matches queries with opcode code. code can be directly specified as an integer, or one of the built-in DNSOpcodes"}, + {"OrRule", true, "selectors", "Matches the traffic if one or more of the the selectors rules does match"}, + {"PoolAction", true, "poolname [, stop]", "set the packet into the specified pool"}, + {"PoolAvailableRule", true, "poolname", "Check whether a pool has any servers available to handle queries"}, + {"PoolOutstandingRule", true, "poolname, limit", "Check whether a pool has outstanding queries above limit"}, + {"printDNSCryptProviderFingerprint", true, R"("/path/to/providerPublic.key")", "display the fingerprint of the provided resolver public key"}, + {"ProbaRule", true, "probability", "Matches queries with a given probability. 1.0 means always"}, + {"ProxyProtocolValueRule", true, "type [, value]", "matches queries with a specified Proxy Protocol TLV value of that type, optionally matching the content of the option as well"}, + {"QClassRule", true, "qclass", "Matches queries with the specified qclass. class can be specified as an integer or as one of the built-in DNSClass"}, + {"QNameLabelsCountRule", true, "min, max", "matches if the qname has less than `min` or more than `max` labels"}, + {"QNameRule", true, "qname", "matches queries with the specified qname"}, + {"QNameSetRule", true, "set", "Matches if the set contains exact qname"}, + {"QNameWireLengthRule", true, "min, max", "matches if the qname's length on the wire is less than `min` or more than `max` bytes"}, + {"QPSAction", true, "maxqps", "Drop a packet if it does exceed the maxqps queries per second limits. Letting the subsequent rules apply otherwise"}, + {"QPSPoolAction", true, "maxqps, poolname [, stop]", "Send the packet into the specified pool only if it does not exceed the maxqps queries per second limits. Letting the subsequent rules apply otherwise"}, + {"QTypeRule", true, "qtype", "matches queries with the specified qtype"}, + {"RCodeAction", true, "rcode", "Reply immediately by turning the query into a response with the specified rcode"}, + {"RCodeRule", true, "rcode", "matches responses with the specified rcode"}, + {"RDRule", true, "", "Matches queries with the RD flag set"}, + {"RecordsCountRule", true, "section, minCount, maxCount", "Matches if there is at least minCount and at most maxCount records in the section section. section can be specified as an integer or as a DNS Packet Sections"}, + {"RecordsTypeCountRule", true, "section, qtype, minCount, maxCount", "Matches if there is at least minCount and at most maxCount records of type type in the section section"}, + {"RegexRule", true, "regex", "matches the query name against the supplied regex"}, + {"registerDynBPFFilter", true, "DynBPFFilter", "register this dynamic BPF filter into the web interface so that its counters are displayed"}, + {"reloadAllCertificates", true, "", "reload all DNSCrypt and TLS certificates, along with their associated keys"}, + {"RemoteLogAction", true, "RemoteLogger [, alterFunction [, serverID]]", "send the content of this query to a remote logger via Protocol Buffer. `alterFunction` is a callback, receiving a DNSQuestion and a DNSDistProtoBufMessage, that can be used to modify the Protocol Buffer content, for example for anonymization purposes. `serverID` is the server identifier."}, + {"RemoteLogResponseAction", true, "RemoteLogger [,alterFunction [,includeCNAME [, serverID]]]", "send the content of this response to a remote logger via Protocol Buffer. `alterFunction` is the same callback than the one in `RemoteLogAction` and `includeCNAME` indicates whether CNAME records inside the response should be parsed and exported. The default is to only exports A and AAAA records. `serverID` is the server identifier."}, + {"requestTCPStatesDump", true, "", "Request a dump of the TCP states (incoming connections, outgoing connections) during the next scan. Useful for debugging purposes only"}, + {"rmACL", true, "netmask", "remove netmask from ACL"}, + {"rmCacheHitResponseRule", true, "id", "remove cache hit response rule in position 'id', or whose uuid matches if 'id' is an UUID string, or finally whose name matches if 'id' is a string but not a valid UUID"}, + {"rmCacheInsertedResponseRule", true, "id", "remove cache inserted response rule in position 'id', or whose uuid matches if 'id' is an UUID string, or finally whose name matches if 'id' is a string but not a valid UUID"}, + {"rmResponseRule", true, "id", "remove response rule in position 'id', or whose uuid matches if 'id' is an UUID string, or finally whose name matches if 'id' is a string but not a valid UUID"}, + {"rmRule", true, "id", "remove rule in position 'id', or whose uuid matches if 'id' is an UUID string, or finally whose name matches if 'id' is a string but not a valid UUID"}, + {"rmSelfAnsweredResponseRule", true, "id", "remove self-answered response rule in position 'id', or whose uuid matches if 'id' is an UUID string, or finally whose name matches if 'id' is a string but not a valid UUID"}, + {"rmServer", true, "id", "remove server with index 'id' or whose uuid matches if 'id' is an UUID string"}, + {"roundrobin", false, "", "Simple round robin over available servers"}, + {"sendCustomTrap", true, "str", "send a custom `SNMP` trap from Lua, containing the `str` string"}, + {"setACL", true, "{netmask, netmask}", "replace the ACL set with these netmasks. Use `setACL({})` to reset the list, meaning no one can use us"}, + {"setACLFromFile", true, "file", "replace the ACL set with netmasks in this file"}, + {"setAddEDNSToSelfGeneratedResponses", true, "add", "set whether to add EDNS to self-generated responses, provided that the initial query had EDNS"}, + {"setAllowEmptyResponse", true, "allow", "Set to true (defaults to false) to allow empty responses (qdcount=0) with a NoError or NXDomain rcode (default) from backends"}, + {"setAPIWritable", true, "bool, dir", "allow modifications via the API. if `dir` is set, it must be a valid directory where the configuration files will be written by the API"}, + {"setCacheCleaningDelay", true, "num", "Set the interval in seconds between two runs of the cache cleaning algorithm, removing expired entries"}, + {"setCacheCleaningPercentage", true, "num", "Set the percentage of the cache that the cache cleaning algorithm will try to free by removing expired entries. By default (100), all expired entries are remove"}, + {"setConsistentHashingBalancingFactor", true, "factor", "Set the balancing factor for bounded-load consistent hashing"}, + {"setConsoleACL", true, "{netmask, netmask}", "replace the console ACL set with these netmasks"}, + {"setConsoleConnectionsLogging", true, "enabled", "whether to log the opening and closing of console connections"}, + {"setConsoleMaximumConcurrentConnections", true, "max", "Set the maximum number of concurrent console connections"}, + {"setConsoleOutputMaxMsgSize", true, "messageSize", "set console message maximum size in bytes, default is 10 MB"}, + {"setDefaultBPFFilter", true, "filter", "When used at configuration time, the corresponding BPFFilter will be attached to every bind"}, + {"setDoHDownstreamCleanupInterval", true, "interval", "minimum interval in seconds between two cleanups of the idle DoH downstream connections"}, + {"setDoHDownstreamMaxIdleTime", true, "time", "Maximum time in seconds that a downstream DoH connection to a backend might stay idle"}, + {"setDynBlocksAction", true, "action", "set which action is performed when a query is blocked. Only DNSAction.Drop (the default) and DNSAction.Refused are supported"}, + {"setDynBlocksPurgeInterval", true, "sec", "set how often the expired dynamic block entries should be removed"}, + {"setDropEmptyQueries", true, "drop", "Whether to drop empty queries right away instead of sending a NOTIMP response"}, + {"setECSOverride", true, "bool", "whether to override an existing EDNS Client Subnet value in the query"}, + {"setECSSourcePrefixV4", true, "prefix-length", "the EDNS Client Subnet prefix-length used for IPv4 queries"}, + {"setECSSourcePrefixV6", true, "prefix-length", "the EDNS Client Subnet prefix-length used for IPv6 queries"}, + {"setKey", true, "key", "set access key to that key"}, + {"setLocal", true, R"(addr [, {doTCP=true, reusePort=false, tcpFastOpenQueueSize=0, interface="", cpus={}}])", "reset the list of addresses we listen on to this address"}, + {"setMaxCachedDoHConnectionsPerDownstream", true, "max", "Set the maximum number of inactive DoH connections to a backend cached by each worker DoH thread"}, + {"setMaxCachedTCPConnectionsPerDownstream", true, "max", "Set the maximum number of inactive TCP connections to a backend cached by each worker TCP thread"}, + {"setMaxTCPClientThreads", true, "n", "set the maximum of TCP client threads, handling TCP connections"}, + {"setMaxTCPConnectionDuration", true, "n", "set the maximum duration of an incoming TCP connection, in seconds. 0 means unlimited"}, + {"setMaxTCPConnectionsPerClient", true, "n", "set the maximum number of TCP connections per client. 0 means unlimited"}, + {"setMaxTCPQueriesPerConnection", true, "n", "set the maximum number of queries in an incoming TCP connection. 0 means unlimited"}, + {"setMaxTCPQueuedConnections", true, "n", "set the maximum number of TCP connections queued (waiting to be picked up by a client thread)"}, + {"setMaxUDPOutstanding", true, "n", "set the maximum number of outstanding UDP queries to a given backend server. This can only be set at configuration time and defaults to 65535"}, + {"setMetric", true, "name, value", "Set the value of a custom metric to the supplied value"}, + {"setPayloadSizeOnSelfGeneratedAnswers", true, "payloadSize", "set the UDP payload size advertised via EDNS on self-generated responses"}, + {"setPoolServerPolicy", true, "policy, pool", "set the server selection policy for this pool to that policy"}, + {"setPoolServerPolicyLua", true, "name, function, pool", "set the server selection policy for this pool to one named 'name' and provided by 'function'"}, + {"setPoolServerPolicyLuaFFI", true, "name, function, pool", "set the server selection policy for this pool to one named 'name' and provided by 'function'"}, + {"setPoolServerPolicyLuaFFIPerThread", true, "name, code", "set server selection policy for this pool to one named 'name' and returned by the Lua FFI code passed in 'code'"}, + {"setProxyProtocolACL", true, "{netmask, netmask}", "Set the netmasks who are allowed to send Proxy Protocol headers in front of queries/connections"}, + {"setProxyProtocolApplyACLToProxiedClients", true, "apply", "Whether the general ACL should be applied to the source IP address gathered from a Proxy Protocol header, in addition to being first applied to the source address seen by dnsdist"}, + {"setProxyProtocolMaximumPayloadSize", true, "max", "Set the maximum size of a Proxy Protocol payload, in bytes"}, + {"setQueryCount", true, "bool", "set whether queries should be counted"}, + {"setQueryCountFilter", true, "func", "filter queries that would be counted, where `func` is a function with parameter `dq` which decides whether a query should and how it should be counted"}, + {"SetReducedTTLResponseAction", true, "percentage", "Reduce the TTL of records in a response to a given percentage"}, + {"setRingBuffersLockRetries", true, "n", "set the number of attempts to get a non-blocking lock to a ringbuffer shard before blocking"}, + {"setRingBuffersOptions", true, "{ lockRetries=int, recordQueries=true, recordResponses=true }", "set ringbuffer options"}, + {"setRingBuffersSize", true, "n [, numberOfShards]", "set the capacity of the ringbuffers used for live traffic inspection to `n`, and optionally the number of shards to use to `numberOfShards`"}, + {"setRoundRobinFailOnNoServer", true, "value", "By default the roundrobin load-balancing policy will still try to select a backend even if all backends are currently down. Setting this to true will make the policy fail and return that no server is available instead"}, + {"setRules", true, "list of rules", "replace the current rules with the supplied list of pairs of DNS Rules and DNS Actions (see `newRuleAction()`)"}, + {"setSecurityPollInterval", true, "n", "set the security polling interval to `n` seconds"}, + {"setSecurityPollSuffix", true, "suffix", "set the security polling suffix to the specified value"}, + {"setServerPolicy", true, "policy", "set server selection policy to that policy"}, + {"setServerPolicyLua", true, "name, function", "set server selection policy to one named 'name' and provided by 'function'"}, + {"setServerPolicyLuaFFI", true, "name, function", "set server selection policy to one named 'name' and provided by the Lua FFI 'function'"}, + {"setServerPolicyLuaFFIPerThread", true, "name, code", "set server selection policy to one named 'name' and returned by the Lua FFI code passed in 'code'"}, + {"setServFailWhenNoServer", true, "bool", "if set, return a ServFail when no servers are available, instead of the default behaviour of dropping the query"}, + {"setStaleCacheEntriesTTL", true, "n", "allows using cache entries expired for at most n seconds when there is no backend available to answer for a query"}, + {"setStructuredLogging", true, "value [, options]", "set whether log messages should be in structured-logging-like format"}, + {"setSyslogFacility", true, "facility", "set the syslog logging facility to 'facility'. Defaults to LOG_DAEMON"}, + {"setTCPDownstreamCleanupInterval", true, "interval", "minimum interval in seconds between two cleanups of the idle TCP downstream connections"}, + {"setTCPFastOpenKey", true, "string", "TCP Fast Open Key"}, + {"setTCPDownstreamMaxIdleTime", true, "time", "Maximum time in seconds that a downstream TCP connection to a backend might stay idle"}, + {"setTCPInternalPipeBufferSize", true, "size", "Set the size in bytes of the internal buffer of the pipes used internally to distribute connections to TCP (and DoT) workers threads"}, + {"setTCPRecvTimeout", true, "n", "set the read timeout on TCP connections from the client, in seconds"}, + {"setTCPSendTimeout", true, "n", "set the write timeout on TCP connections from the client, in seconds"}, + {"setUDPMultipleMessagesVectorSize", true, "n", "set the size of the vector passed to recvmmsg() to receive UDP messages. Default to 1 which means that the feature is disabled and recvmsg() is used instead"}, + {"setUDPSocketBufferSizes", true, "recv, send", "Set the size of the receive (SO_RCVBUF) and send (SO_SNDBUF) buffers for incoming UDP sockets"}, + {"setUDPTimeout", true, "n", "set the maximum time dnsdist will wait for a response from a backend over UDP, in seconds"}, + {"setVerbose", true, "bool", "set whether log messages at the verbose level will be logged"}, + {"setVerboseHealthChecks", true, "bool", "set whether health check errors will be logged"}, + {"setVerboseLogDestination", true, "destination file", "Set a destination file to write the 'verbose' log messages to, instead of sending them to syslog and/or the standard output"}, + {"setWebserverConfig", true, "[{password=string, apiKey=string, customHeaders, statsRequireAuthentication}]", "Updates webserver configuration"}, + {"setWeightedBalancingFactor", true, "factor", "Set the balancing factor for bounded-load weighted policies (whashed, wrandom)"}, + {"setWHashedPertubation", true, "value", "Set the hash perturbation value to be used in the whashed policy instead of a random one, allowing to have consistent whashed results on different instance"}, + {"show", true, "string", "outputs `string`"}, + {"showACL", true, "", "show our ACL set"}, + {"showBinds", true, "", "show listening addresses (frontends)"}, + {"showCacheHitResponseRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined cache hit response rules, optionally with their UUIDs and optionally truncated to a given width"}, + {"showConsoleACL", true, "", "show our current console ACL set"}, + {"showDNSCryptBinds", true, "", "display the currently configured DNSCrypt binds"}, + {"showDOHFrontends", true, "", "list all the available DOH frontends"}, + {"showDOH3Frontends", true, "", "list all the available DOH3 frontends"}, + {"showDOHResponseCodes", true, "", "show the HTTP response code statistics for the DoH frontends"}, + {"showDOQFrontends", true, "", "list all the available DOQ frontends"}, + {"showDynBlocks", true, "", "show dynamic blocks in force"}, + {"showPools", true, "", "show the available pools"}, + {"showPoolServerPolicy", true, "pool", "show server selection policy for this pool"}, + {"showResponseLatency", true, "", "show a plot of the response time latency distribution"}, + {"showResponseRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined response rules, optionally with their UUIDs and optionally truncated to a given width"}, + {"showRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined rules, optionally with their UUIDs and optionally truncated to a given width"}, + {"showSecurityStatus", true, "", "Show the security status"}, + {"showSelfAnsweredResponseRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined self-answered response rules, optionally with their UUIDs and optionally truncated to a given width"}, + {"showServerPolicy", true, "", "show name of currently operational server selection policy"}, + {"showServers", true, "[{showUUIDs=false}]", "output all servers, optionally with their UUIDs"}, + {"showTCPStats", true, "", "show some statistics regarding TCP"}, + {"showTLSContexts", true, "", "list all the available TLS contexts"}, + {"showTLSErrorCounters", true, "", "show metrics about TLS handshake failures"}, + {"showVersion", true, "", "show the current version"}, + {"showWebserverConfig", true, "", "Show the current webserver configuration"}, + {"shutdown", true, "", "shut down `dnsdist`"}, + {"snmpAgent", true, "enableTraps [, daemonSocket]", "enable `SNMP` support. `enableTraps` is a boolean indicating whether traps should be sent and `daemonSocket` an optional string specifying how to connect to the daemon agent"}, + {"SetAdditionalProxyProtocolValueAction", true, "type, value", "Add a Proxy Protocol TLV value of this type"}, + {"SetDisableECSAction", true, "", "Disable the sending of ECS to the backend. Subsequent rules are processed after this action."}, + {"SetDisableValidationAction", true, "", "set the CD bit in the question, let it go through"}, + {"SetECSAction", true, "v4[, v6]", "Set the ECS prefix and prefix length sent to backends to an arbitrary value"}, + {"SetECSOverrideAction", true, "override", "Whether an existing EDNS Client Subnet value should be overridden (true) or not (false). Subsequent rules are processed after this action"}, + {"SetECSPrefixLengthAction", true, "v4, v6", "Set the ECS prefix length. Subsequent rules are processed after this action"}, + {"SetMacAddrAction", true, "option", "Add the source MAC address to the query as EDNS0 option option. This action is currently only supported on Linux. Subsequent rules are processed after this action"}, + {"SetEDNSOptionAction", true, "option, data", "Add arbitrary EDNS option and data to the query. Subsequent rules are processed after this action"}, + {"SetExtendedDNSErrorAction", true, "infoCode [, extraText]", "Set an Extended DNS Error status that will be added to the response corresponding to the current query. Subsequent rules are processed after this action"}, + {"SetExtendedDNSErrorResponseAction", true, "infoCode [, extraText]", "Set an Extended DNS Error status that will be added to this response. Subsequent rules are processed after this action"}, + {"SetNoRecurseAction", true, "", "strip RD bit from the question, let it go through"}, + {"setOutgoingDoHWorkerThreads", true, "n", "Number of outgoing DoH worker threads"}, + {"SetProxyProtocolValuesAction", true, "values", "Set the Proxy-Protocol values for this queries to 'values'"}, + {"SetSkipCacheAction", true, "", "Don’t lookup the cache for this query, don’t store the answer"}, + {"SetSkipCacheResponseAction", true, "", "Don’t store this response into the cache"}, + {"SetTagAction", true, "name, value", "set the tag named 'name' to the given value"}, + {"SetTagResponseAction", true, "name, value", "set the tag named 'name' to the given value"}, + {"SetTempFailureCacheTTLAction", true, "ttl", "set packetcache TTL for temporary failure replies"}, + {"SNIRule", true, "name", "Create a rule which matches on the incoming TLS SNI value, if any (DoT or DoH)"}, + {"SNMPTrapAction", true, "[reason]", "send an SNMP trap, adding the optional `reason` string as the query description"}, + {"SNMPTrapResponseAction", true, "[reason]", "send an SNMP trap, adding the optional `reason` string as the response description"}, + {"SpoofAction", true, "ip|list of ips [, options]", "forge a response with the specified IPv4 (for an A query) or IPv6 (for an AAAA). If you specify multiple addresses, all that match the query type (A, AAAA or ANY) will get spoofed in"}, + {"SpoofCNAMEAction", true, "cname [, options]", "Forge a response with the specified CNAME value"}, + {"SpoofRawAction", true, "raw|list of raws [, options]", "Forge a response with the specified record data as raw bytes. If you specify multiple raws (it is assumed they match the query type), all will get spoofed in"}, + {"SpoofSVCAction", true, "list of svcParams [, options]", "Forge a response with the specified SVC record data"}, + {"SuffixMatchNodeRule", true, "smn[, quiet]", "Matches based on a group of domain suffixes for rapid testing of membership. Pass true as second parameter to prevent listing of all domains matched"}, + {"TagRule", true, "name [, value]", "matches if the tag named 'name' is present, with the given 'value' matching if any"}, + {"TCAction", true, "", "create answer to query with TC and RD bits set, to move to TCP"}, + {"TCPRule", true, "[tcp]", "Matches question received over TCP if tcp is true, over UDP otherwise"}, + {"TCResponseAction", true, "", "truncate a response"}, + {"TeeAction", true, "remote [, addECS [, local]]", "send copy of query to remote, optionally adding ECS info, optionally set local address"}, + {"testCrypto", true, "", "test of the crypto all works"}, + {"TimedIPSetRule", true, "", "Create a rule which matches a set of IP addresses which expire"}, + {"topBandwidth", true, "top", "show top-`top` clients that consume the most bandwidth over length of ringbuffer"}, + {"topCacheHitResponseRules", true, "[top][, vars]", "show `top` cache-hit response rules"}, + {"topCacheInsertedResponseRules", true, "[top][, vars]", "show `top` cache-inserted response rules"}, + {"topClients", true, "n", "show top-`n` clients sending the most queries over length of ringbuffer"}, + {"topQueries", true, "n[, labels]", "show top 'n' queries, as grouped when optionally cut down to 'labels' labels"}, + {"topResponses", true, "n, kind[, labels]", "show top 'n' responses with RCODE=kind (0=NO Error, 2=ServFail, 3=NXDomain), as grouped when optionally cut down to 'labels' labels"}, + {"topResponseRules", true, "[top][, vars]", "show `top` response rules"}, + {"topRules", true, "[top][, vars]", "show `top` rules"}, + {"topSelfAnsweredResponseRules", true, "[top][, vars]", "show `top` self-answered response rules"}, + {"topSlow", true, "[top][, limit][, labels]", "show `top` queries slower than `limit` milliseconds, grouped by last `labels` labels"}, + {"TrailingDataRule", true, "", "Matches if the query has trailing data"}, + {"truncateTC", true, "bool", "if set (defaults to no starting with dnsdist 1.2.0) truncate TC=1 answers so they are actually empty. Fixes an issue for PowerDNS Authoritative Server 2.9.22. Note: turning this on breaks compatibility with RFC 6891."}, + {"unregisterDynBPFFilter", true, "DynBPFFilter", "unregister this dynamic BPF filter"}, + {"webserver", true, "address:port", "launch a webserver with stats on that address"}, + {"whashed", false, "", "Weighted hashed ('sticky') distribution over available servers, based on the server 'weight' parameter"}, + {"chashed", false, "", "Consistent hashed ('sticky') distribution over available servers, also based on the server 'weight' parameter"}, + {"wrandom", false, "", "Weighted random over available servers, based on the server 'weight' parameter"}, }; #if defined(HAVE_LIBEDIT) -extern "C" { -static char* my_generator(const char* text, int state) +extern "C" { - string textStr(text); - /* to keep it readable, we try to keep only 4 keywords per line - and to start a new line when the first letter changes */ - static int s_counter = 0; - int counter = 0; - if (state == 0) { - s_counter = 0; - } + static char* my_generator(const char* text, int state) + { + string textStr(text); + /* to keep it readable, we try to keep only 4 keywords per line + and to start a new line when the first letter changes */ + static int s_counter = 0; + int counter = 0; + if (state == 0) { + s_counter = 0; + } - for (const auto& keyword : g_consoleKeywords) { - if (boost::starts_with(keyword.name, textStr) && counter++ == s_counter) { - std::string value(keyword.name); - s_counter++; - if (keyword.function) { - value += "("; - if (keyword.parameters.empty()) { - value += ")"; + for (const auto& keyword : g_consoleKeywords) { + if (boost::starts_with(keyword.name, textStr) && counter++ == s_counter) { + std::string value(keyword.name); + s_counter++; + if (keyword.function) { + value += "("; + if (keyword.parameters.empty()) { + value += ")"; + } } + return strdup(value.c_str()); } - return strdup(value.c_str()); } + return nullptr; } - return nullptr; -} -char** my_completion( const char * text , int start, int end) -{ - char **matches = nullptr; - if (start == 0) { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast): readline - matches = rl_completion_matches (const_cast(text), &my_generator); - } + char** my_completion(const char* text, int start, int end) + { + char** matches = nullptr; + if (start == 0) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast): readline + matches = rl_completion_matches(const_cast(text), &my_generator); + } - // skip default filename completion. - rl_attempted_completion_over = 1; + // skip default filename completion. + rl_attempted_completion_over = 1; - return matches; -} + return matches; + } } #endif /* HAVE_LIBEDIT */ #endif /* DISABLE_COMPLETION */ @@ -938,37 +940,36 @@ static void controlClientThread(ConsoleConnection&& conn) string, shared_ptr, ClientState*, - std::unordered_map - > - > - >(withReturn ? ("return "+line) : line); + std::unordered_map>>>(withReturn ? ("return " + line) : line); if (ret) { if (const auto* dsValue = boost::get>(&*ret)) { if (*dsValue) { - response = (*dsValue)->getName()+"\n"; - } else { + response = (*dsValue)->getName() + "\n"; + } + else { response = ""; } } else if (const auto* csValue = boost::get(&*ret)) { if (*csValue != nullptr) { - response = (*csValue)->local.toStringWithPort()+"\n"; - } else { + response = (*csValue)->local.toStringWithPort() + "\n"; + } + else { response = ""; } } else if (const auto* strValue = boost::get(&*ret)) { - response = *strValue+"\n"; + response = *strValue + "\n"; } - else if (const auto* mapValue = boost::get >(&*ret)) { + else if (const auto* mapValue = boost::get>(&*ret)) { using namespace json11; Json::object obj; for (const auto& value : *mapValue) { obj[value.first] = value.second; } Json out = obj; - response = out.dump()+"\n"; + response = out.dump() + "\n"; } } else { @@ -987,12 +988,12 @@ static void controlClientThread(ConsoleConnection&& conn) throw; } } - catch(const LuaContext::WrongTypeException& e) { - response = "Command returned an object we can't print: " +std::string(e.what()) + "\n"; + catch (const LuaContext::WrongTypeException& e) { + response = "Command returned an object we can't print: " + std::string(e.what()) + "\n"; // tried to return something we don't understand } catch (const LuaContext::ExecutionErrorException& e) { - if (strcmp(e.what(),"invalid key to 'next'") == 0) { + if (strcmp(e.what(), "invalid key to 'next'") == 0) { response = "Error: Parsing function parameters, did you forget parameter name?"; } else { @@ -1001,9 +1002,10 @@ static void controlClientThread(ConsoleConnection&& conn) try { std::rethrow_if_nested(e); - } catch (const std::exception& ne) { + } + catch (const std::exception& ne) { // ne is the exception that was thrown from inside the lambda - response+= ": " + string(ne.what()); + response += ": " + string(ne.what()); } catch (const PDNSException& ne) { // ne is the exception that was thrown from inside the lambda @@ -1029,8 +1031,7 @@ static void controlClientThread(ConsoleConnection&& conn) // NOLINTNEXTLINE(performance-unnecessary-value-param): this is thread void controlThread(std::shared_ptr acceptFD, ComboAddress local) { - try - { + try { setThreadName("dnsdist/control"); ComboAddress client; int sock{-1}; diff --git a/pdns/dnsdistdist/dnsdist-console.hh b/pdns/dnsdistdist/dnsdist-console.hh index 6e227d47165d..dd833c49e473 100644 --- a/pdns/dnsdistdist/dnsdist-console.hh +++ b/pdns/dnsdistdist/dnsdist-console.hh @@ -25,7 +25,8 @@ #include "sstuff.hh" #ifndef DISABLE_COMPLETION -struct ConsoleKeyword { +struct ConsoleKeyword +{ std::string name; bool function; std::string parameters; @@ -42,8 +43,9 @@ struct ConsoleKeyword { } }; extern const std::vector g_consoleKeywords; -extern "C" { -char** my_completion( const char * text , int start, int end); +extern "C" +{ + char** my_completion(const char* text, int start, int end); } #endif /* DISABLE_COMPLETION */ diff --git a/pdns/dnsdistdist/dnsdist-dynbpf.cc b/pdns/dnsdistdist/dnsdist-dynbpf.cc index 9ede03fabf86..54902b367e6d 100644 --- a/pdns/dnsdistdist/dnsdist-dynbpf.cc +++ b/pdns/dnsdistdist/dnsdist-dynbpf.cc @@ -49,10 +49,10 @@ void DynBPFFilter::purgeExpired(const struct timespec& now) { auto data = d_data.lock(); - typedef boost::multi_index::nth_index::type ordered_until; + typedef boost::multi_index::nth_index::type ordered_until; ordered_until& ou = boost::multi_index::get<1>(data->d_entries); - for (ordered_until::iterator it = ou.begin(); it != ou.end(); ) { + for (ordered_until::iterator it = ou.begin(); it != ou.end();) { if (it->d_until < now) { ComboAddress addr = it->d_addr; it = ou.erase(it); @@ -64,9 +64,9 @@ void DynBPFFilter::purgeExpired(const struct timespec& now) } } -std::vector > DynBPFFilter::getAddrStats() +std::vector> DynBPFFilter::getAddrStats() { - std::vector > result; + std::vector> result; auto data = d_data.lock(); if (!data->d_bpf) { diff --git a/pdns/dnsdistdist/dnsdist-dynbpf.hh b/pdns/dnsdistdist/dnsdist-dynbpf.hh index 907a7300b9e8..cfb5d6b3c2ad 100644 --- a/pdns/dnsdistdist/dnsdist-dynbpf.hh +++ b/pdns/dnsdistdist/dnsdist-dynbpf.hh @@ -50,27 +50,28 @@ public: /* returns true if the addr wasn't already blocked, false otherwise */ bool block(const ComboAddress& addr, const struct timespec& until); void purgeExpired(const struct timespec& now); - std::vector > getAddrStats(); + std::vector> getAddrStats(); + private: struct BlockEntry { - BlockEntry(const ComboAddress& addr, const struct timespec until): d_addr(addr), d_until(until) + BlockEntry(const ComboAddress& addr, const struct timespec until) : + d_addr(addr), d_until(until) { } ComboAddress d_addr; struct timespec d_until; }; typedef boost::multi_index_container, ComboAddress::addressOnlyLessThan >, - boost::multi_index::ordered_non_unique< boost::multi_index::member > - > - > container_t; - struct Data { + boost::multi_index::indexed_by< + boost::multi_index::ordered_unique, ComboAddress::addressOnlyLessThan>, + boost::multi_index::ordered_non_unique>>> + container_t; + struct Data + { container_t d_entries; std::shared_ptr d_bpf{nullptr}; NetmaskGroup d_excludedSubnets; }; LockGuarded d_data; }; - diff --git a/pdns/dnsdistdist/dnsdist-ecs.cc b/pdns/dnsdistdist/dnsdist-ecs.cc index 2cad1945bca8..5fa61c5b1992 100644 --- a/pdns/dnsdistdist/dnsdist-ecs.cc +++ b/pdns/dnsdistdist/dnsdist-ecs.cc @@ -73,24 +73,24 @@ int rewriteResponseWithoutEDNS(const PacketBuffer& initialPacket, PacketBuffer& rrclass = pr.get16BitInt(); GenericDNSPacketWriter pw(newContent, rrname, rrtype, rrclass, dh->opcode); - pw.getHeader()->id=dh->id; - pw.getHeader()->qr=dh->qr; - pw.getHeader()->aa=dh->aa; - pw.getHeader()->tc=dh->tc; - pw.getHeader()->rd=dh->rd; - pw.getHeader()->ra=dh->ra; - pw.getHeader()->ad=dh->ad; - pw.getHeader()->cd=dh->cd; - pw.getHeader()->rcode=dh->rcode; + pw.getHeader()->id = dh->id; + pw.getHeader()->qr = dh->qr; + pw.getHeader()->aa = dh->aa; + pw.getHeader()->tc = dh->tc; + pw.getHeader()->rd = dh->rd; + pw.getHeader()->ra = dh->ra; + pw.getHeader()->ad = dh->ad; + pw.getHeader()->cd = dh->cd; + pw.getHeader()->rcode = dh->rcode; /* consume remaining qd if any */ if (qdcount > 1) { - for(idx = 1; idx < qdcount; idx++) { + for (idx = 1; idx < qdcount; idx++) { rrname = pr.getName(); rrtype = pr.get16BitInt(); rrclass = pr.get16BitInt(); - (void) rrtype; - (void) rrclass; + (void)rrtype; + (void)rrclass; } } @@ -121,7 +121,8 @@ int rewriteResponseWithoutEDNS(const PacketBuffer& initialPacket, PacketBuffer& pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::ADDITIONAL, true); pr.xfrBlob(blob); pw.xfrBlob(blob); - } else { + } + else { pr.skip(ah.d_clen); } @@ -133,7 +134,7 @@ int rewriteResponseWithoutEDNS(const PacketBuffer& initialPacket, PacketBuffer& static bool addOrReplaceEDNSOption(std::vector>& options, uint16_t optionCode, bool& optionAdded, bool overrideExisting, const string& newOptionContent) { - for (auto it = options.begin(); it != options.end(); ) { + for (auto it = options.begin(); it != options.end();) { if (it->first == optionCode) { optionAdded = false; @@ -186,24 +187,24 @@ bool slowRewriteEDNSOptionInQueryWithRecords(const PacketBuffer& initialPacket, rrclass = pr.get16BitInt(); GenericDNSPacketWriter pw(newContent, rrname, rrtype, rrclass, dh->opcode); - pw.getHeader()->id=dh->id; - pw.getHeader()->qr=dh->qr; - pw.getHeader()->aa=dh->aa; - pw.getHeader()->tc=dh->tc; - pw.getHeader()->rd=dh->rd; - pw.getHeader()->ra=dh->ra; - pw.getHeader()->ad=dh->ad; - pw.getHeader()->cd=dh->cd; - pw.getHeader()->rcode=dh->rcode; + pw.getHeader()->id = dh->id; + pw.getHeader()->qr = dh->qr; + pw.getHeader()->aa = dh->aa; + pw.getHeader()->tc = dh->tc; + pw.getHeader()->rd = dh->rd; + pw.getHeader()->ra = dh->ra; + pw.getHeader()->ad = dh->ad; + pw.getHeader()->cd = dh->cd; + pw.getHeader()->rcode = dh->rcode; /* consume remaining qd if any */ if (qdcount > 1) { - for(idx = 1; idx < qdcount; idx++) { + for (idx = 1; idx < qdcount; idx++) { rrname = pr.getName(); rrtype = pr.get16BitInt(); rrclass = pr.get16BitInt(); - (void) rrtype; - (void) rrclass; + (void)rrtype; + (void)rrclass; } } @@ -235,7 +236,8 @@ bool slowRewriteEDNSOptionInQueryWithRecords(const PacketBuffer& initialPacket, pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::ADDITIONAL, true); pr.xfrBlob(blob); pw.xfrBlob(blob); - } else { + } + else { ednsAdded = false; pr.xfrBlob(blob); @@ -286,13 +288,13 @@ static bool slowParseEDNSOptions(const PacketBuffer& packet, EDNSOptionViewMap& uint64_t numrecords = ntohs(dh->ancount) + ntohs(dh->nscount) + ntohs(dh->arcount); DNSPacketMangler dpm(const_cast(reinterpret_cast(&packet.at(0))), packet.size()); uint64_t n; - for(n=0; n < ntohs(dh->qdcount) ; ++n) { + for (n = 0; n < ntohs(dh->qdcount); ++n) { dpm.skipDomainName(); /* type and class */ dpm.skipBytes(4); } - for(n=0; n < numrecords; ++n) { + for (n = 0; n < numrecords; ++n) { dpm.skipDomainName(); uint8_t section = n < ntohs(dh->ancount) ? 1 : (n < (ntohs(dh->ancount) + ntohs(dh->nscount)) ? 2 : 3); @@ -300,7 +302,7 @@ static bool slowParseEDNSOptions(const PacketBuffer& packet, EDNSOptionViewMap& dpm.get16BitInt(); dpm.skipBytes(4); /* TTL */ - if(section == 3 && dnstype == QType::OPT) { + if (section == 3 && dnstype == QType::OPT) { uint32_t offset = dpm.getOffset(); if (offset >= packet.size()) { return false; @@ -314,15 +316,14 @@ static bool slowParseEDNSOptions(const PacketBuffer& packet, EDNSOptionViewMap& } } } - catch(...) - { + catch (...) { return false; } return true; } -int locateEDNSOptRR(const PacketBuffer& packet, uint16_t * optStart, size_t * optLen, bool * last) +int locateEDNSOptRR(const PacketBuffer& packet, uint16_t* optStart, size_t* optLen, bool* last) { assert(optStart != NULL); assert(optLen != NULL); @@ -346,12 +347,12 @@ int locateEDNSOptRR(const PacketBuffer& packet, uint16_t * optStart, size_t * op struct dnsrecordheader ah; /* consume qd */ - for(idx = 0; idx < qdcount; idx++) { + for (idx = 0; idx < qdcount; idx++) { rrname = pr.getName(); rrtype = pr.get16BitInt(); rrclass = pr.get16BitInt(); - (void) rrtype; - (void) rrclass; + (void)rrtype; + (void)rrclass; } /* consume AN and NS */ @@ -375,7 +376,7 @@ int locateEDNSOptRR(const PacketBuffer& packet, uint16_t * optStart, size_t * op throw std::range_error("Opt record overflow"); } - if (idx == ((size_t) arcount - 1)) { + if (idx == ((size_t)arcount - 1)) { *last = true; } else { @@ -420,7 +421,7 @@ int getEDNSOptionsStart(const PacketBuffer& packet, const size_t offset, uint16_ } pos += 1; - uint16_t qtype = packet.at(pos)*256 + packet.at(pos+1); + uint16_t qtype = packet.at(pos) * 256 + packet.at(pos + 1); pos += DNS_TYPE_SIZE; pos += DNS_CLASS_SIZE; @@ -647,7 +648,8 @@ bool handleEDNSClientSubnet(PacketBuffer& packet, const size_t maximumSize, cons } return replaceEDNSClientSubnetOption(packet, maximumSize, optRDPosition + ecsOptionStartPosition, ecsOptionSize, optRDPosition, newECSOption); - } else { + } + else { /* we have an EDNS OPT RR but no existing ECS option */ return addECSToExistingOPT(packet, maximumSize, newECSOption, optRDPosition, ecsAdded); } @@ -669,10 +671,10 @@ static int removeEDNSOptionFromOptions(unsigned char* optionsStart, const uint16 size_t pos = 0; while ((pos + 4) <= optionsLen) { unsigned char* optionBegin = p; - const uint16_t optionCode = 0x100*p[0] + p[1]; + const uint16_t optionCode = 0x100 * p[0] + p[1]; p += sizeof(optionCode); pos += sizeof(optionCode); - const uint16_t optionLen = 0x100*p[0] + p[1]; + const uint16_t optionLen = 0x100 * p[0] + p[1]; p += sizeof(optionLen); pos += sizeof(optionLen); if ((pos + optionLen) > optionsLen) { @@ -698,10 +700,10 @@ int removeEDNSOptionFromOPT(char* optStart, size_t* optLen, const uint16_t optio if (*optLen < optRecordMinimumSize) { return EINVAL; } - const unsigned char* end = (const unsigned char*) optStart + *optLen; - unsigned char* p = (unsigned char*) optStart + 9; + const unsigned char* end = (const unsigned char*)optStart + *optLen; + unsigned char* p = (unsigned char*)optStart + 9; unsigned char* rdLenPtr = p; - uint16_t rdLen = (0x100*p[0] + p[1]); + uint16_t rdLen = (0x100 * p[0] + p[1]); p += sizeof(rdLen); if (p + rdLen != end) { return EINVAL; @@ -723,7 +725,7 @@ bool isEDNSOptionInOpt(const PacketBuffer& packet, const size_t optStart, const return false; } size_t p = optStart + 9; - uint16_t rdLen = (0x100*static_cast(packet.at(p)) + static_cast(packet.at(p+1))); + uint16_t rdLen = (0x100 * static_cast(packet.at(p)) + static_cast(packet.at(p + 1))); p += sizeof(rdLen); if (rdLen > (optLen - optRecordMinimumSize)) { return false; @@ -731,9 +733,9 @@ bool isEDNSOptionInOpt(const PacketBuffer& packet, const size_t optStart, const size_t rdEnd = p + rdLen; while ((p + 4) <= rdEnd) { - const uint16_t optionCode = 0x100*static_cast(packet.at(p)) + static_cast(packet.at(p+1)); + const uint16_t optionCode = 0x100 * static_cast(packet.at(p)) + static_cast(packet.at(p + 1)); p += sizeof(optionCode); - const uint16_t optionLen = 0x100*static_cast(packet.at(p)) + static_cast(packet.at(p+1)); + const uint16_t optionLen = 0x100 * static_cast(packet.at(p)) + static_cast(packet.at(p + 1)); p += sizeof(optionLen); if ((p + optionLen) > rdEnd) { @@ -785,24 +787,24 @@ int rewriteResponseWithoutEDNSOption(const PacketBuffer& initialPacket, const ui rrclass = pr.get16BitInt(); GenericDNSPacketWriter pw(newContent, rrname, rrtype, rrclass, dh->opcode); - pw.getHeader()->id=dh->id; - pw.getHeader()->qr=dh->qr; - pw.getHeader()->aa=dh->aa; - pw.getHeader()->tc=dh->tc; - pw.getHeader()->rd=dh->rd; - pw.getHeader()->ra=dh->ra; - pw.getHeader()->ad=dh->ad; - pw.getHeader()->cd=dh->cd; - pw.getHeader()->rcode=dh->rcode; + pw.getHeader()->id = dh->id; + pw.getHeader()->qr = dh->qr; + pw.getHeader()->aa = dh->aa; + pw.getHeader()->tc = dh->tc; + pw.getHeader()->rd = dh->rd; + pw.getHeader()->ra = dh->ra; + pw.getHeader()->ad = dh->ad; + pw.getHeader()->cd = dh->cd; + pw.getHeader()->rcode = dh->rcode; /* consume remaining qd if any */ if (qdcount > 1) { - for(idx = 1; idx < qdcount; idx++) { + for (idx = 1; idx < qdcount; idx++) { rrname = pr.getName(); rrtype = pr.get16BitInt(); rrclass = pr.get16BitInt(); - (void) rrtype; - (void) rrclass; + (void)rrtype; + (void)rrclass; } } @@ -834,7 +836,8 @@ int rewriteResponseWithoutEDNSOption(const PacketBuffer& initialPacket, const ui pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::ADDITIONAL, true); pr.xfrBlob(blob); pw.xfrBlob(blob); - } else { + } + else { pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::ADDITIONAL, false); pr.xfrBlob(blob); uint16_t rdLen = blob.length(); @@ -843,7 +846,8 @@ int rewriteResponseWithoutEDNSOption(const PacketBuffer& initialPacket, const ui if (rdLen > 0) { blob.resize((size_t)rdLen); pw.xfrBlob(blob); - } else { + } + else { pw.commit(); } } @@ -952,7 +956,8 @@ bool setNegativeAndAdditionalSOA(DNSQuestion& dq, bool nxd, const DNSName& zone, dnsdist::PacketMangling::editDNSHeaderFromPacket(packet, [soaInAuthoritySection](dnsheader& header) { if (soaInAuthoritySection) { header.nscount = htons(1); - } else { + } + else { header.arcount = htons(1); } return true; @@ -1012,8 +1017,7 @@ bool addEDNSToQueryTurnedResponse(DNSQuestion& dq) // goal in life - if you send us a reasonably normal packet, we'll get Z for you, otherwise 0 int getEDNSZ(const DNSQuestion& dq) { - try - { + try { const auto& dh = dq.getHeader(); if (ntohs(dh->qdcount) != 1 || dh->ancount != 0 || ntohs(dh->arcount) != 1 || dh->nscount != 0) { return 0; @@ -1038,7 +1042,7 @@ int getEDNSZ(const DNSQuestion& dq) pos++; - uint16_t qtype = packet.at(pos)*256 + packet.at(pos+1); + uint16_t qtype = packet.at(pos) * 256 + packet.at(pos + 1); pos += DNS_TYPE_SIZE; pos += DNS_CLASS_SIZE; @@ -1047,10 +1051,9 @@ int getEDNSZ(const DNSQuestion& dq) } const uint8_t* z = &packet.at(pos + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE); - return 0x100 * (*z) + *(z+1); + return 0x100 * (*z) + *(z + 1); } - catch(...) - { + catch (...) { return 0; } } @@ -1134,8 +1137,9 @@ bool setEDNSOption(DNSQuestion& dq, uint16_t ednsCode, const std::string& ednsDa return true; } -namespace dnsdist { -bool setInternalQueryRCode(InternalQueryState& state, PacketBuffer& buffer, uint8_t rcode, bool clearAnswers) +namespace dnsdist +{ +bool setInternalQueryRCode(InternalQueryState& state, PacketBuffer& buffer, uint8_t rcode, bool clearAnswers) { const auto qnameLength = state.qname.wirelength(); if (buffer.size() < sizeof(dnsheader) + qnameLength + sizeof(uint16_t) + sizeof(uint16_t)) { @@ -1148,7 +1152,7 @@ bool setInternalQueryRCode(InternalQueryState& state, PacketBuffer& buffer, uin hadEDNS = getEDNS0Record(buffer, edns0); } - dnsdist::PacketMangling::editDNSHeaderFromPacket(buffer, [rcode,clearAnswers](dnsheader& header) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(buffer, [rcode, clearAnswers](dnsheader& header) { header.rcode = rcode; header.ad = false; header.aa = false; diff --git a/pdns/dnsdistdist/dnsdist-ecs.hh b/pdns/dnsdistdist/dnsdist-ecs.hh index f5d215f1a065..3af754d8af42 100644 --- a/pdns/dnsdistdist/dnsdist-ecs.hh +++ b/pdns/dnsdistdist/dnsdist-ecs.hh @@ -36,12 +36,12 @@ extern uint16_t g_PayloadSizeSelfGenAnswers; int rewriteResponseWithoutEDNS(const PacketBuffer& initialPacket, PacketBuffer& newContent); bool slowRewriteEDNSOptionInQueryWithRecords(const PacketBuffer& initialPacket, PacketBuffer& newContent, bool& ednsAdded, uint16_t optionToReplace, bool& optionAdded, bool overrideExisting, const string& newOptionContent); -int locateEDNSOptRR(const PacketBuffer & packet, uint16_t * optStart, size_t * optLen, bool * last); +int locateEDNSOptRR(const PacketBuffer& packet, uint16_t* optStart, size_t* optLen, bool* last); bool generateOptRR(const std::string& optRData, PacketBuffer& res, size_t maximumSize, uint16_t udpPayloadSize, uint8_t ednsrcode, bool dnssecOK); void generateECSOption(const ComboAddress& source, string& res, uint16_t ECSPrefixLength); int removeEDNSOptionFromOPT(char* optStart, size_t* optLen, const uint16_t optionCodeToRemove); int rewriteResponseWithoutEDNSOption(const PacketBuffer& initialPacket, const uint16_t optionCodeToSkip, PacketBuffer& newContent); -int getEDNSOptionsStart(const PacketBuffer& packet, const size_t offset, uint16_t* optRDPosition, size_t * remaining); +int getEDNSOptionsStart(const PacketBuffer& packet, const size_t offset, uint16_t* optRDPosition, size_t* remaining); bool isEDNSOptionInOpt(const PacketBuffer& packet, const size_t optStart, const size_t optLen, const uint16_t optionCodeToFind, size_t* optContentStart = nullptr, uint16_t* optContentLen = nullptr); bool addEDNS(PacketBuffer& packet, size_t maximumSize, bool dnssecOK, uint16_t payloadSize, uint8_t ednsrcode); bool addEDNSToQueryTurnedResponse(DNSQuestion& dq); @@ -59,6 +59,7 @@ bool getEDNS0Record(const PacketBuffer& packet, EDNS0Record& edns0); bool setEDNSOption(DNSQuestion& dq, uint16_t ednsCode, const std::string& data); struct InternalQueryState; -namespace dnsdist { -bool setInternalQueryRCode(InternalQueryState& state, PacketBuffer& buffer, uint8_t rcode, bool clearAnswers); +namespace dnsdist +{ +bool setInternalQueryRCode(InternalQueryState& state, PacketBuffer& buffer, uint8_t rcode, bool clearAnswers); } diff --git a/pdns/dnsdistdist/dnsdist-lbpolicies.hh b/pdns/dnsdistdist/dnsdist-lbpolicies.hh index 72443402d10f..78fcb22016b2 100644 --- a/pdns/dnsdistdist/dnsdist-lbpolicies.hh +++ b/pdns/dnsdistdist/dnsdist-lbpolicies.hh @@ -32,16 +32,19 @@ struct PerThreadPoliciesState; class ServerPolicy { public: - template using NumberedVector = std::vector >; + template + using NumberedVector = std::vector>; using NumberedServerVector = NumberedVector>; typedef std::function(const NumberedServerVector& servers, const DNSQuestion*)> policyfunc_t; typedef std::function ffipolicyfunc_t; - ServerPolicy(const std::string& name_, policyfunc_t policy_, bool isLua_): d_name(name_), d_policy(std::move(policy_)), d_isLua(isLua_) + ServerPolicy(const std::string& name_, policyfunc_t policy_, bool isLua_) : + d_name(name_), d_policy(std::move(policy_)), d_isLua(isLua_) { } - ServerPolicy(const std::string& name_, ffipolicyfunc_t policy_): d_name(name_), d_ffipolicy(std::move(policy_)), d_isLua(true), d_isFFI(true) + ServerPolicy(const std::string& name_, ffipolicyfunc_t policy_) : + d_name(name_), d_ffipolicy(std::move(policy_)), d_isLua(true), d_isFFI(true) { } @@ -59,7 +62,8 @@ public: return d_name; } - std::string toString() const { + std::string toString() const + { return string("ServerPolicy") + (d_isLua ? " (Lua)" : "") + " \"" + d_name + "\""; } @@ -74,7 +78,6 @@ private: const ffipolicyfunc_t& getPerThreadPolicy() const; static thread_local PerThreadState t_perThreadState; - public: std::string d_name; std::string d_perThreadPolicyCode; @@ -96,7 +99,7 @@ void setPoolPolicy(pools_t& pools, const string& poolName, std::shared_ptr server); void removeServerFromPool(pools_t& pools, const string& poolName, std::shared_ptr server); -const std::shared_ptr getDownstreamCandidates(const map>& pools, const std::string& poolName); +const std::shared_ptr getDownstreamCandidates(const map>& pools, const std::string& poolName); std::shared_ptr firstAvailable(const ServerPolicy::NumberedServerVector& servers, const DNSQuestion* dq); diff --git a/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc b/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc index 4512fc5ef4f8..deb8c3f7aca5 100644 --- a/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc +++ b/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc @@ -33,80 +33,88 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) #ifndef DISABLE_NON_FFI_DQ_BINDINGS /* DNSQuestion */ /* PowerDNS DNSQuestion compat */ - luaCtx.registerMember("localaddr", [](const DNSQuestion& dq) -> const ComboAddress { return dq.ids.origDest; }, [](DNSQuestion& dq, const ComboAddress newLocal) { (void) newLocal; }); - luaCtx.registerMember("qname", [](const DNSQuestion& dq) -> const DNSName { return dq.ids.qname; }, [](DNSQuestion& dq, const DNSName& newName) { (void) newName; }); - luaCtx.registerMember("qtype", [](const DNSQuestion& dq) -> uint16_t { return dq.ids.qtype; }, [](DNSQuestion& dq, uint16_t newType) { (void) newType; }); - luaCtx.registerMember("qclass", [](const DNSQuestion& dq) -> uint16_t { return dq.ids.qclass; }, [](DNSQuestion& dq, uint16_t newClass) { (void) newClass; }); - luaCtx.registerMember("rcode", [](const DNSQuestion& dq) -> int { return static_cast(dq.getHeader()->rcode); }, [](DNSQuestion& dq, int newRCode) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [newRCode](dnsheader& header) { - header.rcode = static_cast(newRCode); - return true; - }); - }); - luaCtx.registerMember("remoteaddr", [](const DNSQuestion& dq) -> const ComboAddress { return dq.ids.origRemote; }, [](DNSQuestion& dq, const ComboAddress newRemote) { (void) newRemote; }); + luaCtx.registerMember( + "localaddr", [](const DNSQuestion& dq) -> const ComboAddress { return dq.ids.origDest; }, [](DNSQuestion& dq, const ComboAddress newLocal) { (void)newLocal; }); + luaCtx.registerMember( + "qname", [](const DNSQuestion& dq) -> const DNSName { return dq.ids.qname; }, [](DNSQuestion& dq, const DNSName& newName) { (void)newName; }); + luaCtx.registerMember( + "qtype", [](const DNSQuestion& dq) -> uint16_t { return dq.ids.qtype; }, [](DNSQuestion& dq, uint16_t newType) { (void)newType; }); + luaCtx.registerMember( + "qclass", [](const DNSQuestion& dq) -> uint16_t { return dq.ids.qclass; }, [](DNSQuestion& dq, uint16_t newClass) { (void)newClass; }); + luaCtx.registerMember( + "rcode", [](const DNSQuestion& dq) -> int { return static_cast(dq.getHeader()->rcode); }, [](DNSQuestion& dq, int newRCode) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [newRCode](dnsheader& header) { + header.rcode = static_cast(newRCode); + return true; + }); }); + luaCtx.registerMember( + "remoteaddr", [](const DNSQuestion& dq) -> const ComboAddress { return dq.ids.origRemote; }, [](DNSQuestion& dq, const ComboAddress newRemote) { (void)newRemote; }); /* DNSDist DNSQuestion */ - luaCtx.registerMember("dh", [](const DNSQuestion& dq) -> dnsheader* { return dq.getMutableHeader(); }, [](DNSQuestion& dq, const dnsheader* dh) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [&dh](dnsheader& header) { - header = *dh; - return true; - }); - }); - luaCtx.registerMember("len", [](const DNSQuestion& dq) -> uint16_t { return dq.getData().size(); }, [](DNSQuestion& dq, uint16_t newlen) { dq.getMutableData().resize(newlen); }); - luaCtx.registerMember("opcode", [](const DNSQuestion& dq) -> uint8_t { return dq.getHeader()->opcode; }, [](DNSQuestion& dq, uint8_t newOpcode) { (void) newOpcode; }); - luaCtx.registerMember("tcp", [](const DNSQuestion& dq) -> bool { return dq.overTCP(); }, [](DNSQuestion& dq, bool newTcp) { (void) newTcp; }); - luaCtx.registerMember("skipCache", [](const DNSQuestion& dq) -> bool { return dq.ids.skipCache; }, [](DNSQuestion& dq, bool newSkipCache) { dq.ids.skipCache = newSkipCache; }); - luaCtx.registerMember("pool", [](const DNSQuestion& dq) -> std::string { return dq.ids.poolName; }, [](DNSQuestion& dq, const std::string& newPoolName) { dq.ids.poolName = newPoolName; }); - luaCtx.registerMember("useECS", [](const DNSQuestion& dq) -> bool { return dq.useECS; }, [](DNSQuestion& dq, bool useECS) { dq.useECS = useECS; }); - luaCtx.registerMember("ecsOverride", [](const DNSQuestion& dq) -> bool { return dq.ecsOverride; }, [](DNSQuestion& dq, bool ecsOverride) { dq.ecsOverride = ecsOverride; }); - luaCtx.registerMember("ecsPrefixLength", [](const DNSQuestion& dq) -> uint16_t { return dq.ecsPrefixLength; }, [](DNSQuestion& dq, uint16_t newPrefixLength) { dq.ecsPrefixLength = newPrefixLength; }); - luaCtx.registerMember (DNSQuestion::*)>("tempFailureTTL", - [](const DNSQuestion& dq) -> boost::optional { - return dq.ids.tempFailureTTL; - }, - [](DNSQuestion& dq, boost::optional newValue) { - dq.ids.tempFailureTTL = newValue; - } - ); - luaCtx.registerMember("deviceID", [](const DNSQuestion& dq) -> std::string { + luaCtx.registerMember( + "dh", [](const DNSQuestion& dq) -> dnsheader* { return dq.getMutableHeader(); }, [](DNSQuestion& dq, const dnsheader* dh) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [&dh](dnsheader& header) { + header = *dh; + return true; + }); }); + luaCtx.registerMember( + "len", [](const DNSQuestion& dq) -> uint16_t { return dq.getData().size(); }, [](DNSQuestion& dq, uint16_t newlen) { dq.getMutableData().resize(newlen); }); + luaCtx.registerMember( + "opcode", [](const DNSQuestion& dq) -> uint8_t { return dq.getHeader()->opcode; }, [](DNSQuestion& dq, uint8_t newOpcode) { (void)newOpcode; }); + luaCtx.registerMember( + "tcp", [](const DNSQuestion& dq) -> bool { return dq.overTCP(); }, [](DNSQuestion& dq, bool newTcp) { (void)newTcp; }); + luaCtx.registerMember( + "skipCache", [](const DNSQuestion& dq) -> bool { return dq.ids.skipCache; }, [](DNSQuestion& dq, bool newSkipCache) { dq.ids.skipCache = newSkipCache; }); + luaCtx.registerMember( + "pool", [](const DNSQuestion& dq) -> std::string { return dq.ids.poolName; }, [](DNSQuestion& dq, const std::string& newPoolName) { dq.ids.poolName = newPoolName; }); + luaCtx.registerMember( + "useECS", [](const DNSQuestion& dq) -> bool { return dq.useECS; }, [](DNSQuestion& dq, bool useECS) { dq.useECS = useECS; }); + luaCtx.registerMember( + "ecsOverride", [](const DNSQuestion& dq) -> bool { return dq.ecsOverride; }, [](DNSQuestion& dq, bool ecsOverride) { dq.ecsOverride = ecsOverride; }); + luaCtx.registerMember( + "ecsPrefixLength", [](const DNSQuestion& dq) -> uint16_t { return dq.ecsPrefixLength; }, [](DNSQuestion& dq, uint16_t newPrefixLength) { dq.ecsPrefixLength = newPrefixLength; }); + luaCtx.registerMember(DNSQuestion::*)>( + "tempFailureTTL", + [](const DNSQuestion& dq) -> boost::optional { + return dq.ids.tempFailureTTL; + }, + [](DNSQuestion& dq, boost::optional newValue) { + dq.ids.tempFailureTTL = newValue; + }); + luaCtx.registerMember( + "deviceID", [](const DNSQuestion& dq) -> std::string { if (dq.ids.d_protoBufData) { return dq.ids.d_protoBufData->d_deviceID; } - return std::string(); - }, [](DNSQuestion& dq, const std::string& newValue) { + return std::string(); }, [](DNSQuestion& dq, const std::string& newValue) { if (!dq.ids.d_protoBufData) { dq.ids.d_protoBufData = std::make_unique(); } - dq.ids.d_protoBufData->d_deviceID = newValue; - }); - luaCtx.registerMember("deviceName", [](const DNSQuestion& dq) -> std::string { + dq.ids.d_protoBufData->d_deviceID = newValue; }); + luaCtx.registerMember( + "deviceName", [](const DNSQuestion& dq) -> std::string { if (dq.ids.d_protoBufData) { return dq.ids.d_protoBufData->d_deviceName; } - return std::string(); - }, [](DNSQuestion& dq, const std::string& newValue) { + return std::string(); }, [](DNSQuestion& dq, const std::string& newValue) { if (!dq.ids.d_protoBufData) { dq.ids.d_protoBufData = std::make_unique(); } - dq.ids.d_protoBufData->d_deviceName = newValue; - }); - luaCtx.registerMember("requestorID", [](const DNSQuestion& dq) -> std::string { + dq.ids.d_protoBufData->d_deviceName = newValue; }); + luaCtx.registerMember( + "requestorID", [](const DNSQuestion& dq) -> std::string { if (dq.ids.d_protoBufData) { return dq.ids.d_protoBufData->d_requestorID; } - return std::string(); - }, [](DNSQuestion& dq, const std::string& newValue) { + return std::string(); }, [](DNSQuestion& dq, const std::string& newValue) { if (!dq.ids.d_protoBufData) { dq.ids.d_protoBufData = std::make_unique(); } - dq.ids.d_protoBufData->d_requestorID = newValue; - }); - luaCtx.registerFunction("getDO", [](const DNSQuestion& dq) { + dq.ids.d_protoBufData->d_requestorID = newValue; }); + luaCtx.registerFunction("getDO", [](const DNSQuestion& dq) { return getEDNSZ(dq) & EDNS_HEADER_FLAG_DO; - }); - luaCtx.registerFunction("getContent", [](const DNSQuestion& dq) { + }); + luaCtx.registerFunction("getContent", [](const DNSQuestion& dq) { return std::string(reinterpret_cast(dq.getData().data()), dq.getData().size()); }); - luaCtx.registerFunction("setContent", [](DNSQuestion& dq, const std::string& raw) { + luaCtx.registerFunction("setContent", [](DNSQuestion& dq, const std::string& raw) { uint16_t oldID = dq.getHeader()->id; auto& buffer = dq.getMutableData(); buffer.clear(); @@ -117,73 +125,73 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) return true; }); }); - luaCtx.registerFunction(DNSQuestion::*)()const>("getEDNSOptions", [](const DNSQuestion& dq) { + luaCtx.registerFunction (DNSQuestion::*)() const>("getEDNSOptions", [](const DNSQuestion& dq) { + if (dq.ednsOptions == nullptr) { + parseEDNSOptions(dq); if (dq.ednsOptions == nullptr) { - parseEDNSOptions(dq); - if (dq.ednsOptions == nullptr) { - throw std::runtime_error("parseEDNSOptions should have populated the EDNS options"); - } + throw std::runtime_error("parseEDNSOptions should have populated the EDNS options"); } + } - return *dq.ednsOptions; - }); - luaCtx.registerFunction("getTrailingData", [](const DNSQuestion& dq) { - return dq.getTrailingData(); - }); - luaCtx.registerFunction("setTrailingData", [](DNSQuestion& dq, const std::string& tail) { - return dq.setTrailingData(tail); - }); + return *dq.ednsOptions; + }); + luaCtx.registerFunction("getTrailingData", [](const DNSQuestion& dq) { + return dq.getTrailingData(); + }); + luaCtx.registerFunction("setTrailingData", [](DNSQuestion& dq, const std::string& tail) { + return dq.setTrailingData(tail); + }); - luaCtx.registerFunction("getServerNameIndication", [](const DNSQuestion& dq) { - return dq.sni; - }); + luaCtx.registerFunction("getServerNameIndication", [](const DNSQuestion& dq) { + return dq.sni; + }); - luaCtx.registerFunction("getProtocol", [](const DNSQuestion& dq) { + luaCtx.registerFunction("getProtocol", [](const DNSQuestion& dq) { return dq.getProtocol().toPrettyString(); }); - luaCtx.registerFunction("getQueryTime", [](const DNSQuestion& dq) { + luaCtx.registerFunction("getQueryTime", [](const DNSQuestion& dq) { return dq.ids.queryRealTime.getStartTime(); }); - luaCtx.registerFunction("sendTrap", [](const DNSQuestion& dq, boost::optional reason) { + luaCtx.registerFunction("sendTrap", [](const DNSQuestion& dq, boost::optional reason) { #ifdef HAVE_NET_SNMP - if (g_snmpAgent && g_snmpTrapsEnabled) { - g_snmpAgent->sendDNSTrap(dq, reason ? *reason : ""); - } + if (g_snmpAgent && g_snmpTrapsEnabled) { + g_snmpAgent->sendDNSTrap(dq, reason ? *reason : ""); + } #endif /* HAVE_NET_SNMP */ - }); + }); - luaCtx.registerFunction("setTag", [](DNSQuestion& dq, const std::string& strLabel, const std::string& strValue) { - dq.setTag(strLabel, strValue); - }); - luaCtx.registerFunction)>("setTagArray", [](DNSQuestion& dq, const LuaAssociativeTable&tags) { - for (const auto& tag : tags) { - dq.setTag(tag.first, tag.second); - } - }); - luaCtx.registerFunction("getTag", [](const DNSQuestion& dq, const std::string& strLabel) { - if (!dq.ids.qTag) { - return string(); - } + luaCtx.registerFunction("setTag", [](DNSQuestion& dq, const std::string& strLabel, const std::string& strValue) { + dq.setTag(strLabel, strValue); + }); + luaCtx.registerFunction)>("setTagArray", [](DNSQuestion& dq, const LuaAssociativeTable& tags) { + for (const auto& tag : tags) { + dq.setTag(tag.first, tag.second); + } + }); + luaCtx.registerFunction("getTag", [](const DNSQuestion& dq, const std::string& strLabel) { + if (!dq.ids.qTag) { + return string(); + } - std::string strValue; - const auto it = dq.ids.qTag->find(strLabel); - if (it == dq.ids.qTag->cend()) { - return string(); - } - return it->second; - }); - luaCtx.registerFunction("getTagArray", [](const DNSQuestion& dq) { - if (!dq.ids.qTag) { - QTag empty; - return empty; - } + std::string strValue; + const auto it = dq.ids.qTag->find(strLabel); + if (it == dq.ids.qTag->cend()) { + return string(); + } + return it->second; + }); + luaCtx.registerFunction("getTagArray", [](const DNSQuestion& dq) { + if (!dq.ids.qTag) { + QTag empty; + return empty; + } - return *dq.ids.qTag; - }); + return *dq.ids.qTag; + }); - luaCtx.registerFunction)>("setProxyProtocolValues", [](DNSQuestion& dq, const LuaArray& values) { + luaCtx.registerFunction)>("setProxyProtocolValues", [](DNSQuestion& dq, const LuaArray& values) { if (!dq.proxyProtocolValues) { dq.proxyProtocolValues = make_unique>(); } @@ -196,7 +204,7 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) } }); - luaCtx.registerFunction("addProxyProtocolValue", [](DNSQuestion& dq, uint64_t type, std::string value) { + luaCtx.registerFunction("addProxyProtocolValue", [](DNSQuestion& dq, uint64_t type, std::string value) { checkParameterBound("addProxyProtocolValue", type, std::numeric_limits::max()); if (!dq.proxyProtocolValues) { dq.proxyProtocolValues = make_unique>(); @@ -205,7 +213,7 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) dq.proxyProtocolValues->push_back({std::move(value), static_cast(type)}); }); - luaCtx.registerFunction(DNSQuestion::*)()>("getProxyProtocolValues", [](const DNSQuestion& dq) { + luaCtx.registerFunction (DNSQuestion::*)()>("getProxyProtocolValues", [](const DNSQuestion& dq) { LuaArray result; if (!dq.proxyProtocolValues) { return result; @@ -213,13 +221,13 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) result.resize(dq.proxyProtocolValues->size()); for (const auto& value : *dq.proxyProtocolValues) { - result.push_back({ value.type, value.content }); + result.push_back({value.type, value.content}); } return result; }); - luaCtx.registerFunction("changeName", [](DNSQuestion& dq, const DNSName& newName) -> bool { + luaCtx.registerFunction("changeName", [](DNSQuestion& dq, const DNSName& newName) -> bool { if (!dnsdist::changeNameInDNSPacket(dq.getMutableData(), dq.ids.qname, newName)) { return false; } @@ -227,38 +235,38 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) return true; }); - luaCtx.registerFunction, LuaArray>&, boost::optional)>("spoof", [](DNSQuestion& dnsQuestion, const boost::variant, LuaArray>& response, boost::optional typeForAny) { - if (response.type() == typeid(LuaArray)) { - std::vector data; - auto responses = boost::get>(response); - data.reserve(responses.size()); - for (const auto& resp : responses) { - data.push_back(resp.second); - } - std::string result; - SpoofAction tempSpoofAction(data); - tempSpoofAction(&dnsQuestion, &result); - return; + luaCtx.registerFunction, LuaArray>&, boost::optional)>("spoof", [](DNSQuestion& dnsQuestion, const boost::variant, LuaArray>& response, boost::optional typeForAny) { + if (response.type() == typeid(LuaArray)) { + std::vector data; + auto responses = boost::get>(response); + data.reserve(responses.size()); + for (const auto& resp : responses) { + data.push_back(resp.second); } - if (response.type() == typeid(LuaArray)) { - std::vector data; - auto responses = boost::get>(response); - data.reserve(responses.size()); - for (const auto& resp : responses) { - data.push_back(resp.second); - } - std::string result; - SpoofAction tempSpoofAction(data, typeForAny ? *typeForAny : std::optional()); - tempSpoofAction(&dnsQuestion, &result); - return; + std::string result; + SpoofAction tempSpoofAction(data); + tempSpoofAction(&dnsQuestion, &result); + return; + } + if (response.type() == typeid(LuaArray)) { + std::vector data; + auto responses = boost::get>(response); + data.reserve(responses.size()); + for (const auto& resp : responses) { + data.push_back(resp.second); } + std::string result; + SpoofAction tempSpoofAction(data, typeForAny ? *typeForAny : std::optional()); + tempSpoofAction(&dnsQuestion, &result); + return; + } }); - luaCtx.registerFunction("setEDNSOption", [](DNSQuestion& dq, uint16_t code, const std::string& data) { + luaCtx.registerFunction("setEDNSOption", [](DNSQuestion& dq, uint16_t code, const std::string& data) { setEDNSOption(dq, code, data); }); - luaCtx.registerFunction& extraText)>("setExtendedDNSError", [](DNSQuestion& dnsQuestion, uint16_t infoCode, const boost::optional& extraText) { + luaCtx.registerFunction& extraText)>("setExtendedDNSError", [](DNSQuestion& dnsQuestion, uint16_t infoCode, const boost::optional& extraText) { EDNSExtendedError ede; ede.infoCode = infoCode; if (extraText) { @@ -267,77 +275,78 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) dnsQuestion.ids.d_extendedError = std::make_unique(ede); }); - luaCtx.registerFunction("suspend", [](DNSQuestion& dq, uint16_t asyncID, uint16_t queryID, uint32_t timeoutMs) { + luaCtx.registerFunction("suspend", [](DNSQuestion& dq, uint16_t asyncID, uint16_t queryID, uint32_t timeoutMs) { dq.asynchronous = true; return dnsdist::suspendQuery(dq, asyncID, queryID, timeoutMs); }); - luaCtx.registerFunction("setRestartable", [](DNSQuestion& dq) { + luaCtx.registerFunction("setRestartable", [](DNSQuestion& dq) { dq.ids.d_packet = std::make_unique(dq.getData()); return true; }); -class AsynchronousObject -{ -public: - AsynchronousObject(std::unique_ptr&& obj_): object(std::move(obj_)) - { - } - - DNSQuestion getDQ() const + class AsynchronousObject { - return object->getDQ(); - } + public: + AsynchronousObject(std::unique_ptr&& obj_) : + object(std::move(obj_)) + { + } - DNSResponse getDR() const - { - return object->getDR(); - } + DNSQuestion getDQ() const + { + return object->getDQ(); + } - bool resume() - { - return dnsdist::queueQueryResumptionEvent(std::move(object)); - } + DNSResponse getDR() const + { + return object->getDR(); + } - bool drop() - { - auto sender = object->getTCPQuerySender(); - if (!sender) { - return false; + bool resume() + { + return dnsdist::queueQueryResumptionEvent(std::move(object)); } - struct timeval now; - gettimeofday(&now, nullptr); - sender->notifyIOError(now, TCPResponse(std::move(object->query))); - return true; - } + bool drop() + { + auto sender = object->getTCPQuerySender(); + if (!sender) { + return false; + } - bool setRCode(uint8_t rcode, bool clearAnswers) - { - return dnsdist::setInternalQueryRCode(object->query.d_idstate, object->query.d_buffer, rcode, clearAnswers); - } + struct timeval now; + gettimeofday(&now, nullptr); + sender->notifyIOError(now, TCPResponse(std::move(object->query))); + return true; + } -private: - std::unique_ptr object; -}; + bool setRCode(uint8_t rcode, bool clearAnswers) + { + return dnsdist::setInternalQueryRCode(object->query.d_idstate, object->query.d_buffer, rcode, clearAnswers); + } - luaCtx.registerFunction("getDQ", [](const AsynchronousObject& obj) { - return obj.getDQ(); - }); + private: + std::unique_ptr object; + }; - luaCtx.registerFunction("getDR", [](const AsynchronousObject& obj) { - return obj.getDR(); - }); + luaCtx.registerFunction("getDQ", [](const AsynchronousObject& obj) { + return obj.getDQ(); + }); - luaCtx.registerFunction("resume", [](AsynchronousObject& obj) { - return obj.resume(); - }); + luaCtx.registerFunction("getDR", [](const AsynchronousObject& obj) { + return obj.getDR(); + }); - luaCtx.registerFunction("drop", [](AsynchronousObject& obj) { - return obj.drop(); - }); + luaCtx.registerFunction("resume", [](AsynchronousObject& obj) { + return obj.resume(); + }); + + luaCtx.registerFunction("drop", [](AsynchronousObject& obj) { + return obj.drop(); + }); - luaCtx.registerFunction("setRCode", [](AsynchronousObject& obj, uint8_t rcode, bool clearAnswers) { + luaCtx.registerFunction("setRCode", [](AsynchronousObject& obj, uint8_t rcode, bool clearAnswers) { return obj.setRCode(rcode, clearAnswers); }); @@ -353,38 +362,46 @@ class AsynchronousObject }); /* LuaWrapper doesn't support inheritance */ - luaCtx.registerMember("localaddr", [](const DNSResponse& dq) -> const ComboAddress { return dq.ids.origDest; }, [](DNSResponse& dq, const ComboAddress newLocal) { (void) newLocal; }); - luaCtx.registerMember("qname", [](const DNSResponse& dq) -> const DNSName { return dq.ids.qname; }, [](DNSResponse& dq, const DNSName& newName) { (void) newName; }); - luaCtx.registerMember("qtype", [](const DNSResponse& dq) -> uint16_t { return dq.ids.qtype; }, [](DNSResponse& dq, uint16_t newType) { (void) newType; }); - luaCtx.registerMember("qclass", [](const DNSResponse& dq) -> uint16_t { return dq.ids.qclass; }, [](DNSResponse& dq, uint16_t newClass) { (void) newClass; }); - luaCtx.registerMember("rcode", [](const DNSResponse& dq) -> int { return static_cast(dq.getHeader()->rcode); }, [](DNSResponse& dq, int newRCode) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [newRCode](dnsheader& header) { - header.rcode = static_cast(newRCode); - return true; - }); + luaCtx.registerMember( + "localaddr", [](const DNSResponse& dq) -> const ComboAddress { return dq.ids.origDest; }, [](DNSResponse& dq, const ComboAddress newLocal) { (void)newLocal; }); + luaCtx.registerMember( + "qname", [](const DNSResponse& dq) -> const DNSName { return dq.ids.qname; }, [](DNSResponse& dq, const DNSName& newName) { (void)newName; }); + luaCtx.registerMember( + "qtype", [](const DNSResponse& dq) -> uint16_t { return dq.ids.qtype; }, [](DNSResponse& dq, uint16_t newType) { (void)newType; }); + luaCtx.registerMember( + "qclass", [](const DNSResponse& dq) -> uint16_t { return dq.ids.qclass; }, [](DNSResponse& dq, uint16_t newClass) { (void)newClass; }); + luaCtx.registerMember( + "rcode", [](const DNSResponse& dq) -> int { return static_cast(dq.getHeader()->rcode); }, [](DNSResponse& dq, int newRCode) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [newRCode](dnsheader& header) { + header.rcode = static_cast(newRCode); + return true; + }); }); + luaCtx.registerMember( + "remoteaddr", [](const DNSResponse& dq) -> const ComboAddress { return dq.ids.origRemote; }, [](DNSResponse& dq, const ComboAddress newRemote) { (void)newRemote; }); + luaCtx.registerMember( + "dh", [](const DNSResponse& dr) -> dnsheader* { return dr.getMutableHeader(); }, [](DNSResponse& dr, const dnsheader* dh) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dr.getMutableData(), [&dh](dnsheader& header) { + header = *dh; + return true; + }); }); + luaCtx.registerMember( + "len", [](const DNSResponse& dq) -> uint16_t { return dq.getData().size(); }, [](DNSResponse& dq, uint16_t newlen) { dq.getMutableData().resize(newlen); }); + luaCtx.registerMember( + "opcode", [](const DNSResponse& dq) -> uint8_t { return dq.getHeader()->opcode; }, [](DNSResponse& dq, uint8_t newOpcode) { (void)newOpcode; }); + luaCtx.registerMember( + "tcp", [](const DNSResponse& dq) -> bool { return dq.overTCP(); }, [](DNSResponse& dq, bool newTcp) { (void)newTcp; }); + luaCtx.registerMember( + "skipCache", [](const DNSResponse& dq) -> bool { return dq.ids.skipCache; }, [](DNSResponse& dq, bool newSkipCache) { dq.ids.skipCache = newSkipCache; }); + luaCtx.registerMember( + "pool", [](const DNSResponse& dq) -> std::string { return dq.ids.poolName; }, [](DNSResponse& dq, const std::string& newPoolName) { dq.ids.poolName = newPoolName; }); + luaCtx.registerFunction editFunc)>("editTTLs", [](DNSResponse& dr, std::function editFunc) { + editDNSPacketTTL(reinterpret_cast(dr.getMutableData().data()), dr.getData().size(), editFunc); }); - luaCtx.registerMember("remoteaddr", [](const DNSResponse& dq) -> const ComboAddress { return dq.ids.origRemote; }, [](DNSResponse& dq, const ComboAddress newRemote) { (void) newRemote; }); - luaCtx.registerMember("dh", [](const DNSResponse& dr) -> dnsheader* { return dr.getMutableHeader(); }, [](DNSResponse& dr, const dnsheader* dh) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dr.getMutableData(), [&dh](dnsheader& header) { - header = *dh; - return true; - }); + luaCtx.registerFunction("getDO", [](const DNSResponse& dq) { + return getEDNSZ(dq) & EDNS_HEADER_FLAG_DO; }); - luaCtx.registerMember("len", [](const DNSResponse& dq) -> uint16_t { return dq.getData().size(); }, [](DNSResponse& dq, uint16_t newlen) { dq.getMutableData().resize(newlen); }); - luaCtx.registerMember("opcode", [](const DNSResponse& dq) -> uint8_t { return dq.getHeader()->opcode; }, [](DNSResponse& dq, uint8_t newOpcode) { (void) newOpcode; }); - luaCtx.registerMember("tcp", [](const DNSResponse& dq) -> bool { return dq.overTCP(); }, [](DNSResponse& dq, bool newTcp) { (void) newTcp; }); - luaCtx.registerMember("skipCache", [](const DNSResponse& dq) -> bool { return dq.ids.skipCache; }, [](DNSResponse& dq, bool newSkipCache) { dq.ids.skipCache = newSkipCache; }); - luaCtx.registerMember("pool", [](const DNSResponse& dq) -> std::string { return dq.ids.poolName; }, [](DNSResponse& dq, const std::string& newPoolName) { dq.ids.poolName = newPoolName; }); - luaCtx.registerFunction editFunc)>("editTTLs", [](DNSResponse& dr, std::function editFunc) { - editDNSPacketTTL(reinterpret_cast(dr.getMutableData().data()), dr.getData().size(), editFunc); - }); - luaCtx.registerFunction("getDO", [](const DNSResponse& dq) { - return getEDNSZ(dq) & EDNS_HEADER_FLAG_DO; - }); - luaCtx.registerFunction("getContent", [](const DNSResponse& dq) { + luaCtx.registerFunction("getContent", [](const DNSResponse& dq) { return std::string(reinterpret_cast(dq.getData().data()), dq.getData().size()); }); - luaCtx.registerFunction("setContent", [](DNSResponse& dr, const std::string& raw) { + luaCtx.registerFunction("setContent", [](DNSResponse& dr, const std::string& raw) { uint16_t oldID = dr.getHeader()->id; auto& buffer = dr.getMutableData(); buffer.clear(); @@ -395,127 +412,127 @@ class AsynchronousObject }); }); - luaCtx.registerFunction(DNSResponse::*)()const>("getEDNSOptions", [](const DNSResponse& dq) { + luaCtx.registerFunction (DNSResponse::*)() const>("getEDNSOptions", [](const DNSResponse& dq) { + if (dq.ednsOptions == nullptr) { + parseEDNSOptions(dq); if (dq.ednsOptions == nullptr) { - parseEDNSOptions(dq); - if (dq.ednsOptions == nullptr) { - throw std::runtime_error("parseEDNSOptions should have populated the EDNS options"); - } + throw std::runtime_error("parseEDNSOptions should have populated the EDNS options"); } + } - return *dq.ednsOptions; - }); - luaCtx.registerFunction("getTrailingData", [](const DNSResponse& dq) { - return dq.getTrailingData(); - }); - luaCtx.registerFunction("setTrailingData", [](DNSResponse& dq, const std::string& tail) { - return dq.setTrailingData(tail); - }); + return *dq.ednsOptions; + }); + luaCtx.registerFunction("getTrailingData", [](const DNSResponse& dq) { + return dq.getTrailingData(); + }); + luaCtx.registerFunction("setTrailingData", [](DNSResponse& dq, const std::string& tail) { + return dq.setTrailingData(tail); + }); - luaCtx.registerFunction("setTag", [](DNSResponse& dr, const std::string& strLabel, const std::string& strValue) { - dr.setTag(strLabel, strValue); - }); + luaCtx.registerFunction("setTag", [](DNSResponse& dr, const std::string& strLabel, const std::string& strValue) { + dr.setTag(strLabel, strValue); + }); - luaCtx.registerFunction)>("setTagArray", [](DNSResponse& dr, const LuaAssociativeTable&tags) { - for (const auto& tag : tags) { - dr.setTag(tag.first, tag.second); - } - }); - luaCtx.registerFunction("getTag", [](const DNSResponse& dr, const std::string& strLabel) { - if (!dr.ids.qTag) { - return string(); - } + luaCtx.registerFunction)>("setTagArray", [](DNSResponse& dr, const LuaAssociativeTable& tags) { + for (const auto& tag : tags) { + dr.setTag(tag.first, tag.second); + } + }); + luaCtx.registerFunction("getTag", [](const DNSResponse& dr, const std::string& strLabel) { + if (!dr.ids.qTag) { + return string(); + } - std::string strValue; - const auto it = dr.ids.qTag->find(strLabel); - if (it == dr.ids.qTag->cend()) { - return string(); - } - return it->second; - }); - luaCtx.registerFunction("getTagArray", [](const DNSResponse& dr) { - if (!dr.ids.qTag) { - QTag empty; - return empty; - } + std::string strValue; + const auto it = dr.ids.qTag->find(strLabel); + if (it == dr.ids.qTag->cend()) { + return string(); + } + return it->second; + }); + luaCtx.registerFunction("getTagArray", [](const DNSResponse& dr) { + if (!dr.ids.qTag) { + QTag empty; + return empty; + } - return *dr.ids.qTag; - }); + return *dr.ids.qTag; + }); - luaCtx.registerFunction("getProtocol", [](const DNSResponse& dr) { + luaCtx.registerFunction("getProtocol", [](const DNSResponse& dr) { return dr.getProtocol().toPrettyString(); }); - luaCtx.registerFunction("getQueryTime", [](const DNSResponse& dr) { + luaCtx.registerFunction("getQueryTime", [](const DNSResponse& dr) { return dr.ids.queryRealTime.getStartTime(); }); - luaCtx.registerFunction("sendTrap", [](const DNSResponse& dr, boost::optional reason) { + luaCtx.registerFunction("sendTrap", [](const DNSResponse& dr, boost::optional reason) { #ifdef HAVE_NET_SNMP - if (g_snmpAgent && g_snmpTrapsEnabled) { - g_snmpAgent->sendDNSTrap(dr, reason ? *reason : ""); - } + if (g_snmpAgent && g_snmpTrapsEnabled) { + g_snmpAgent->sendDNSTrap(dr, reason ? *reason : ""); + } #endif /* HAVE_NET_SNMP */ - }); + }); #ifdef HAVE_DNS_OVER_HTTPS - luaCtx.registerFunction("getHTTPPath", [](const DNSQuestion& dq) { - if (dq.ids.du == nullptr) { - return std::string(); - } - return dq.ids.du->getHTTPPath(); - }); + luaCtx.registerFunction("getHTTPPath", [](const DNSQuestion& dq) { + if (dq.ids.du == nullptr) { + return std::string(); + } + return dq.ids.du->getHTTPPath(); + }); - luaCtx.registerFunction("getHTTPQueryString", [](const DNSQuestion& dq) { - if (dq.ids.du == nullptr) { - return std::string(); - } - return dq.ids.du->getHTTPQueryString(); - }); + luaCtx.registerFunction("getHTTPQueryString", [](const DNSQuestion& dq) { + if (dq.ids.du == nullptr) { + return std::string(); + } + return dq.ids.du->getHTTPQueryString(); + }); - luaCtx.registerFunction("getHTTPHost", [](const DNSQuestion& dq) { - if (dq.ids.du == nullptr) { - return std::string(); - } - return dq.ids.du->getHTTPHost(); - }); + luaCtx.registerFunction("getHTTPHost", [](const DNSQuestion& dq) { + if (dq.ids.du == nullptr) { + return std::string(); + } + return dq.ids.du->getHTTPHost(); + }); - luaCtx.registerFunction("getHTTPScheme", [](const DNSQuestion& dq) { - if (dq.ids.du == nullptr) { - return std::string(); - } - return dq.ids.du->getHTTPScheme(); - }); + luaCtx.registerFunction("getHTTPScheme", [](const DNSQuestion& dq) { + if (dq.ids.du == nullptr) { + return std::string(); + } + return dq.ids.du->getHTTPScheme(); + }); - luaCtx.registerFunction(DNSQuestion::*)(void)const>("getHTTPHeaders", [](const DNSQuestion& dq) { - if (dq.ids.du == nullptr) { - return LuaAssociativeTable(); - } - return dq.ids.du->getHTTPHeaders(); - }); + luaCtx.registerFunction (DNSQuestion::*)(void) const>("getHTTPHeaders", [](const DNSQuestion& dq) { + if (dq.ids.du == nullptr) { + return LuaAssociativeTable(); + } + return dq.ids.du->getHTTPHeaders(); + }); - luaCtx.registerFunction contentType)>("setHTTPResponse", [](DNSQuestion& dq, uint64_t statusCode, const std::string& body, const boost::optional contentType) { - if (dq.ids.du == nullptr) { - return; - } - checkParameterBound("DNSQuestion::setHTTPResponse", statusCode, std::numeric_limits::max()); - PacketBuffer vect(body.begin(), body.end()); - dq.ids.du->setHTTPResponse(statusCode, std::move(vect), contentType ? *contentType : ""); - }); + luaCtx.registerFunction contentType)>("setHTTPResponse", [](DNSQuestion& dq, uint64_t statusCode, const std::string& body, const boost::optional contentType) { + if (dq.ids.du == nullptr) { + return; + } + checkParameterBound("DNSQuestion::setHTTPResponse", statusCode, std::numeric_limits::max()); + PacketBuffer vect(body.begin(), body.end()); + dq.ids.du->setHTTPResponse(statusCode, std::move(vect), contentType ? *contentType : ""); + }); #endif /* HAVE_DNS_OVER_HTTPS */ - luaCtx.registerFunction("setNegativeAndAdditionalSOA", [](DNSQuestion& dq, bool nxd, const std::string& zone, uint64_t ttl, const std::string& mname, const std::string& rname, uint64_t serial, uint64_t refresh, uint64_t retry, uint64_t expire, uint64_t minimum) { - checkParameterBound("setNegativeAndAdditionalSOA", ttl, std::numeric_limits::max()); - checkParameterBound("setNegativeAndAdditionalSOA", serial, std::numeric_limits::max()); - checkParameterBound("setNegativeAndAdditionalSOA", refresh, std::numeric_limits::max()); - checkParameterBound("setNegativeAndAdditionalSOA", retry, std::numeric_limits::max()); - checkParameterBound("setNegativeAndAdditionalSOA", expire, std::numeric_limits::max()); - checkParameterBound("setNegativeAndAdditionalSOA", minimum, std::numeric_limits::max()); + luaCtx.registerFunction("setNegativeAndAdditionalSOA", [](DNSQuestion& dq, bool nxd, const std::string& zone, uint64_t ttl, const std::string& mname, const std::string& rname, uint64_t serial, uint64_t refresh, uint64_t retry, uint64_t expire, uint64_t minimum) { + checkParameterBound("setNegativeAndAdditionalSOA", ttl, std::numeric_limits::max()); + checkParameterBound("setNegativeAndAdditionalSOA", serial, std::numeric_limits::max()); + checkParameterBound("setNegativeAndAdditionalSOA", refresh, std::numeric_limits::max()); + checkParameterBound("setNegativeAndAdditionalSOA", retry, std::numeric_limits::max()); + checkParameterBound("setNegativeAndAdditionalSOA", expire, std::numeric_limits::max()); + checkParameterBound("setNegativeAndAdditionalSOA", minimum, std::numeric_limits::max()); - return setNegativeAndAdditionalSOA(dq, nxd, DNSName(zone), ttl, DNSName(mname), DNSName(rname), serial, refresh, retry, expire, minimum, false); - }); + return setNegativeAndAdditionalSOA(dq, nxd, DNSName(zone), ttl, DNSName(mname), DNSName(rname), serial, refresh, retry, expire, minimum, false); + }); - luaCtx.registerFunction& extraText)>("setExtendedDNSError", [](DNSResponse& dnsResponse, uint16_t infoCode, const boost::optional& extraText) { + luaCtx.registerFunction& extraText)>("setExtendedDNSError", [](DNSResponse& dnsResponse, uint16_t infoCode, const boost::optional& extraText) { EDNSExtendedError ede; ede.infoCode = infoCode; if (extraText) { @@ -524,12 +541,12 @@ class AsynchronousObject dnsResponse.ids.d_extendedError = std::make_unique(ede); }); - luaCtx.registerFunction("suspend", [](DNSResponse& dr, uint16_t asyncID, uint16_t queryID, uint32_t timeoutMs) { + luaCtx.registerFunction("suspend", [](DNSResponse& dr, uint16_t asyncID, uint16_t queryID, uint32_t timeoutMs) { dr.asynchronous = true; return dnsdist::suspendResponse(dr, asyncID, queryID, timeoutMs); }); - luaCtx.registerFunction("changeName", [](DNSResponse& dr, const DNSName& newName) -> bool { + luaCtx.registerFunction("changeName", [](DNSResponse& dr, const DNSName& newName) -> bool { if (!dnsdist::changeNameInDNSPacket(dr.getMutableData(), dr.ids.qname, newName)) { return false; } @@ -537,7 +554,7 @@ class AsynchronousObject return true; }); - luaCtx.registerFunction("restart", [](DNSResponse& dr) { + luaCtx.registerFunction("restart", [](DNSResponse& dr) { if (!dr.ids.d_packet) { return false; } @@ -547,7 +564,7 @@ class AsynchronousObject return dnsdist::queueQueryResumptionEvent(std::move(query)); }); - luaCtx.registerFunction(DNSResponse::*)(void)const>("getSelectedBackend", [](const DNSResponse& dr) { + luaCtx.registerFunction (DNSResponse::*)(void) const>("getSelectedBackend", [](const DNSResponse& dr) { return dr.d_downstream; }); #endif /* DISABLE_NON_FFI_DQ_BINDINGS */ diff --git a/pdns/dnsdistdist/dnsdist-lua-bindings.cc b/pdns/dnsdistdist/dnsdist-lua-bindings.cc index 3f5d6e21159a..8f15f197ed3f 100644 --- a/pdns/dnsdistdist/dnsdist-lua-bindings.cc +++ b/pdns/dnsdistdist/dnsdist-lua-bindings.cc @@ -35,40 +35,43 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) { luaCtx.writeFunction("vinfolog", [](const string& arg) { - vinfolog("%s", arg); - }); + vinfolog("%s", arg); + }); luaCtx.writeFunction("infolog", [](const string& arg) { - infolog("%s", arg); - }); + infolog("%s", arg); + }); luaCtx.writeFunction("errlog", [](const string& arg) { - errlog("%s", arg); - }); + errlog("%s", arg); + }); luaCtx.writeFunction("warnlog", [](const string& arg) { - warnlog("%s", arg); - }); + warnlog("%s", arg); + }); luaCtx.writeFunction("show", [](const string& arg) { - g_outputBuffer+=arg; - g_outputBuffer+="\n"; - }); + g_outputBuffer += arg; + g_outputBuffer += "\n"; + }); /* Exceptions */ - luaCtx.registerFunction("__tostring", [](const std::exception_ptr& eptr) -> std::string { - try { - if (eptr) { - std::rethrow_exception(eptr); - } - } catch(const std::exception& e) { - return string(e.what()); - } catch(const PDNSException& e) { - return e.reason; - } catch(...) { - return string("Unknown exception"); + luaCtx.registerFunction("__tostring", [](const std::exception_ptr& eptr) -> std::string { + try { + if (eptr) { + std::rethrow_exception(eptr); } - return string("No exception"); - }); + } + catch (const std::exception& e) { + return string(e.what()); + } + catch (const PDNSException& e) { + return e.reason; + } + catch (...) { + return string("Unknown exception"); + } + return string("No exception"); + }); #ifndef DISABLE_POLICIES_BINDINGS /* ServerPolicy */ - luaCtx.writeFunction("newServerPolicy", [](string name, ServerPolicy::policyfunc_t policy) { return std::make_shared(name, policy, true);}); + luaCtx.writeFunction("newServerPolicy", [](string name, ServerPolicy::policyfunc_t policy) { return std::make_shared(name, policy, true); }); luaCtx.registerMember("name", &ServerPolicy::d_name); luaCtx.registerMember("policy", &ServerPolicy::d_policy); luaCtx.registerMember("ffipolicy", &ServerPolicy::d_ffipolicy); @@ -84,8 +87,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) std::make_shared("wrandom", wrandom, false), std::make_shared("whashed", whashed, false), std::make_shared("chashed", chashed, false), - std::make_shared("leastOutstanding", leastOutstanding, false) - }; + std::make_shared("leastOutstanding", leastOutstanding, false)}; for (const auto& policy : policies) { luaCtx.writeVariable(policy->d_name, policy); } @@ -93,255 +95,257 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) #endif /* DISABLE_POLICIES_BINDINGS */ /* ServerPool */ - luaCtx.registerFunction::*)(std::shared_ptr)>("setCache", [](std::shared_ptr pool, std::shared_ptr cache) { - if (pool) { - pool->packetCache = std::move(cache); - } - }); + luaCtx.registerFunction::*)(std::shared_ptr)>("setCache", [](std::shared_ptr pool, std::shared_ptr cache) { + if (pool) { + pool->packetCache = std::move(cache); + } + }); luaCtx.registerFunction("getCache", &ServerPool::getCache); - luaCtx.registerFunction::*)()>("unsetCache", [](std::shared_ptr pool) { - if (pool) { - pool->packetCache = nullptr; - } - }); + luaCtx.registerFunction::*)()>("unsetCache", [](std::shared_ptr pool) { + if (pool) { + pool->packetCache = nullptr; + } + }); luaCtx.registerFunction("getECS", &ServerPool::getECS); luaCtx.registerFunction("setECS", &ServerPool::setECS); #ifndef DISABLE_DOWNSTREAM_BINDINGS /* DownstreamState */ - luaCtx.registerFunction("setQPS", [](DownstreamState& state, int lim) { state.qps = lim > 0 ? QPSLimiter(lim, lim) : QPSLimiter(); }); - luaCtx.registerFunction::*)(string)>("addPool", [](const std::shared_ptr& state, const string& pool) { - auto localPools = g_pools.getCopy(); - addServerToPool(localPools, pool, state); - g_pools.setState(localPools); - state->d_config.pools.insert(pool); - }); - luaCtx.registerFunction::*)(string)>("rmPool", [](const std::shared_ptr& state, const string& pool) { - auto localPools = g_pools.getCopy(); - removeServerFromPool(localPools, pool, state); - g_pools.setState(localPools); - state->d_config.pools.erase(pool); - }); - luaCtx.registerFunction("getOutstanding", [](const DownstreamState& state) { return state.outstanding.load(); }); - luaCtx.registerFunction("getDrops", [](const DownstreamState& state) { return state.reuseds.load(); }); - luaCtx.registerFunction("getLatency", [](const DownstreamState& state) { return state.getRelevantLatencyUsec(); }); + luaCtx.registerFunction("setQPS", [](DownstreamState& state, int lim) { state.qps = lim > 0 ? QPSLimiter(lim, lim) : QPSLimiter(); }); + luaCtx.registerFunction::*)(string)>("addPool", [](const std::shared_ptr& state, const string& pool) { + auto localPools = g_pools.getCopy(); + addServerToPool(localPools, pool, state); + g_pools.setState(localPools); + state->d_config.pools.insert(pool); + }); + luaCtx.registerFunction::*)(string)>("rmPool", [](const std::shared_ptr& state, const string& pool) { + auto localPools = g_pools.getCopy(); + removeServerFromPool(localPools, pool, state); + g_pools.setState(localPools); + state->d_config.pools.erase(pool); + }); + luaCtx.registerFunction("getOutstanding", [](const DownstreamState& state) { return state.outstanding.load(); }); + luaCtx.registerFunction("getDrops", [](const DownstreamState& state) { return state.reuseds.load(); }); + luaCtx.registerFunction("getLatency", [](const DownstreamState& state) { return state.getRelevantLatencyUsec(); }); luaCtx.registerFunction("isUp", &DownstreamState::isUp); luaCtx.registerFunction("setDown", &DownstreamState::setDown); luaCtx.registerFunction("setUp", &DownstreamState::setUp); - luaCtx.registerFunction newStatus)>("setAuto", [](DownstreamState& state, boost::optional newStatus) { - if (newStatus) { - state.setUpStatus(*newStatus); - } - state.setAuto(); - }); - luaCtx.registerFunction newStatus)>("setLazyAuto", [](DownstreamState& state, boost::optional newStatus) { - if (newStatus) { - state.setUpStatus(*newStatus); - } - state.setLazyAuto(); - }); - luaCtx.registerFunction("getName", [](const DownstreamState& state) -> const std::string& { return state.getName(); }); - luaCtx.registerFunction("getNameWithAddr", [](const DownstreamState& state) -> const std::string& { return state.getNameWithAddr(); }); + luaCtx.registerFunction newStatus)>("setAuto", [](DownstreamState& state, boost::optional newStatus) { + if (newStatus) { + state.setUpStatus(*newStatus); + } + state.setAuto(); + }); + luaCtx.registerFunction newStatus)>("setLazyAuto", [](DownstreamState& state, boost::optional newStatus) { + if (newStatus) { + state.setUpStatus(*newStatus); + } + state.setLazyAuto(); + }); + luaCtx.registerFunction("getName", [](const DownstreamState& state) -> const std::string& { return state.getName(); }); + luaCtx.registerFunction("getNameWithAddr", [](const DownstreamState& state) -> const std::string& { return state.getNameWithAddr(); }); luaCtx.registerMember("upStatus", &DownstreamState::upStatus); - luaCtx.registerMember("weight", - [](const DownstreamState& state) -> int {return state.d_config.d_weight;}, - [](DownstreamState& state, int newWeight) { state.setWeight(newWeight); } - ); - luaCtx.registerMember("order", - [](const DownstreamState& state) -> int {return state.d_config.order; }, - [](DownstreamState& state, int newOrder) { state.d_config.order = newOrder; } - ); - luaCtx.registerMember("name", [](const DownstreamState& backend) -> const std::string { return backend.getName(); }, [](DownstreamState& backend, const std::string& newName) { backend.setName(newName); }); - luaCtx.registerFunction("getID", [](const DownstreamState& state) { return boost::uuids::to_string(*state.d_config.id); }); + luaCtx.registerMember( + "weight", + [](const DownstreamState& state) -> int { return state.d_config.d_weight; }, + [](DownstreamState& state, int newWeight) { state.setWeight(newWeight); }); + luaCtx.registerMember( + "order", + [](const DownstreamState& state) -> int { return state.d_config.order; }, + [](DownstreamState& state, int newOrder) { state.d_config.order = newOrder; }); + luaCtx.registerMember( + "name", [](const DownstreamState& backend) -> const std::string { return backend.getName(); }, [](DownstreamState& backend, const std::string& newName) { backend.setName(newName); }); + luaCtx.registerFunction("getID", [](const DownstreamState& state) { return boost::uuids::to_string(*state.d_config.id); }); #endif /* DISABLE_DOWNSTREAM_BINDINGS */ #ifndef DISABLE_DNSHEADER_BINDINGS /* dnsheader */ - luaCtx.registerFunction("setRD", [](dnsheader& dh, bool v) { - dh.rd=v; - }); + luaCtx.registerFunction("setRD", [](dnsheader& dh, bool v) { + dh.rd = v; + }); - luaCtx.registerFunction("getRD", [](const dnsheader& dh) { - return (bool)dh.rd; - }); + luaCtx.registerFunction("getRD", [](const dnsheader& dh) { + return (bool)dh.rd; + }); - luaCtx.registerFunction("setRA", [](dnsheader& dh, bool v) { - dh.ra=v; - }); + luaCtx.registerFunction("setRA", [](dnsheader& dh, bool v) { + dh.ra = v; + }); - luaCtx.registerFunction("getRA", [](const dnsheader& dh) { - return (bool)dh.ra; - }); + luaCtx.registerFunction("getRA", [](const dnsheader& dh) { + return (bool)dh.ra; + }); - luaCtx.registerFunction("setAD", [](dnsheader& dh, bool v) { - dh.ad=v; - }); + luaCtx.registerFunction("setAD", [](dnsheader& dh, bool v) { + dh.ad = v; + }); - luaCtx.registerFunction("getAD", [](const dnsheader& dh) { - return (bool)dh.ad; - }); + luaCtx.registerFunction("getAD", [](const dnsheader& dh) { + return (bool)dh.ad; + }); - luaCtx.registerFunction("setAA", [](dnsheader& dh, bool v) { - dh.aa=v; - }); + luaCtx.registerFunction("setAA", [](dnsheader& dh, bool v) { + dh.aa = v; + }); - luaCtx.registerFunction("getAA", [](const dnsheader& dh) { - return (bool)dh.aa; - }); + luaCtx.registerFunction("getAA", [](const dnsheader& dh) { + return (bool)dh.aa; + }); - luaCtx.registerFunction("setCD", [](dnsheader& dh, bool v) { - dh.cd=v; - }); + luaCtx.registerFunction("setCD", [](dnsheader& dh, bool v) { + dh.cd = v; + }); - luaCtx.registerFunction("getCD", [](const dnsheader& dh) { - return (bool)dh.cd; - }); + luaCtx.registerFunction("getCD", [](const dnsheader& dh) { + return (bool)dh.cd; + }); - luaCtx.registerFunction("getID", [](const dnsheader& dh) { - return ntohs(dh.id); - }); + luaCtx.registerFunction("getID", [](const dnsheader& dh) { + return ntohs(dh.id); + }); - luaCtx.registerFunction("getTC", [](const dnsheader& dh) { - return (bool)dh.tc; - }); + luaCtx.registerFunction("getTC", [](const dnsheader& dh) { + return (bool)dh.tc; + }); - luaCtx.registerFunction("setTC", [](dnsheader& dh, bool v) { - dh.tc=v; - if(v) dh.ra = dh.rd; // you'll always need this, otherwise TC=1 gets ignored - }); + luaCtx.registerFunction("setTC", [](dnsheader& dh, bool v) { + dh.tc = v; + if (v) + dh.ra = dh.rd; // you'll always need this, otherwise TC=1 gets ignored + }); - luaCtx.registerFunction("setQR", [](dnsheader& dh, bool v) { - dh.qr=v; - }); + luaCtx.registerFunction("setQR", [](dnsheader& dh, bool v) { + dh.qr = v; + }); #endif /* DISABLE_DNSHEADER_BINDINGS */ #ifndef DISABLE_COMBO_ADDR_BINDINGS /* ComboAddress */ luaCtx.writeFunction("newCA", [](const std::string& name) { return ComboAddress(name); }); luaCtx.writeFunction("newCAFromRaw", [](const std::string& raw, boost::optional port) { - if (raw.size() == 4) { - struct sockaddr_in sin4; - memset(&sin4, 0, sizeof(sin4)); - sin4.sin_family = AF_INET; - memcpy(&sin4.sin_addr.s_addr, raw.c_str(), raw.size()); - if (port) { - sin4.sin_port = htons(*port); - } - return ComboAddress(&sin4); - } - else if (raw.size() == 16) { - struct sockaddr_in6 sin6; - memset(&sin6, 0, sizeof(sin6)); - sin6.sin6_family = AF_INET6; - memcpy(&sin6.sin6_addr.s6_addr, raw.c_str(), raw.size()); - if (port) { - sin6.sin6_port = htons(*port); - } - return ComboAddress(&sin6); - } - return ComboAddress(); - }); - luaCtx.registerFunction("tostring", [](const ComboAddress& ca) { return ca.toString(); }); - luaCtx.registerFunction("tostringWithPort", [](const ComboAddress& ca) { return ca.toStringWithPort(); }); - luaCtx.registerFunction("__tostring", [](const ComboAddress& ca) { return ca.toString(); }); - luaCtx.registerFunction("toString", [](const ComboAddress& ca) { return ca.toString(); }); - luaCtx.registerFunction("toStringWithPort", [](const ComboAddress& ca) { return ca.toStringWithPort(); }); - luaCtx.registerFunction("getPort", [](const ComboAddress& ca) { return ntohs(ca.sin4.sin_port); } ); - luaCtx.registerFunction("truncate", [](ComboAddress& ca, unsigned int bits) { ca.truncate(bits); }); - luaCtx.registerFunction("isIPv4", [](const ComboAddress& ca) { return ca.sin4.sin_family == AF_INET; }); - luaCtx.registerFunction("isIPv6", [](const ComboAddress& ca) { return ca.sin4.sin_family == AF_INET6; }); - luaCtx.registerFunction("isMappedIPv4", [](const ComboAddress& ca) { return ca.isMappedIPv4(); }); - luaCtx.registerFunction("mapToIPv4", [](const ComboAddress& ca) { return ca.mapToIPv4(); }); - luaCtx.registerFunction("match", [](nmts_t& s, const ComboAddress& ca) { return s.match(ca); }); + if (raw.size() == 4) { + struct sockaddr_in sin4; + memset(&sin4, 0, sizeof(sin4)); + sin4.sin_family = AF_INET; + memcpy(&sin4.sin_addr.s_addr, raw.c_str(), raw.size()); + if (port) { + sin4.sin_port = htons(*port); + } + return ComboAddress(&sin4); + } + else if (raw.size() == 16) { + struct sockaddr_in6 sin6; + memset(&sin6, 0, sizeof(sin6)); + sin6.sin6_family = AF_INET6; + memcpy(&sin6.sin6_addr.s6_addr, raw.c_str(), raw.size()); + if (port) { + sin6.sin6_port = htons(*port); + } + return ComboAddress(&sin6); + } + return ComboAddress(); + }); + luaCtx.registerFunction("tostring", [](const ComboAddress& ca) { return ca.toString(); }); + luaCtx.registerFunction("tostringWithPort", [](const ComboAddress& ca) { return ca.toStringWithPort(); }); + luaCtx.registerFunction("__tostring", [](const ComboAddress& ca) { return ca.toString(); }); + luaCtx.registerFunction("toString", [](const ComboAddress& ca) { return ca.toString(); }); + luaCtx.registerFunction("toStringWithPort", [](const ComboAddress& ca) { return ca.toStringWithPort(); }); + luaCtx.registerFunction("getPort", [](const ComboAddress& ca) { return ntohs(ca.sin4.sin_port); }); + luaCtx.registerFunction("truncate", [](ComboAddress& ca, unsigned int bits) { ca.truncate(bits); }); + luaCtx.registerFunction("isIPv4", [](const ComboAddress& ca) { return ca.sin4.sin_family == AF_INET; }); + luaCtx.registerFunction("isIPv6", [](const ComboAddress& ca) { return ca.sin4.sin_family == AF_INET6; }); + luaCtx.registerFunction("isMappedIPv4", [](const ComboAddress& ca) { return ca.isMappedIPv4(); }); + luaCtx.registerFunction("mapToIPv4", [](const ComboAddress& ca) { return ca.mapToIPv4(); }); + luaCtx.registerFunction("match", [](nmts_t& s, const ComboAddress& ca) { return s.match(ca); }); #endif /* DISABLE_COMBO_ADDR_BINDINGS */ #ifndef DISABLE_DNSNAME_BINDINGS /* DNSName */ luaCtx.registerFunction("isPartOf", &DNSName::isPartOf); - luaCtx.registerFunction("chopOff", [](DNSName&dn ) { return dn.chopOff(); }); - luaCtx.registerFunction("countLabels", [](const DNSName& name) { return name.countLabels(); }); - luaCtx.registerFunction("hash", [](const DNSName& name) { return name.hash(); }); - luaCtx.registerFunction("wirelength", [](const DNSName& name) { return name.wirelength(); }); - luaCtx.registerFunction("tostring", [](const DNSName&dn ) { return dn.toString(); }); - luaCtx.registerFunction("toString", [](const DNSName&dn ) { return dn.toString(); }); - luaCtx.registerFunction("toStringNoDot", [](const DNSName&dn ) { return dn.toStringNoDot(); }); - luaCtx.registerFunction("__tostring", [](const DNSName&dn ) { return dn.toString(); }); - luaCtx.registerFunction("toDNSString", [](const DNSName&dn ) { return dn.toDNSString(); }); - luaCtx.registerFunction("makeRelative", [](const DNSName& dn, const DNSName& to) { return dn.makeRelative(to); }); + luaCtx.registerFunction("chopOff", [](DNSName& dn) { return dn.chopOff(); }); + luaCtx.registerFunction("countLabels", [](const DNSName& name) { return name.countLabels(); }); + luaCtx.registerFunction("hash", [](const DNSName& name) { return name.hash(); }); + luaCtx.registerFunction("wirelength", [](const DNSName& name) { return name.wirelength(); }); + luaCtx.registerFunction("tostring", [](const DNSName& dn) { return dn.toString(); }); + luaCtx.registerFunction("toString", [](const DNSName& dn) { return dn.toString(); }); + luaCtx.registerFunction("toStringNoDot", [](const DNSName& dn) { return dn.toStringNoDot(); }); + luaCtx.registerFunction("__tostring", [](const DNSName& dn) { return dn.toString(); }); + luaCtx.registerFunction("toDNSString", [](const DNSName& dn) { return dn.toDNSString(); }); + luaCtx.registerFunction("makeRelative", [](const DNSName& dn, const DNSName& to) { return dn.makeRelative(to); }); luaCtx.writeFunction("newDNSName", [](const std::string& name) { return DNSName(name); }); luaCtx.writeFunction("newDNSNameFromRaw", [](const std::string& name) { return DNSName(name.c_str(), name.size(), 0, false); }); luaCtx.writeFunction("newSuffixMatchNode", []() { return SuffixMatchNode(); }); luaCtx.writeFunction("newDNSNameSet", []() { return DNSNameSet(); }); /* DNSNameSet */ - luaCtx.registerFunction("toString", [](const DNSNameSet&dns ) { return dns.toString(); }); - luaCtx.registerFunction("__tostring", [](const DNSNameSet&dns ) { return dns.toString(); }); - luaCtx.registerFunction("add", [](DNSNameSet& dns, DNSName& dn) { dns.insert(dn); }); - luaCtx.registerFunction("check", [](DNSNameSet& dns, DNSName& dn) { return dns.find(dn) != dns.end(); }); - luaCtx.registerFunction("delete",(size_t (DNSNameSet::*)(const DNSName&)) &DNSNameSet::erase); - luaCtx.registerFunction("size",(size_t (DNSNameSet::*)() const) &DNSNameSet::size); - luaCtx.registerFunction("clear",(void (DNSNameSet::*)()) &DNSNameSet::clear); - luaCtx.registerFunction("empty",(bool (DNSNameSet::*)() const) &DNSNameSet::empty); + luaCtx.registerFunction("toString", [](const DNSNameSet& dns) { return dns.toString(); }); + luaCtx.registerFunction("__tostring", [](const DNSNameSet& dns) { return dns.toString(); }); + luaCtx.registerFunction("add", [](DNSNameSet& dns, DNSName& dn) { dns.insert(dn); }); + luaCtx.registerFunction("check", [](DNSNameSet& dns, DNSName& dn) { return dns.find(dn) != dns.end(); }); + luaCtx.registerFunction("delete", (size_t(DNSNameSet::*)(const DNSName&)) & DNSNameSet::erase); + luaCtx.registerFunction("size", (size_t(DNSNameSet::*)() const) & DNSNameSet::size); + luaCtx.registerFunction("clear", (void(DNSNameSet::*)()) & DNSNameSet::clear); + luaCtx.registerFunction("empty", (bool(DNSNameSet::*)() const) & DNSNameSet::empty); #endif /* DISABLE_DNSNAME_BINDINGS */ #ifndef DISABLE_SUFFIX_MATCH_BINDINGS /* SuffixMatchNode */ - luaCtx.registerFunction, LuaArray> &name)>("add", [](SuffixMatchNode &smn, const boost::variant, LuaArray> &name) { - if (name.type() == typeid(DNSName)) { - const auto& actualName = boost::get(name); - smn.add(actualName); - return; - } - if (name.type() == typeid(std::string)) { - const auto& actualName = boost::get(name); - smn.add(actualName); - return; - } - if (name.type() == typeid(LuaArray)) { - const auto& names = boost::get>(name); - for (const auto& actualName : names) { - smn.add(actualName.second); - } - return; + luaCtx.registerFunction, LuaArray>& name)>("add", [](SuffixMatchNode& smn, const boost::variant, LuaArray>& name) { + if (name.type() == typeid(DNSName)) { + const auto& actualName = boost::get(name); + smn.add(actualName); + return; + } + if (name.type() == typeid(std::string)) { + const auto& actualName = boost::get(name); + smn.add(actualName); + return; + } + if (name.type() == typeid(LuaArray)) { + const auto& names = boost::get>(name); + for (const auto& actualName : names) { + smn.add(actualName.second); } - if (name.type() == typeid(LuaArray)) { - const auto& names = boost::get>(name); - for (const auto& actualName : names) { - smn.add(actualName.second); - } - return; + return; + } + if (name.type() == typeid(LuaArray)) { + const auto& names = boost::get>(name); + for (const auto& actualName : names) { + smn.add(actualName.second); } + return; + } }); - luaCtx.registerFunction, LuaArray> &name)>("remove", [](SuffixMatchNode &smn, const boost::variant, LuaArray> &name) { - if (name.type() == typeid(DNSName)) { - const auto& actualName = boost::get(name); - smn.remove(actualName); - return; - } - if (name.type() == typeid(string)) { - const auto& actualName = boost::get(name); - DNSName dnsName(actualName); - smn.remove(dnsName); - return; - } - if (name.type() == typeid(LuaArray)) { - const auto& names = boost::get>(name); - for (const auto& actualName : names) { - smn.remove(actualName.second); - } - return; + luaCtx.registerFunction, LuaArray>& name)>("remove", [](SuffixMatchNode& smn, const boost::variant, LuaArray>& name) { + if (name.type() == typeid(DNSName)) { + const auto& actualName = boost::get(name); + smn.remove(actualName); + return; + } + if (name.type() == typeid(string)) { + const auto& actualName = boost::get(name); + DNSName dnsName(actualName); + smn.remove(dnsName); + return; + } + if (name.type() == typeid(LuaArray)) { + const auto& names = boost::get>(name); + for (const auto& actualName : names) { + smn.remove(actualName.second); } - if (name.type() == typeid(LuaArray)) { - const auto& names = boost::get>(name); - for (const auto& actualName : names) { - DNSName dnsName(actualName.second); - smn.remove(dnsName); - } - return; + return; + } + if (name.type() == typeid(LuaArray)) { + const auto& names = boost::get>(name); + for (const auto& actualName : names) { + DNSName dnsName(actualName.second); + smn.remove(dnsName); } + return; + } }); - luaCtx.registerFunction("check", (bool (SuffixMatchNode::*)(const DNSName&) const) &SuffixMatchNode::check); + luaCtx.registerFunction("check", (bool(SuffixMatchNode::*)(const DNSName&) const) & SuffixMatchNode::check); luaCtx.registerFunction (SuffixMatchNode::*)(const DNSName&) const>("getBestMatch", [](const SuffixMatchNode& smn, const DNSName& needle) { boost::optional result{boost::none}; auto res = smn.getBestMatch(needle); @@ -354,7 +358,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) #ifndef DISABLE_NETMASK_BINDINGS /* Netmask */ - luaCtx.writeFunction("newNetmask", [](boost::variant addrOrStr, boost::optional bits) { + luaCtx.writeFunction("newNetmask", [](boost::variant addrOrStr, boost::optional bits) { if (addrOrStr.type() == typeid(ComboAddress)) { const auto& comboAddr = boost::get(addrOrStr); if (bits) { @@ -370,13 +374,13 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) }); luaCtx.registerFunction("empty", &Netmask::empty); luaCtx.registerFunction("getBits", &Netmask::getBits); - luaCtx.registerFunction("getNetwork", [](const Netmask& nm) { return nm.getNetwork(); } ); // const reference makes this necessary - luaCtx.registerFunction("getMaskedNetwork", [](const Netmask& nm) { return nm.getMaskedNetwork(); } ); + luaCtx.registerFunction("getNetwork", [](const Netmask& nm) { return nm.getNetwork(); }); // const reference makes this necessary + luaCtx.registerFunction("getMaskedNetwork", [](const Netmask& nm) { return nm.getMaskedNetwork(); }); luaCtx.registerFunction("isIpv4", &Netmask::isIPv4); luaCtx.registerFunction("isIPv4", &Netmask::isIPv4); luaCtx.registerFunction("isIpv6", &Netmask::isIPv6); luaCtx.registerFunction("isIPv6", &Netmask::isIPv6); - luaCtx.registerFunction("match", (bool (Netmask::*)(const string&) const)&Netmask::match); + luaCtx.registerFunction("match", (bool(Netmask::*)(const string&) const) & Netmask::match); luaCtx.registerFunction("toString", &Netmask::toString); luaCtx.registerFunction("__tostring", &Netmask::toString); luaCtx.registerEqFunction(&Netmask::operator==); @@ -384,29 +388,27 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) /* NetmaskGroup */ luaCtx.writeFunction("newNMG", []() { return NetmaskGroup(); }); - luaCtx.registerFunction("addMask", [](NetmaskGroup& nmg, const std::string& mask) - { - nmg.addMask(mask); - }); - luaCtx.registerFunction("addNMG", [](NetmaskGroup& nmg, const NetmaskGroup& otherNMG) { + luaCtx.registerFunction("addMask", [](NetmaskGroup& nmg, const std::string& mask) { + nmg.addMask(mask); + }); + luaCtx.registerFunction("addNMG", [](NetmaskGroup& nmg, const NetmaskGroup& otherNMG) { /* this is not going to be very efficient, sorry */ auto entries = otherNMG.toStringVector(); for (const auto& entry : entries) { nmg.addMask(entry); } }); - luaCtx.registerFunction& map)>("addMasks", [](NetmaskGroup&nmg, const std::map& map) - { - for (const auto& entry : map) { - nmg.addMask(Netmask(entry.first)); - } - }); + luaCtx.registerFunction& map)>("addMasks", [](NetmaskGroup& nmg, const std::map& map) { + for (const auto& entry : map) { + nmg.addMask(Netmask(entry.first)); + } + }); - luaCtx.registerFunction("match", (bool (NetmaskGroup::*)(const ComboAddress&) const)&NetmaskGroup::match); + luaCtx.registerFunction("match", (bool(NetmaskGroup::*)(const ComboAddress&) const) & NetmaskGroup::match); luaCtx.registerFunction("size", &NetmaskGroup::size); luaCtx.registerFunction("clear", &NetmaskGroup::clear); - luaCtx.registerFunction("toString", [](const NetmaskGroup& nmg ) { return "NetmaskGroup " + nmg.toString(); }); - luaCtx.registerFunction("__tostring", [](const NetmaskGroup& nmg ) { return "NetmaskGroup " + nmg.toString(); }); + luaCtx.registerFunction("toString", [](const NetmaskGroup& nmg) { return "NetmaskGroup " + nmg.toString(); }); + luaCtx.registerFunction("__tostring", [](const NetmaskGroup& nmg) { return "NetmaskGroup " + nmg.toString(); }); #endif /* DISABLE_NETMASK_BINDINGS */ #ifndef DISABLE_QPS_LIMITER_BINDINGS @@ -417,48 +419,48 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) #ifndef DISABLE_CLIENT_STATE_BINDINGS /* ClientState */ - luaCtx.registerFunction("toString", [](const ClientState& fe) { - setLuaNoSideEffect(); - return fe.local.toStringWithPort(); - }); - luaCtx.registerFunction("__tostring", [](const ClientState& fe) { - setLuaNoSideEffect(); - return fe.local.toStringWithPort(); - }); - luaCtx.registerFunction("getType", [](const ClientState& fe) { - setLuaNoSideEffect(); - return fe.getType(); - }); - luaCtx.registerFunction("getConfiguredTLSProvider", [](const ClientState& fe) { - setLuaNoSideEffect(); - if (fe.tlsFrontend != nullptr) { - return fe.tlsFrontend->getRequestedProvider(); - } - else if (fe.dohFrontend != nullptr) { - return std::string("openssl"); - } - return std::string(); + luaCtx.registerFunction("toString", [](const ClientState& fe) { + setLuaNoSideEffect(); + return fe.local.toStringWithPort(); }); - luaCtx.registerFunction("getEffectiveTLSProvider", [](const ClientState& fe) { - setLuaNoSideEffect(); - if (fe.tlsFrontend != nullptr) { - return fe.tlsFrontend->getEffectiveProvider(); - } - else if (fe.dohFrontend != nullptr) { - return std::string("openssl"); - } - return std::string(); + luaCtx.registerFunction("__tostring", [](const ClientState& fe) { + setLuaNoSideEffect(); + return fe.local.toStringWithPort(); + }); + luaCtx.registerFunction("getType", [](const ClientState& fe) { + setLuaNoSideEffect(); + return fe.getType(); + }); + luaCtx.registerFunction("getConfiguredTLSProvider", [](const ClientState& fe) { + setLuaNoSideEffect(); + if (fe.tlsFrontend != nullptr) { + return fe.tlsFrontend->getRequestedProvider(); + } + else if (fe.dohFrontend != nullptr) { + return std::string("openssl"); + } + return std::string(); + }); + luaCtx.registerFunction("getEffectiveTLSProvider", [](const ClientState& fe) { + setLuaNoSideEffect(); + if (fe.tlsFrontend != nullptr) { + return fe.tlsFrontend->getEffectiveProvider(); + } + else if (fe.dohFrontend != nullptr) { + return std::string("openssl"); + } + return std::string(); }); luaCtx.registerMember("muted", &ClientState::muted); #ifdef HAVE_EBPF - luaCtx.registerFunction)>("attachFilter", [](ClientState& frontend, std::shared_ptr bpf) { - if (bpf) { - frontend.attachFilter(bpf, frontend.getSocket()); - } - }); - luaCtx.registerFunction("detachFilter", [](ClientState& frontend) { - frontend.detachFilter(frontend.getSocket()); - }); + luaCtx.registerFunction)>("attachFilter", [](ClientState& frontend, std::shared_ptr bpf) { + if (bpf) { + frontend.attachFilter(bpf, frontend.getSocket()); + } + }); + luaCtx.registerFunction("detachFilter", [](ClientState& frontend) { + frontend.detachFilter(frontend.getSocket()); + }); #endif /* HAVE_EBPF */ #endif /* DISABLE_CLIENT_STATE_BINDINGS */ @@ -466,80 +468,80 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) #ifdef HAVE_EBPF using bpfopts_t = LuaAssociativeTable>; luaCtx.writeFunction("newBPFFilter", [client](bpfopts_t opts) { - if (client) { - return std::shared_ptr(nullptr); - } - std::unordered_map mapsConfig; - - const auto convertParamsToConfig = [&](const std::string& name, BPFFilter::MapType type) { - BPFFilter::MapConfiguration config; - config.d_type = type; - if (const string key = name + "MaxItems"; opts.count(key)) { - const auto& tmp = opts.at(key); - if (tmp.type() != typeid(uint32_t)) { - throw std::runtime_error("params is invalid"); - } - const auto& params = boost::get(tmp); - config.d_maxItems = params; + if (client) { + return std::shared_ptr(nullptr); + } + std::unordered_map mapsConfig; + + const auto convertParamsToConfig = [&](const std::string& name, BPFFilter::MapType type) { + BPFFilter::MapConfiguration config; + config.d_type = type; + if (const string key = name + "MaxItems"; opts.count(key)) { + const auto& tmp = opts.at(key); + if (tmp.type() != typeid(uint32_t)) { + throw std::runtime_error("params is invalid"); } + const auto& params = boost::get(tmp); + config.d_maxItems = params; + } - if (const string key = name + "PinnedPath"; opts.count(key)) { - auto& tmp = opts.at(key); - if (tmp.type() != typeid(string)) { - throw std::runtime_error("params is invalid"); - } - auto& params = boost::get(tmp); - config.d_pinnedPath = std::move(params); - } - mapsConfig[name] = std::move(config); - }; - - convertParamsToConfig("ipv4", BPFFilter::MapType::IPv4); - convertParamsToConfig("ipv6", BPFFilter::MapType::IPv6); - convertParamsToConfig("qnames", BPFFilter::MapType::QNames); - convertParamsToConfig("cidr4", BPFFilter::MapType::CIDR4); - convertParamsToConfig("cidr6", BPFFilter::MapType::CIDR6); - - BPFFilter::MapFormat format = BPFFilter::MapFormat::Legacy; - bool external = false; - if (opts.count("external")) { - const auto& tmp = opts.at("external"); - if (tmp.type() != typeid(bool)) { + if (const string key = name + "PinnedPath"; opts.count(key)) { + auto& tmp = opts.at(key); + if (tmp.type() != typeid(string)) { throw std::runtime_error("params is invalid"); } - if ((external = boost::get(tmp))) { - format = BPFFilter::MapFormat::WithActions; - } + auto& params = boost::get(tmp); + config.d_pinnedPath = std::move(params); + } + mapsConfig[name] = std::move(config); + }; + + convertParamsToConfig("ipv4", BPFFilter::MapType::IPv4); + convertParamsToConfig("ipv6", BPFFilter::MapType::IPv6); + convertParamsToConfig("qnames", BPFFilter::MapType::QNames); + convertParamsToConfig("cidr4", BPFFilter::MapType::CIDR4); + convertParamsToConfig("cidr6", BPFFilter::MapType::CIDR6); + + BPFFilter::MapFormat format = BPFFilter::MapFormat::Legacy; + bool external = false; + if (opts.count("external")) { + const auto& tmp = opts.at("external"); + if (tmp.type() != typeid(bool)) { + throw std::runtime_error("params is invalid"); + } + if ((external = boost::get(tmp))) { + format = BPFFilter::MapFormat::WithActions; } + } - return std::make_shared(mapsConfig, format, external); + return std::make_shared(mapsConfig, format, external); }); - luaCtx.registerFunction::*)(const ComboAddress& ca, boost::optional action)>("block", [](std::shared_ptr bpf, const ComboAddress& ca, boost::optional action) { - if (bpf) { - if (!action) { - return bpf->block(ca, BPFFilter::MatchAction::Drop); - } - else { - BPFFilter::MatchAction match; - - switch (*action) { - case 0: - match = BPFFilter::MatchAction::Pass; - break; - case 1: - match = BPFFilter::MatchAction::Drop; - break; - case 2: - match = BPFFilter::MatchAction::Truncate; - break; - default: - throw std::runtime_error("Unsupported action for BPFFilter::block"); - } - return bpf->block(ca, match); + luaCtx.registerFunction::*)(const ComboAddress& ca, boost::optional action)>("block", [](std::shared_ptr bpf, const ComboAddress& ca, boost::optional action) { + if (bpf) { + if (!action) { + return bpf->block(ca, BPFFilter::MatchAction::Drop); + } + else { + BPFFilter::MatchAction match; + + switch (*action) { + case 0: + match = BPFFilter::MatchAction::Pass; + break; + case 1: + match = BPFFilter::MatchAction::Drop; + break; + case 2: + match = BPFFilter::MatchAction::Truncate; + break; + default: + throw std::runtime_error("Unsupported action for BPFFilter::block"); } + return bpf->block(ca, match); } - }); + } + }); luaCtx.registerFunction::*)(const string& range, uint32_t action, boost::optional force)>("addRangeRule", [](std::shared_ptr bpf, const string& range, uint32_t action, boost::optional force) { if (!bpf) { return; @@ -560,37 +562,37 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } return bpf->addRangeRule(Netmask(range), force ? *force : false, match); }); - luaCtx.registerFunction::*)(const DNSName& qname, boost::optional qtype, boost::optional action)>("blockQName", [](std::shared_ptr bpf, const DNSName& qname, boost::optional qtype, boost::optional action) { - if (bpf) { - if (!action) { - return bpf->block(qname, BPFFilter::MatchAction::Drop, qtype ? *qtype : 255); - } - else { - BPFFilter::MatchAction match; - - switch (*action) { - case 0: - match = BPFFilter::MatchAction::Pass; - break; - case 1: - match = BPFFilter::MatchAction::Drop; - break; - case 2: - match = BPFFilter::MatchAction::Truncate; - break; - default: - throw std::runtime_error("Unsupported action for BPFFilter::blockQName"); - } - return bpf->block(qname, match, qtype ? *qtype : 255); + luaCtx.registerFunction::*)(const DNSName& qname, boost::optional qtype, boost::optional action)>("blockQName", [](std::shared_ptr bpf, const DNSName& qname, boost::optional qtype, boost::optional action) { + if (bpf) { + if (!action) { + return bpf->block(qname, BPFFilter::MatchAction::Drop, qtype ? *qtype : 255); + } + else { + BPFFilter::MatchAction match; + + switch (*action) { + case 0: + match = BPFFilter::MatchAction::Pass; + break; + case 1: + match = BPFFilter::MatchAction::Drop; + break; + case 2: + match = BPFFilter::MatchAction::Truncate; + break; + default: + throw std::runtime_error("Unsupported action for BPFFilter::blockQName"); } + return bpf->block(qname, match, qtype ? *qtype : 255); } - }); + } + }); - luaCtx.registerFunction::*)(const ComboAddress& ca)>("unblock", [](std::shared_ptr bpf, const ComboAddress& ca) { - if (bpf) { - return bpf->unblock(ca); - } - }); + luaCtx.registerFunction::*)(const ComboAddress& ca)>("unblock", [](std::shared_ptr bpf, const ComboAddress& ca) { + if (bpf) { + return bpf->unblock(ca); + } + }); luaCtx.registerFunction::*)(const string& range)>("rmRangeRule", [](std::shared_ptr bpf, const string& range) { if (!bpf) { return; @@ -614,108 +616,108 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } return res; }); - luaCtx.registerFunction::*)(const DNSName& qname, boost::optional qtype)>("unblockQName", [](std::shared_ptr bpf, const DNSName& qname, boost::optional qtype) { - if (bpf) { - return bpf->unblock(qname, qtype ? *qtype : 255); - } - }); + luaCtx.registerFunction::*)(const DNSName& qname, boost::optional qtype)>("unblockQName", [](std::shared_ptr bpf, const DNSName& qname, boost::optional qtype) { + if (bpf) { + return bpf->unblock(qname, qtype ? *qtype : 255); + } + }); - luaCtx.registerFunction::*)()const>("getStats", [](const std::shared_ptr bpf) { - setLuaNoSideEffect(); - std::string res; - if (bpf) { - auto stats = bpf->getAddrStats(); - for (const auto& value : stats) { - if (value.first.sin4.sin_family == AF_INET) { - res += value.first.toString() + ": " + std::to_string(value.second) + "\n"; - } - else if (value.first.sin4.sin_family == AF_INET6) { - res += "[" + value.first.toString() + "]: " + std::to_string(value.second) + "\n"; - } + luaCtx.registerFunction::*)() const>("getStats", [](const std::shared_ptr bpf) { + setLuaNoSideEffect(); + std::string res; + if (bpf) { + auto stats = bpf->getAddrStats(); + for (const auto& value : stats) { + if (value.first.sin4.sin_family == AF_INET) { + res += value.first.toString() + ": " + std::to_string(value.second) + "\n"; } - const auto rangeStat = bpf->getRangeRule(); - for (const auto& value : rangeStat) { - if (value.first.isIPv4()) { - res += BPFFilter::toString(value.second.action) + "\t " + value.first.toString() + ": " + std::to_string(value.second.counter) + "\n"; - } - else if (value.first.isIPv6()) { - res += BPFFilter::toString(value.second.action) + "\t[" + value.first.toString() + "]: " + std::to_string(value.second.counter) + "\n"; - } + else if (value.first.sin4.sin_family == AF_INET6) { + res += "[" + value.first.toString() + "]: " + std::to_string(value.second) + "\n"; } - auto qstats = bpf->getQNameStats(); - for (const auto& value : qstats) { - res += std::get<0>(value).toString() + " " + std::to_string(std::get<1>(value)) + ": " + std::to_string(std::get<2>(value)) + "\n"; + } + const auto rangeStat = bpf->getRangeRule(); + for (const auto& value : rangeStat) { + if (value.first.isIPv4()) { + res += BPFFilter::toString(value.second.action) + "\t " + value.first.toString() + ": " + std::to_string(value.second.counter) + "\n"; + } + else if (value.first.isIPv6()) { + res += BPFFilter::toString(value.second.action) + "\t[" + value.first.toString() + "]: " + std::to_string(value.second.counter) + "\n"; } } - return res; - }); - - luaCtx.registerFunction::*)()>("attachToAllBinds", [](std::shared_ptr bpf) { - std::string res; - if (!g_configurationDone) { - throw std::runtime_error("attachToAllBinds() cannot be used at configuration time!"); - return; + auto qstats = bpf->getQNameStats(); + for (const auto& value : qstats) { + res += std::get<0>(value).toString() + " " + std::to_string(std::get<1>(value)) + ": " + std::to_string(std::get<2>(value)) + "\n"; } - if (bpf) { - for (const auto& frontend : g_frontends) { - frontend->attachFilter(bpf, frontend->getSocket()); - } + } + return res; + }); + + luaCtx.registerFunction::*)()>("attachToAllBinds", [](std::shared_ptr bpf) { + std::string res; + if (!g_configurationDone) { + throw std::runtime_error("attachToAllBinds() cannot be used at configuration time!"); + return; + } + if (bpf) { + for (const auto& frontend : g_frontends) { + frontend->attachFilter(bpf, frontend->getSocket()); } - }); + } + }); - luaCtx.writeFunction("newDynBPFFilter", [client](std::shared_ptr bpf) { - if (client) { - return std::shared_ptr(nullptr); - } - return std::make_shared(bpf); - }); - - luaCtx.registerFunction::*)(const ComboAddress& addr, boost::optional seconds)>("block", [](std::shared_ptr dbpf, const ComboAddress& addr, boost::optional seconds) { - if (dbpf) { - struct timespec until; - clock_gettime(CLOCK_MONOTONIC, &until); - until.tv_sec += seconds ? *seconds : 10; - dbpf->block(addr, until); - } - }); + luaCtx.writeFunction("newDynBPFFilter", [client](std::shared_ptr bpf) { + if (client) { + return std::shared_ptr(nullptr); + } + return std::make_shared(bpf); + }); - luaCtx.registerFunction::*)()>("purgeExpired", [](std::shared_ptr dbpf) { - if (dbpf) { - struct timespec now; - clock_gettime(CLOCK_MONOTONIC, &now); - dbpf->purgeExpired(now); - } - }); + luaCtx.registerFunction::*)(const ComboAddress& addr, boost::optional seconds)>("block", [](std::shared_ptr dbpf, const ComboAddress& addr, boost::optional seconds) { + if (dbpf) { + struct timespec until; + clock_gettime(CLOCK_MONOTONIC, &until); + until.tv_sec += seconds ? *seconds : 10; + dbpf->block(addr, until); + } + }); - luaCtx.registerFunction::*)(LuaTypeOrArrayOf)>("excludeRange", [](std::shared_ptr dbpf, LuaTypeOrArrayOf ranges) { - if (!dbpf) { - return; - } + luaCtx.registerFunction::*)()>("purgeExpired", [](std::shared_ptr dbpf) { + if (dbpf) { + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + dbpf->purgeExpired(now); + } + }); - if (ranges.type() == typeid(LuaArray)) { - for (const auto& range : *boost::get>(&ranges)) { - dbpf->excludeRange(Netmask(range.second)); - } - } - else { - dbpf->excludeRange(Netmask(*boost::get(&ranges))); - } - }); + luaCtx.registerFunction::*)(LuaTypeOrArrayOf)>("excludeRange", [](std::shared_ptr dbpf, LuaTypeOrArrayOf ranges) { + if (!dbpf) { + return; + } - luaCtx.registerFunction::*)(LuaTypeOrArrayOf)>("includeRange", [](std::shared_ptr dbpf, LuaTypeOrArrayOf ranges) { - if (!dbpf) { - return; + if (ranges.type() == typeid(LuaArray)) { + for (const auto& range : *boost::get>(&ranges)) { + dbpf->excludeRange(Netmask(range.second)); } + } + else { + dbpf->excludeRange(Netmask(*boost::get(&ranges))); + } + }); - if (ranges.type() == typeid(LuaArray)) { - for (const auto& range : *boost::get>(&ranges)) { - dbpf->includeRange(Netmask(range.second)); - } - } - else { - dbpf->includeRange(Netmask(*boost::get(&ranges))); + luaCtx.registerFunction::*)(LuaTypeOrArrayOf)>("includeRange", [](std::shared_ptr dbpf, LuaTypeOrArrayOf ranges) { + if (!dbpf) { + return; + } + + if (ranges.type() == typeid(LuaArray)) { + for (const auto& range : *boost::get>(&ranges)) { + dbpf->includeRange(Netmask(range.second)); } - }); + } + else { + dbpf->includeRange(Netmask(*boost::get(&ranges))); + } + }); #endif /* HAVE_EBPF */ #ifdef HAVE_XSK using xskopt_t = LuaAssociativeTable>; @@ -752,7 +754,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) dnsdist::xsk::g_xsk.push_back(socket); return socket; }); - luaCtx.registerFunction::*)()const>("getMetrics", [](const std::shared_ptr& xsk) -> std::string { + luaCtx.registerFunction::*)() const>("getMetrics", [](const std::shared_ptr& xsk) -> std::string { if (!xsk) { return {}; } @@ -760,10 +762,10 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) }); #endif /* HAVE_XSK */ /* EDNSOptionView */ - luaCtx.registerFunction("count", [](const EDNSOptionView& option) { - return option.values.size(); - }); - luaCtx.registerFunction(EDNSOptionView::*)()const>("getValues", [] (const EDNSOptionView& option) { + luaCtx.registerFunction("count", [](const EDNSOptionView& option) { + return option.values.size(); + }); + luaCtx.registerFunction (EDNSOptionView::*)() const>("getValues", [](const EDNSOptionView& option) { std::vector values; for (const auto& value : option.values) { values.push_back(std::string(value.content, value.size)); @@ -783,8 +785,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) return std::make_shared(regex, status, PacketBuffer(content.begin(), content.end()), headers); }); - luaCtx.writeFunction("newSVCRecordParameters", [](uint64_t priority, const std::string& target, boost::optional additionalParameters) - { + luaCtx.writeFunction("newSVCRecordParameters", [](uint64_t priority, const std::string& target, boost::optional additionalParameters) { checkParameterBound("newSVCRecordParameters", priority, std::numeric_limits::max()); SVCRecordParameters parameters; if (additionalParameters) { @@ -842,7 +843,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) if (client || configCheck) { return; } - std::thread newThread(dnsdist::resolver::asynchronousResolver, std::move(hostname), [callback=std::move(callback)](const std::string& resolvedHostname, std::vector& ips) { + std::thread newThread(dnsdist::resolver::asynchronousResolver, std::move(hostname), [callback = std::move(callback)](const std::string& resolvedHostname, std::vector& ips) { LuaArray result; result.reserve(ips.size()); for (const auto& entry : ips) { diff --git a/pdns/dnsdistdist/dnsdist-lua-inspection.cc b/pdns/dnsdistdist/dnsdist-lua-inspection.cc index 35b5c8b9b344..304a05af5d01 100644 --- a/pdns/dnsdistdist/dnsdist-lua-inspection.cc +++ b/pdns/dnsdistdist/dnsdist-lua-inspection.cc @@ -31,17 +31,17 @@ #include "statnode.hh" #ifndef DISABLE_TOP_N_BINDINGS -static LuaArray>> getGenResponses(uint64_t top, boost::optional labels, std::function pred) +static LuaArray>> getGenResponses(uint64_t top, boost::optional labels, std::function pred) { setLuaNoSideEffect(); map counts; - unsigned int total=0; + unsigned int total = 0; { for (const auto& shard : g_rings.d_shards) { auto rl = shard->respRing.lock(); if (!labels) { - for(const auto& a : *rl) { - if(!pred(a)) + for (const auto& a : *rl) { + if (!pred(a)) continue; counts[a.name]++; total++; @@ -49,8 +49,8 @@ static LuaArray>> getGenResponses(uint } else { unsigned int lab = *labels; - for(const auto& a : *rl) { - if(!pred(a)) + for (const auto& a : *rl) { + if (!pred(a)) continue; DNSName temp(a.name); @@ -67,29 +67,28 @@ static LuaArray>> getGenResponses(uint for (const auto& c : counts) rcounts.emplace_back(c.second, c.first.makeLowerCase()); - sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& a, - const decltype(rcounts)::value_type& b) { - return b.first < a.first; - }); + sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& a, const decltype(rcounts)::value_type& b) { + return b.first < a.first; + }); - LuaArray>> ret; + LuaArray>> ret; ret.reserve(std::min(rcounts.size(), static_cast(top + 1U))); int count = 1; unsigned int rest = 0; for (const auto& rc : rcounts) { if (count == static_cast(top + 1)) { - rest+=rc.first; + rest += rc.first; } else { - ret.push_back({count++, {rc.second.toString(), rc.first, 100.0*rc.first/total}}); + ret.push_back({count++, {rc.second.toString(), rc.first, 100.0 * rc.first / total}}); } } if (total > 0) { - ret.push_back({count, {"Rest", rest, 100.0*rest/total}}); + ret.push_back({count, {"Rest", rest, 100.0 * rest / total}}); } else { - ret.push_back({count, {"Rest", rest, 100.0 }}); + ret.push_back({count, {"Rest", rest, 100.0}}); } return ret; @@ -102,12 +101,12 @@ static LuaArray>> getGenResponses(uint typedef std::unordered_map counts_t; static counts_t filterScore(const counts_t& counts, - double delta, unsigned int rate) + double delta, unsigned int rate) { counts_t ret; - double lim = delta*rate; - for(const auto& c : counts) { + double lim = delta * rate; + for (const auto& c : counts) { if (c.second > lim) { ret[c.first] = c.second; } @@ -129,8 +128,8 @@ static void statNodeRespRing(statvisitor_t visitor, uint64_t seconds) for (const auto& shard : g_rings.d_shards) { auto rl = shard->respRing.lock(); - for(const auto& c : *rl) { - if (now < c.when){ + for (const auto& c : *rl) { + if (now < c.when) { continue; } @@ -144,8 +143,7 @@ static void statNodeRespRing(statvisitor_t visitor, uint64_t seconds) } StatNode::Stat node; - root.visit([visitor = std::move(visitor)](const StatNode* node_, const StatNode::Stat& self, const StatNode::Stat& children) { - visitor(*node_, self, children);}, node); + root.visit([visitor = std::move(visitor)](const StatNode* node_, const StatNode::Stat& self, const StatNode::Stat& children) { visitor(*node_, self, children); }, node); } static LuaArray> getRespRing(boost::optional rcode) @@ -184,15 +182,15 @@ static counts_t exceedRespGen(unsigned int rate, int seconds, std::functionrespRing.lock(); - for(const auto& c : *rl) { + for (const auto& c : *rl) { - if(seconds && c.when < cutoff) + if (seconds && c.when < cutoff) continue; - if(now < c.when) + if (now < c.when) continue; T(counts, c); - if(c.when < mintime) + if (c.when < mintime) mintime = c.when; } } @@ -213,13 +211,13 @@ static counts_t exceedQueryGen(unsigned int rate, int seconds, std::functionqueryRing.lock(); - for(const auto& c : *rl) { - if(seconds && c.when < cutoff) + for (const auto& c : *rl) { + if (seconds && c.when < cutoff) continue; - if(now < c.when) + if (now < c.when) continue; T(counts, c); - if(c.when < mintime) + if (c.when < mintime) mintime = c.when; } } @@ -228,22 +226,19 @@ static counts_t exceedQueryGen(unsigned int rate, int seconds, std::function top_) { - setLuaNoSideEffect(); - uint64_t top = top_ ? *top_ : 10U; - map counts; - unsigned int total=0; - { - for (const auto& shard : g_rings.d_shards) { - auto rl = shard->queryRing.lock(); - for(const auto& c : *rl) { - counts[c.requestor]++; - total++; - } + setLuaNoSideEffect(); + uint64_t top = top_ ? *top_ : 10U; + map counts; + unsigned int total = 0; + { + for (const auto& shard : g_rings.d_shards) { + auto rl = shard->queryRing.lock(); + for (const auto& c : *rl) { + counts[c.requestor]++; + total++; } } - vector> rcounts; - rcounts.reserve(counts.size()); - for(const auto& c : counts) - rcounts.emplace_back(c.second, c.first); - - sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& a, - const decltype(rcounts)::value_type& b) { - return b.first < a.first; - }); - unsigned int count=1, rest=0; - boost::format fmt("%4d %-40s %4d %4.1f%%\n"); - for(const auto& rc : rcounts) { - if(count==top+1) - rest+=rc.first; - else - g_outputBuffer += (fmt % (count++) % rc.second.toString() % rc.first % (100.0*rc.first/total)).str(); - } - g_outputBuffer += (fmt % (count) % "Rest" % rest % (total > 0 ? 100.0*rest/total : 100.0)).str(); - }); + } + vector> rcounts; + rcounts.reserve(counts.size()); + for (const auto& c : counts) + rcounts.emplace_back(c.second, c.first); + + sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& a, const decltype(rcounts)::value_type& b) { + return b.first < a.first; + }); + unsigned int count = 1, rest = 0; + boost::format fmt("%4d %-40s %4d %4.1f%%\n"); + for (const auto& rc : rcounts) { + if (count == top + 1) + rest += rc.first; + else + g_outputBuffer += (fmt % (count++) % rc.second.toString() % rc.first % (100.0 * rc.first / total)).str(); + } + g_outputBuffer += (fmt % (count) % "Rest" % rest % (total > 0 ? 100.0 * rest / total : 100.0)).str(); + }); luaCtx.writeFunction("getTopQueries", [](uint64_t top, boost::optional labels) { - setLuaNoSideEffect(); - map counts; - unsigned int total=0; - if(!labels) { - for (const auto& shard : g_rings.d_shards) { - auto rl = shard->queryRing.lock(); - for(const auto& a : *rl) { - counts[a.name]++; - total++; - } + setLuaNoSideEffect(); + map counts; + unsigned int total = 0; + if (!labels) { + for (const auto& shard : g_rings.d_shards) { + auto rl = shard->queryRing.lock(); + for (const auto& a : *rl) { + counts[a.name]++; + total++; } } - else { - unsigned int lab = *labels; - for (const auto& shard : g_rings.d_shards) { - auto rl = shard->queryRing.lock(); - // coverity[auto_causes_copy] - for (auto a : *rl) { - a.name.trimToLabels(lab); - counts[a.name]++; - total++; - } + } + else { + unsigned int lab = *labels; + for (const auto& shard : g_rings.d_shards) { + auto rl = shard->queryRing.lock(); + // coverity[auto_causes_copy] + for (auto a : *rl) { + a.name.trimToLabels(lab); + counts[a.name]++; + total++; } } - // cout<<"Looked at "<> rcounts; - rcounts.reserve(counts.size()); - for(const auto& c : counts) - rcounts.emplace_back(c.second, c.first.makeLowerCase()); - - sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& a, - const decltype(rcounts)::value_type& b) { - return b.first < a.first; - }); - - std::unordered_map>> ret; - unsigned int count=1, rest=0; - for(const auto& rc : rcounts) { - if(count==top+1) - rest+=rc.first; - else - ret.insert({count++, {rc.second.toString(), rc.first, 100.0*rc.first/total}}); - } - - if (total > 0) { - ret.insert({count, {"Rest", rest, 100.0*rest/total}}); - } - else { - ret.insert({count, {"Rest", rest, 100.0}}); - } + } + // cout<<"Looked at "<> rcounts; + rcounts.reserve(counts.size()); + for (const auto& c : counts) + rcounts.emplace_back(c.second, c.first.makeLowerCase()); + + sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& a, const decltype(rcounts)::value_type& b) { + return b.first < a.first; + }); + + std::unordered_map>> ret; + unsigned int count = 1, rest = 0; + for (const auto& rc : rcounts) { + if (count == top + 1) + rest += rc.first; + else + ret.insert({count++, {rc.second.toString(), rc.first, 100.0 * rc.first / total}}); + } - return ret; + if (total > 0) { + ret.insert({count, {"Rest", rest, 100.0 * rest / total}}); + } + else { + ret.insert({count, {"Rest", rest, 100.0}}); + } - }); + return ret; + }); luaCtx.executeCode(R"(function topQueries(top, labels) top = top or 10; for k,v in ipairs(getTopQueries(top,labels)) do show(string.format("%4d %-40s %4d %4.1f%%",k,v[1],v[2], v[3])) end end)"); luaCtx.writeFunction("getResponseRing", []() { - setLuaNoSideEffect(); - size_t totalEntries = 0; - std::vector> rings; - rings.reserve(g_rings.getNumberOfShards()); - for (const auto& shard : g_rings.d_shards) { - { - auto rl = shard->respRing.lock(); - rings.push_back(*rl); - } - totalEntries += rings.back().size(); - } - vector > > ret; - ret.reserve(totalEntries); - decltype(ret)::value_type item; - for (size_t idx = 0; idx < rings.size(); idx++) { - for(const auto& r : rings[idx]) { - item["name"]=r.name.toString(); - item["qtype"]=r.qtype; - item["rcode"]=r.dh.rcode; - item["usec"]=r.usec; - ret.push_back(item); - } + setLuaNoSideEffect(); + size_t totalEntries = 0; + std::vector> rings; + rings.reserve(g_rings.getNumberOfShards()); + for (const auto& shard : g_rings.d_shards) { + { + auto rl = shard->respRing.lock(); + rings.push_back(*rl); } - return ret; - }); + totalEntries += rings.back().size(); + } + vector>> ret; + ret.reserve(totalEntries); + decltype(ret)::value_type item; + for (size_t idx = 0; idx < rings.size(); idx++) { + for (const auto& r : rings[idx]) { + item["name"] = r.name.toString(); + item["qtype"] = r.qtype; + item["rcode"] = r.dh.rcode; + item["usec"] = r.usec; + ret.push_back(item); + } + } + return ret; + }); luaCtx.writeFunction("getTopResponses", [](uint64_t top, uint64_t kind, boost::optional labels) { - return getGenResponses(top, labels, [kind](const Rings::Response& r) { return r.dh.rcode == kind; }); - }); + return getGenResponses(top, labels, [kind](const Rings::Response& r) { return r.dh.rcode == kind; }); + }); luaCtx.executeCode(R"(function topResponses(top, kind, labels) top = top or 10; kind = kind or 0; for k,v in ipairs(getTopResponses(top, kind, labels)) do show(string.format("%4d %-40s %4d %4.1f%%",k,v[1],v[2],v[3])) end end)"); - luaCtx.writeFunction("getSlowResponses", [](uint64_t top, uint64_t msec, boost::optional labels) { - return getGenResponses(top, labels, [msec](const Rings::Response& r) { return r.usec > msec*1000; }); - }); - + return getGenResponses(top, labels, [msec](const Rings::Response& r) { return r.usec > msec * 1000; }); + }); luaCtx.executeCode(R"(function topSlow(top, msec, labels) top = top or 10; msec = msec or 500; for k,v in ipairs(getSlowResponses(top, msec, labels)) do show(string.format("%4d %-40s %4d %4.1f%%",k,v[1],v[2],v[3])) end end)"); luaCtx.writeFunction("getTopBandwidth", [](uint64_t top) { - setLuaNoSideEffect(); - return g_rings.getTopBandwidth(top); - }); + setLuaNoSideEffect(); + return g_rings.getTopBandwidth(top); + }); luaCtx.executeCode(R"(function topBandwidth(top) top = top or 10; for k,v in ipairs(getTopBandwidth(top)) do show(string.format("%4d %-40s %4d %4.1f%%",k,v[1],v[2],v[3])) end end)"); #endif /* DISABLE_TOP_N_BINDINGS */ luaCtx.writeFunction("delta", []() { - setLuaNoSideEffect(); - // we hold the lua lock already! - for(const auto& d : g_confDelta) { - struct tm tm; - localtime_r(&d.first.tv_sec, &tm); - char date[80]; - strftime(date, sizeof(date)-1, "-- %a %b %d %Y %H:%M:%S %Z\n", &tm); - g_outputBuffer += date; - g_outputBuffer += d.second + "\n"; - } - }); + setLuaNoSideEffect(); + // we hold the lua lock already! + for (const auto& d : g_confDelta) { + struct tm tm; + localtime_r(&d.first.tv_sec, &tm); + char date[80]; + strftime(date, sizeof(date) - 1, "-- %a %b %d %Y %H:%M:%S %Z\n", &tm); + g_outputBuffer += date; + g_outputBuffer += d.second + "\n"; + } + }); luaCtx.writeFunction("grepq", [](LuaTypeOrArrayOf inp, boost::optional limit, boost::optional> options) { - setLuaNoSideEffect(); - boost::optional nm; - boost::optional dn; - int msec = -1; - std::unique_ptr outputFile{nullptr, fclose}; - - if (options) { - std::string outputFileName; - if (getOptionalValue(options, "outputFile", outputFileName) > 0) { - int fd = open(outputFileName.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0600); - if (fd < 0) { - g_outputBuffer = "Error opening dump file for writing: " + stringerror() + "\n"; - return; - } - outputFile = std::unique_ptr(fdopen(fd, "w"), fclose); - if (outputFile == nullptr) { - g_outputBuffer = "Error opening dump file for writing: " + stringerror() + "\n"; - close(fd); - return; - } - } - checkAllParametersConsumed("grepq", options); - } + setLuaNoSideEffect(); + boost::optional nm; + boost::optional dn; + int msec = -1; + std::unique_ptr outputFile{nullptr, fclose}; + + if (options) { + std::string outputFileName; + if (getOptionalValue(options, "outputFile", outputFileName) > 0) { + int fd = open(outputFileName.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0600); + if (fd < 0) { + g_outputBuffer = "Error opening dump file for writing: " + stringerror() + "\n"; + return; + } + outputFile = std::unique_ptr(fdopen(fd, "w"), fclose); + if (outputFile == nullptr) { + g_outputBuffer = "Error opening dump file for writing: " + stringerror() + "\n"; + close(fd); + return; + } + } + checkAllParametersConsumed("grepq", options); + } - vector vec; - auto str = boost::get(&inp); - if (str) { - vec.push_back(*str); - } - else { - auto v = boost::get>(inp); - for (const auto& a: v) { - vec.push_back(a.second); - } + vector vec; + auto str = boost::get(&inp); + if (str) { + vec.push_back(*str); + } + else { + auto v = boost::get>(inp); + for (const auto& a : v) { + vec.push_back(a.second); } + } - for (const auto& s : vec) { - try { - nm = Netmask(s); + for (const auto& s : vec) { + try { + nm = Netmask(s); + } + catch (...) { + if (boost::ends_with(s, "ms") && sscanf(s.c_str(), "%ums", &msec)) { + ; } - catch (...) { - if (boost::ends_with(s,"ms") && sscanf(s.c_str(), "%ums", &msec)) { - ; + else { + try { + dn = DNSName(s); } - else { - try { - dn = DNSName(s); - } - catch (...) { - g_outputBuffer = "Could not parse '"+s+"' as domain name or netmask"; - return; - } + catch (...) { + g_outputBuffer = "Could not parse '" + s + "' as domain name or netmask"; + return; } } } + } - std::vector qr; - std::vector rr; - qr.reserve(g_rings.getNumberOfQueryEntries()); - rr.reserve(g_rings.getNumberOfResponseEntries()); - for (const auto& shard : g_rings.d_shards) { - { - auto rl = shard->queryRing.lock(); - for (const auto& entry : *rl) { - qr.push_back(entry); - } + std::vector qr; + std::vector rr; + qr.reserve(g_rings.getNumberOfQueryEntries()); + rr.reserve(g_rings.getNumberOfResponseEntries()); + for (const auto& shard : g_rings.d_shards) { + { + auto rl = shard->queryRing.lock(); + for (const auto& entry : *rl) { + qr.push_back(entry); } - { - auto rl = shard->respRing.lock(); - for (const auto& entry : *rl) { - rr.push_back(entry); - } + } + { + auto rl = shard->respRing.lock(); + for (const auto& entry : *rl) { + rr.push_back(entry); } } + } - sort(qr.begin(), qr.end(), [](const decltype(qr)::value_type& a, const decltype(qr)::value_type& b) { - return b.when < a.when; - }); - - sort(rr.begin(), rr.end(), [](const decltype(rr)::value_type& a, const decltype(rr)::value_type& b) { - return b.when < a.when; - }); + sort(qr.begin(), qr.end(), [](const decltype(qr)::value_type& a, const decltype(qr)::value_type& b) { + return b.when < a.when; + }); - unsigned int num=0; - struct timespec now; - gettime(&now); + sort(rr.begin(), rr.end(), [](const decltype(rr)::value_type& a, const decltype(rr)::value_type& b) { + return b.when < a.when; + }); - std::multimap out; + unsigned int num = 0; + struct timespec now; + gettime(&now); - boost::format fmt("%-7.1f %-47s %-12s %-12s %-5d %-25s %-5s %-6.1f %-2s %-2s %-2s %-s\n"); - const auto headLine = (fmt % "Time" % "Client" % "Protocol" % "Server" % "ID" % "Name" % "Type" % "Lat." % "TC" % "RD" % "AA" % "Rcode").str(); - if (!outputFile) { - g_outputBuffer += headLine; - } - else { - fprintf(outputFile.get(), "%s", headLine.c_str()); - } + std::multimap out; - if (msec == -1) { - for (const auto& c : qr) { - bool nmmatch = true; - bool dnmatch = true; - if (nm) { - nmmatch = nm->match(c.requestor); - } - if (dn) { - if (c.name.empty()) { - dnmatch = false; - } - else { - dnmatch = c.name.isPartOf(*dn); - } - } - if (nmmatch && dnmatch) { - QType qt(c.qtype); - std::string extra; - if (c.dh.opcode != 0) { - extra = " (" + Opcode::to_s(c.dh.opcode) + ")"; - } - out.emplace(c.when, (fmt % DiffTime(now, c.when) % c.requestor.toStringWithPort() % dnsdist::Protocol(c.protocol).toString() % "" % htons(c.dh.id) % c.name.toString() % qt.toString() % "" % (c.dh.tc ? "TC" : "") % (c.dh.rd ? "RD" : "") % (c.dh.aa ? "AA" : "") % ("Question" + extra)).str()); - - if (limit && *limit == ++num) { - break; - } - } - } - } - num = 0; + boost::format fmt("%-7.1f %-47s %-12s %-12s %-5d %-25s %-5s %-6.1f %-2s %-2s %-2s %-s\n"); + const auto headLine = (fmt % "Time" % "Client" % "Protocol" % "Server" % "ID" % "Name" % "Type" % "Lat." % "TC" % "RD" % "AA" % "Rcode").str(); + if (!outputFile) { + g_outputBuffer += headLine; + } + else { + fprintf(outputFile.get(), "%s", headLine.c_str()); + } - string extra; - for (const auto& c : rr) { + if (msec == -1) { + for (const auto& c : qr) { bool nmmatch = true; bool dnmatch = true; - bool msecmatch = true; if (nm) { nmmatch = nm->match(c.requestor); } @@ -552,169 +510,201 @@ void setupLuaInspection(LuaContext& luaCtx) dnmatch = c.name.isPartOf(*dn); } } - if (msec != -1) { - msecmatch = (c.usec/1000 > (unsigned int)msec); - } - - if (nmmatch && dnmatch && msecmatch) { + if (nmmatch && dnmatch) { QType qt(c.qtype); - if (!c.dh.rcode) { - extra = ". " +std::to_string(htons(c.dh.ancount)) + " answers"; - } - else { - extra.clear(); - } - - std::string server = c.ds.toStringWithPort(); - std::string protocol = dnsdist::Protocol(c.protocol).toString(); - if (server == "0.0.0.0:0") { - server = "Cache"; - protocol = "-"; - } - if (c.usec != std::numeric_limits::max()) { - out.emplace(c.when, (fmt % DiffTime(now, c.when) % c.requestor.toStringWithPort() % protocol % server % htons(c.dh.id) % c.name.toString() % qt.toString() % (c.usec / 1000.0) % (c.dh.tc ? "TC" : "") % (c.dh.rd ? "RD" : "") % (c.dh.aa ? "AA" : "") % (RCode::to_s(c.dh.rcode) + extra)).str()); - } - else { - out.emplace(c.when, (fmt % DiffTime(now, c.when) % c.requestor.toStringWithPort() % protocol % server % htons(c.dh.id) % c.name.toString() % qt.toString() % "T.O" % (c.dh.tc ? "TC" : "") % (c.dh.rd ? "RD" : "") % (c.dh.aa ? "AA" : "") % (RCode::to_s(c.dh.rcode) + extra)).str()); + std::string extra; + if (c.dh.opcode != 0) { + extra = " (" + Opcode::to_s(c.dh.opcode) + ")"; } + out.emplace(c.when, (fmt % DiffTime(now, c.when) % c.requestor.toStringWithPort() % dnsdist::Protocol(c.protocol).toString() % "" % htons(c.dh.id) % c.name.toString() % qt.toString() % "" % (c.dh.tc ? "TC" : "") % (c.dh.rd ? "RD" : "") % (c.dh.aa ? "AA" : "") % ("Question" + extra)).str()); if (limit && *limit == ++num) { break; } } } + } + num = 0; - for (const auto& p : out) { - if (!outputFile) { - g_outputBuffer += p.second; + string extra; + for (const auto& c : rr) { + bool nmmatch = true; + bool dnmatch = true; + bool msecmatch = true; + if (nm) { + nmmatch = nm->match(c.requestor); + } + if (dn) { + if (c.name.empty()) { + dnmatch = false; } else { - fprintf(outputFile.get(), "%s", p.second.c_str()); + dnmatch = c.name.isPartOf(*dn); } } - }); - - luaCtx.writeFunction("showResponseLatency", []() { - setLuaNoSideEffect(); - map histo; - double bin=100; - for(int i=0; i < 15; ++i) { - histo[bin]; - bin*=2; + if (msec != -1) { + msecmatch = (c.usec / 1000 > (unsigned int)msec); } - double totlat=0; - unsigned int size=0; - { - for (const auto& shard : g_rings.d_shards) { - auto rl = shard->respRing.lock(); - for(const auto& r : *rl) { - /* skip actively discovered timeouts */ - if (r.usec == std::numeric_limits::max()) - continue; - - ++size; - auto iter = histo.lower_bound(r.usec); - if(iter != histo.end()) - iter->second++; - else - histo.rbegin()++; - totlat+=r.usec; - } + if (nmmatch && dnmatch && msecmatch) { + QType qt(c.qtype); + if (!c.dh.rcode) { + extra = ". " + std::to_string(htons(c.dh.ancount)) + " answers"; + } + else { + extra.clear(); + } + + std::string server = c.ds.toStringWithPort(); + std::string protocol = dnsdist::Protocol(c.protocol).toString(); + if (server == "0.0.0.0:0") { + server = "Cache"; + protocol = "-"; + } + if (c.usec != std::numeric_limits::max()) { + out.emplace(c.when, (fmt % DiffTime(now, c.when) % c.requestor.toStringWithPort() % protocol % server % htons(c.dh.id) % c.name.toString() % qt.toString() % (c.usec / 1000.0) % (c.dh.tc ? "TC" : "") % (c.dh.rd ? "RD" : "") % (c.dh.aa ? "AA" : "") % (RCode::to_s(c.dh.rcode) + extra)).str()); + } + else { + out.emplace(c.when, (fmt % DiffTime(now, c.when) % c.requestor.toStringWithPort() % protocol % server % htons(c.dh.id) % c.name.toString() % qt.toString() % "T.O" % (c.dh.tc ? "TC" : "") % (c.dh.rd ? "RD" : "") % (c.dh.aa ? "AA" : "") % (RCode::to_s(c.dh.rcode) + extra)).str()); + } + + if (limit && *limit == ++num) { + break; } } + } - if (size == 0) { - g_outputBuffer = "No traffic yet.\n"; - return; + for (const auto& p : out) { + if (!outputFile) { + g_outputBuffer += p.second; + } + else { + fprintf(outputFile.get(), "%s", p.second.c_str()); } + } + }); - g_outputBuffer = (boost::format("Average response latency: %.02f ms\n") % (0.001*totlat/size)).str(); - double highest=0; + luaCtx.writeFunction("showResponseLatency", []() { + setLuaNoSideEffect(); + map histo; + double bin = 100; + for (int i = 0; i < 15; ++i) { + histo[bin]; + bin *= 2; + } - for(auto iter = histo.cbegin(); iter != histo.cend(); ++iter) { - highest=std::max(highest, iter->second*1.0); - } - boost::format fmt("%7.2f\t%s\n"); - g_outputBuffer += (fmt % "ms" % "").str(); + double totlat = 0; + unsigned int size = 0; + { + for (const auto& shard : g_rings.d_shards) { + auto rl = shard->respRing.lock(); + for (const auto& r : *rl) { + /* skip actively discovered timeouts */ + if (r.usec == std::numeric_limits::max()) + continue; - for(auto iter = histo.cbegin(); iter != histo.cend(); ++iter) { - int stars = (70.0 * iter->second/highest); - char c='*'; - if(!stars && iter->second) { - stars=1; // you get 1 . to show something is there.. - if(70.0*iter->second/highest > 0.5) - c=':'; - else - c='.'; - } - g_outputBuffer += (fmt % (iter->first/1000.0) % string(stars, c)).str(); + ++size; + auto iter = histo.lower_bound(r.usec); + if (iter != histo.end()) + iter->second++; + else + histo.rbegin()++; + totlat += r.usec; + } } - }); + } - luaCtx.writeFunction("showTCPStats", [] { - setLuaNoSideEffect(); - ostringstream ret; - boost::format fmt("%-12d %-12d %-12d %-12d"); - ret << (fmt % "Workers" % "Max Workers" % "Queued" % "Max Queued") << endl; - ret << (fmt % g_tcpclientthreads->getThreadsCount() % (g_maxTCPClientThreads ? *g_maxTCPClientThreads : 0) % g_tcpclientthreads->getQueuedCount() % g_maxTCPQueuedConnections) << endl; - ret << endl; + if (size == 0) { + g_outputBuffer = "No traffic yet.\n"; + return; + } - ret << "Frontends:" << endl; - fmt = boost::format("%-3d %-20.20s %-20d %-20d %-20d %-25d %-20d %-20d %-20d %-20f %-20f %-20d %-20d %-25d %-25d %-15d %-15d %-15d %-15d %-15d"); - ret << (fmt % "#" % "Address" % "Connections" % "Max concurrent conn" % "Died reading query" % "Died sending response" % "Gave up" % "Client timeouts" % "Downstream timeouts" % "Avg queries/conn" % "Avg duration" % "TLS new sessions" % "TLS Resumptions" % "TLS unknown ticket keys" % "TLS inactive ticket keys" % "TLS 1.0" % "TLS 1.1" % "TLS 1.2" % "TLS 1.3" % "TLS other") << endl; + g_outputBuffer = (boost::format("Average response latency: %.02f ms\n") % (0.001 * totlat / size)).str(); + double highest = 0; - size_t counter = 0; - for(const auto& f : g_frontends) { - ret << (fmt % counter % f->local.toStringWithPort() % f->tcpCurrentConnections % f->tcpMaxConcurrentConnections % f->tcpDiedReadingQuery % f->tcpDiedSendingResponse % f->tcpGaveUp % f->tcpClientTimeouts % f->tcpDownstreamTimeouts % f->tcpAvgQueriesPerConnection % f->tcpAvgConnectionDuration % f->tlsNewSessions % f->tlsResumptions % f->tlsUnknownTicketKey % f->tlsInactiveTicketKey % f->tls10queries % f->tls11queries % f->tls12queries % f->tls13queries % f->tlsUnknownqueries) << endl; - ++counter; - } - ret << endl; + for (auto iter = histo.cbegin(); iter != histo.cend(); ++iter) { + highest = std::max(highest, iter->second * 1.0); + } + boost::format fmt("%7.2f\t%s\n"); + g_outputBuffer += (fmt % "ms" % "").str(); + + for (auto iter = histo.cbegin(); iter != histo.cend(); ++iter) { + int stars = (70.0 * iter->second / highest); + char c = '*'; + if (!stars && iter->second) { + stars = 1; // you get 1 . to show something is there.. + if (70.0 * iter->second / highest > 0.5) + c = ':'; + else + c = '.'; + } + g_outputBuffer += (fmt % (iter->first / 1000.0) % string(stars, c)).str(); + } + }); - ret << "Backends:" << endl; - fmt = boost::format("%-3d %-20.20s %-20.20s %-20d %-20d %-25d %-25d %-20d %-20d %-20d %-20d %-20d %-20d %-20d %-20d %-20f %-20f"); - ret << (fmt % "#" % "Name" % "Address" % "Connections" % "Max concurrent conn" % "Died sending query" % "Died reading response" % "Gave up" % "Read timeouts" % "Write timeouts" % "Connect timeouts" % "Too many conn" % "Total connections" % "Reused connections" % "TLS resumptions" % "Avg queries/conn" % "Avg duration") << endl; + luaCtx.writeFunction("showTCPStats", [] { + setLuaNoSideEffect(); + ostringstream ret; + boost::format fmt("%-12d %-12d %-12d %-12d"); + ret << (fmt % "Workers" % "Max Workers" % "Queued" % "Max Queued") << endl; + ret << (fmt % g_tcpclientthreads->getThreadsCount() % (g_maxTCPClientThreads ? *g_maxTCPClientThreads : 0) % g_tcpclientthreads->getQueuedCount() % g_maxTCPQueuedConnections) << endl; + ret << endl; + + ret << "Frontends:" << endl; + fmt = boost::format("%-3d %-20.20s %-20d %-20d %-20d %-25d %-20d %-20d %-20d %-20f %-20f %-20d %-20d %-25d %-25d %-15d %-15d %-15d %-15d %-15d"); + ret << (fmt % "#" % "Address" % "Connections" % "Max concurrent conn" % "Died reading query" % "Died sending response" % "Gave up" % "Client timeouts" % "Downstream timeouts" % "Avg queries/conn" % "Avg duration" % "TLS new sessions" % "TLS Resumptions" % "TLS unknown ticket keys" % "TLS inactive ticket keys" % "TLS 1.0" % "TLS 1.1" % "TLS 1.2" % "TLS 1.3" % "TLS other") << endl; + + size_t counter = 0; + for (const auto& f : g_frontends) { + ret << (fmt % counter % f->local.toStringWithPort() % f->tcpCurrentConnections % f->tcpMaxConcurrentConnections % f->tcpDiedReadingQuery % f->tcpDiedSendingResponse % f->tcpGaveUp % f->tcpClientTimeouts % f->tcpDownstreamTimeouts % f->tcpAvgQueriesPerConnection % f->tcpAvgConnectionDuration % f->tlsNewSessions % f->tlsResumptions % f->tlsUnknownTicketKey % f->tlsInactiveTicketKey % f->tls10queries % f->tls11queries % f->tls12queries % f->tls13queries % f->tlsUnknownqueries) << endl; + ++counter; + } + ret << endl; - auto states = g_dstates.getLocal(); - counter = 0; - for(const auto& s : *states) { - ret << (fmt % counter % s->getName() % s->d_config.remote.toStringWithPort() % s->tcpCurrentConnections % s->tcpMaxConcurrentConnections % s->tcpDiedSendingQuery % s->tcpDiedReadingResponse % s->tcpGaveUp % s->tcpReadTimeouts % s->tcpWriteTimeouts % s->tcpConnectTimeouts % s->tcpTooManyConcurrentConnections % s->tcpNewConnections % s->tcpReusedConnections % s->tlsResumptions % s->tcpAvgQueriesPerConnection % s->tcpAvgConnectionDuration) << endl; - ++counter; - } + ret << "Backends:" << endl; + fmt = boost::format("%-3d %-20.20s %-20.20s %-20d %-20d %-25d %-25d %-20d %-20d %-20d %-20d %-20d %-20d %-20d %-20d %-20f %-20f"); + ret << (fmt % "#" % "Name" % "Address" % "Connections" % "Max concurrent conn" % "Died sending query" % "Died reading response" % "Gave up" % "Read timeouts" % "Write timeouts" % "Connect timeouts" % "Too many conn" % "Total connections" % "Reused connections" % "TLS resumptions" % "Avg queries/conn" % "Avg duration") << endl; - g_outputBuffer=ret.str(); - }); + auto states = g_dstates.getLocal(); + counter = 0; + for (const auto& s : *states) { + ret << (fmt % counter % s->getName() % s->d_config.remote.toStringWithPort() % s->tcpCurrentConnections % s->tcpMaxConcurrentConnections % s->tcpDiedSendingQuery % s->tcpDiedReadingResponse % s->tcpGaveUp % s->tcpReadTimeouts % s->tcpWriteTimeouts % s->tcpConnectTimeouts % s->tcpTooManyConcurrentConnections % s->tcpNewConnections % s->tcpReusedConnections % s->tlsResumptions % s->tcpAvgQueriesPerConnection % s->tcpAvgConnectionDuration) << endl; + ++counter; + } + + g_outputBuffer = ret.str(); + }); luaCtx.writeFunction("showTLSErrorCounters", [] { - setLuaNoSideEffect(); - ostringstream ret; - boost::format fmt("%-3d %-20.20s %-23d %-23d %-23d %-23d %-23d %-23d %-23d %-23d"); + setLuaNoSideEffect(); + ostringstream ret; + boost::format fmt("%-3d %-20.20s %-23d %-23d %-23d %-23d %-23d %-23d %-23d %-23d"); - ret << (fmt % "#" % "Address" % "DH key too small" % "Inappropriate fallback" % "No shared cipher" % "Unknown cipher type" % "Unknown exchange type" % "Unknown protocol" % "Unsupported EC" % "Unsupported protocol") << endl; + ret << (fmt % "#" % "Address" % "DH key too small" % "Inappropriate fallback" % "No shared cipher" % "Unknown cipher type" % "Unknown exchange type" % "Unknown protocol" % "Unsupported EC" % "Unsupported protocol") << endl; - size_t counter = 0; - for(const auto& f : g_frontends) { - if (!f->hasTLS()) { - continue; - } - const TLSErrorCounters* errorCounters = nullptr; - if (f->tlsFrontend != nullptr) { - errorCounters = &f->tlsFrontend->d_tlsCounters; - } - else if (f->dohFrontend != nullptr) { - errorCounters = &f->dohFrontend->d_tlsContext.d_tlsCounters; - } - if (errorCounters == nullptr) { - continue; - } - - ret << (fmt % counter % f->local.toStringWithPort() % errorCounters->d_dhKeyTooSmall % errorCounters->d_inappropriateFallBack % errorCounters->d_noSharedCipher % errorCounters->d_unknownCipherType % errorCounters->d_unknownKeyExchangeType % errorCounters->d_unknownProtocol % errorCounters->d_unsupportedEC % errorCounters->d_unsupportedProtocol) << endl; - ++counter; + size_t counter = 0; + for (const auto& f : g_frontends) { + if (!f->hasTLS()) { + continue; + } + const TLSErrorCounters* errorCounters = nullptr; + if (f->tlsFrontend != nullptr) { + errorCounters = &f->tlsFrontend->d_tlsCounters; + } + else if (f->dohFrontend != nullptr) { + errorCounters = &f->dohFrontend->d_tlsContext.d_tlsCounters; + } + if (errorCounters == nullptr) { + continue; } - ret << endl; - g_outputBuffer=ret.str(); - }); + ret << (fmt % counter % f->local.toStringWithPort() % errorCounters->d_dhKeyTooSmall % errorCounters->d_inappropriateFallBack % errorCounters->d_noSharedCipher % errorCounters->d_unknownCipherType % errorCounters->d_unknownKeyExchangeType % errorCounters->d_unknownProtocol % errorCounters->d_unsupportedEC % errorCounters->d_unsupportedProtocol) << endl; + ++counter; + } + ret << endl; + + g_outputBuffer = ret.str(); + }); luaCtx.writeFunction("requestTCPStatesDump", [] { setLuaNoSideEffect(); @@ -730,95 +720,95 @@ void setupLuaInspection(LuaContext& luaCtx) }); luaCtx.writeFunction("dumpStats", [] { - setLuaNoSideEffect(); - vector leftcolumn, rightcolumn; - - boost::format fmt("%-35s\t%+11s"); - g_outputBuffer.clear(); - auto entries = *dnsdist::metrics::g_stats.entries.read_lock(); - sort(entries.begin(), entries.end(), - [](const decltype(entries)::value_type& a, const decltype(entries)::value_type& b) { - return a.d_name < b.d_name; - }); - boost::format flt(" %9.1f"); - for (const auto& entry : entries) { - string second; - if (const auto& val = std::get_if(&entry.d_value)) { - second = std::to_string((*val)->load()); - } - else if (const auto& adval = std::get_if*>(&entry.d_value)) { - second = (flt % (*adval)->load()).str(); - } - else if (const auto& dval = std::get_if(&entry.d_value)) { - second = (flt % (**dval)).str(); - } - else if (const auto& func = std::get_if(&entry.d_value)) { - second = std::to_string((*func)(entry.d_name)); - } + setLuaNoSideEffect(); + vector leftcolumn, rightcolumn; - if (leftcolumn.size() < entries.size() / 2) { - leftcolumn.push_back((fmt % entry.d_name % second).str()); - } - else { - rightcolumn.push_back((fmt % entry.d_name % second).str()); - } + boost::format fmt("%-35s\t%+11s"); + g_outputBuffer.clear(); + auto entries = *dnsdist::metrics::g_stats.entries.read_lock(); + sort(entries.begin(), entries.end(), + [](const decltype(entries)::value_type& a, const decltype(entries)::value_type& b) { + return a.d_name < b.d_name; + }); + boost::format flt(" %9.1f"); + for (const auto& entry : entries) { + string second; + if (const auto& val = std::get_if(&entry.d_value)) { + second = std::to_string((*val)->load()); + } + else if (const auto& adval = std::get_if*>(&entry.d_value)) { + second = (flt % (*adval)->load()).str(); + } + else if (const auto& dval = std::get_if(&entry.d_value)) { + second = (flt % (**dval)).str(); + } + else if (const auto& func = std::get_if(&entry.d_value)) { + second = std::to_string((*func)(entry.d_name)); + } + + if (leftcolumn.size() < entries.size() / 2) { + leftcolumn.push_back((fmt % entry.d_name % second).str()); + } + else { + rightcolumn.push_back((fmt % entry.d_name % second).str()); } + } - auto leftiter=leftcolumn.begin(), rightiter=rightcolumn.begin(); - boost::format clmn("%|0t|%1% %|51t|%2%\n"); + auto leftiter = leftcolumn.begin(), rightiter = rightcolumn.begin(); + boost::format clmn("%|0t|%1% %|51t|%2%\n"); - for(;leftiter != leftcolumn.end() || rightiter != rightcolumn.end();) { - string lentry, rentry; - if(leftiter!= leftcolumn.end()) { - lentry = *leftiter; - leftiter++; - } - if(rightiter!= rightcolumn.end()) { - rentry = *rightiter; - rightiter++; - } - g_outputBuffer += (clmn % lentry % rentry).str(); + for (; leftiter != leftcolumn.end() || rightiter != rightcolumn.end();) { + string lentry, rentry; + if (leftiter != leftcolumn.end()) { + lentry = *leftiter; + leftiter++; } - }); + if (rightiter != rightcolumn.end()) { + rentry = *rightiter; + rightiter++; + } + g_outputBuffer += (clmn % lentry % rentry).str(); + } + }); #ifndef DISABLE_DYNBLOCKS #ifndef DISABLE_DEPRECATED_DYNBLOCK luaCtx.writeFunction("exceedServFails", [](unsigned int rate, int seconds) { - setLuaNoSideEffect(); - return exceedRCode(rate, seconds, RCode::ServFail); - }); + setLuaNoSideEffect(); + return exceedRCode(rate, seconds, RCode::ServFail); + }); luaCtx.writeFunction("exceedNXDOMAINs", [](unsigned int rate, int seconds) { - setLuaNoSideEffect(); - return exceedRCode(rate, seconds, RCode::NXDomain); - }); + setLuaNoSideEffect(); + return exceedRCode(rate, seconds, RCode::NXDomain); + }); luaCtx.writeFunction("exceedRespByterate", [](unsigned int rate, int seconds) { - setLuaNoSideEffect(); - return exceedRespByterate(rate, seconds); - }); + setLuaNoSideEffect(); + return exceedRespByterate(rate, seconds); + }); luaCtx.writeFunction("exceedQTypeRate", [](uint16_t type, unsigned int rate, int seconds) { - setLuaNoSideEffect(); - return exceedQueryGen(rate, seconds, [type](counts_t& counts, const Rings::Query& q) { - if(q.qtype==type) - counts[q.requestor]++; - }); + setLuaNoSideEffect(); + return exceedQueryGen(rate, seconds, [type](counts_t& counts, const Rings::Query& q) { + if (q.qtype == type) + counts[q.requestor]++; }); + }); luaCtx.writeFunction("exceedQRate", [](unsigned int rate, int seconds) { - setLuaNoSideEffect(); - return exceedQueryGen(rate, seconds, [](counts_t& counts, const Rings::Query& q) { - counts[q.requestor]++; - }); + setLuaNoSideEffect(); + return exceedQueryGen(rate, seconds, [](counts_t& counts, const Rings::Query& q) { + counts[q.requestor]++; }); + }); luaCtx.writeFunction("getRespRing", getRespRing); /* StatNode */ - luaCtx.registerFunction("numChildren", - [](const StatNode& sn) -> unsigned int { - return sn.children.size(); - } ); + luaCtx.registerFunction("numChildren", + [](const StatNode& sn) -> unsigned int { + return sn.children.size(); + }); luaCtx.registerMember("fullname", &StatNode::fullname); luaCtx.registerMember("labelsCount", &StatNode::labelsCount); luaCtx.registerMember("servfails", &StatNode::Stat::servfails); @@ -830,124 +820,124 @@ void setupLuaInspection(LuaContext& luaCtx) luaCtx.registerMember("hits", &StatNode::Stat::hits); luaCtx.writeFunction("statNodeRespRing", [](statvisitor_t visitor, boost::optional seconds) { - statNodeRespRing(std::move(visitor), seconds ? *seconds : 0U); - }); + statNodeRespRing(std::move(visitor), seconds ? *seconds : 0U); + }); #endif /* DISABLE_DEPRECATED_DYNBLOCK */ /* DynBlockRulesGroup */ luaCtx.writeFunction("dynBlockRulesGroup", []() { return std::make_shared(); }); - luaCtx.registerFunction::*)(unsigned int, unsigned int, const std::string&, unsigned int, boost::optional, boost::optional)>("setQueryRate", [](std::shared_ptr& group, unsigned int rate, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, boost::optional warningRate) { - if (group) { - group->setQueryRate(rate, warningRate ? *warningRate : 0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None); - } - }); - luaCtx.registerFunction::*)(unsigned int, unsigned int, const std::string&, unsigned int, boost::optional, boost::optional)>("setResponseByteRate", [](std::shared_ptr& group, unsigned int rate, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, boost::optional warningRate) { - if (group) { - group->setResponseByteRate(rate, warningRate ? *warningRate : 0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None); - } - }); - luaCtx.registerFunction::*)(unsigned int, const std::string&, unsigned int, boost::optional, DynBlockRulesGroup::smtVisitor_t)>("setSuffixMatchRule", [](std::shared_ptr& group, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, DynBlockRulesGroup::smtVisitor_t visitor) { - if (group) { - group->setSuffixMatchRule(seconds, reason, blockDuration, action ? *action : DNSAction::Action::None, std::move(visitor)); - } - }); - luaCtx.registerFunction::*)(unsigned int, const std::string&, unsigned int, boost::optional, dnsdist_ffi_stat_node_visitor_t)>("setSuffixMatchRuleFFI", [](std::shared_ptr& group, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, dnsdist_ffi_stat_node_visitor_t visitor) { - if (group) { - group->setSuffixMatchRuleFFI(seconds, reason, blockDuration, action ? *action : DNSAction::Action::None, std::move(visitor)); - } - }); - luaCtx.registerFunction::*)(const dnsdist_ffi_dynamic_block_inserted_hook&)>("setNewBlockInsertedHook", [](std::shared_ptr& group, const dnsdist_ffi_dynamic_block_inserted_hook& hook) { - if (group) { - group->setNewBlockHook(hook); - } - }); - luaCtx.registerFunction::*)(uint8_t, unsigned int, unsigned int, const std::string&, unsigned int, boost::optional, boost::optional)>("setRCodeRate", [](std::shared_ptr& group, uint8_t rcode, unsigned int rate, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, boost::optional warningRate) { - if (group) { - group->setRCodeRate(rcode, rate, warningRate ? *warningRate : 0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None); - } - }); - luaCtx.registerFunction::*)(uint8_t, double, unsigned int, const std::string&, unsigned int, size_t, boost::optional, boost::optional)>("setRCodeRatio", [](std::shared_ptr& group, uint8_t rcode, double ratio, unsigned int seconds, const std::string& reason, unsigned int blockDuration, size_t minimumNumberOfResponses, boost::optional action, boost::optional warningRatio) { - if (group) { - group->setRCodeRatio(rcode, ratio, warningRatio ? *warningRatio : 0.0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None, minimumNumberOfResponses); - } - }); - luaCtx.registerFunction::*)(uint16_t, unsigned int, unsigned int, const std::string&, unsigned int, boost::optional, boost::optional)>("setQTypeRate", [](std::shared_ptr& group, uint16_t qtype, unsigned int rate, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, boost::optional warningRate) { - if (group) { - group->setQTypeRate(qtype, rate, warningRate ? *warningRate : 0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None); - } - }); - luaCtx.registerFunction::*)(double, unsigned int, const std::string&, unsigned int, size_t, double, boost::optional, boost::optional)>("setCacheMissRatio", [](std::shared_ptr& group, double ratio, unsigned int seconds, const std::string& reason, unsigned int blockDuration, size_t minimumNumberOfResponses, double minimumGlobalCacheHitRatio, boost::optional action, boost::optional warningRatio) { - if (group) { - group->setCacheMissRatio(ratio, warningRatio ? *warningRatio : 0.0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None, minimumNumberOfResponses, minimumGlobalCacheHitRatio); - } - }); - luaCtx.registerFunction::*)(uint8_t, uint8_t, uint8_t)>("setMasks", [](std::shared_ptr& group, uint8_t v4, uint8_t v6, uint8_t port) { - if (group) { - if (v4 > 32) { - throw std::runtime_error("Trying to set an invalid IPv4 mask (" + std::to_string(v4) + ") to a Dynamic Block object"); - } - if (v6 > 128) { - throw std::runtime_error("Trying to set an invalid IPv6 mask (" + std::to_string(v6) + ") to a Dynamic Block object"); - } - if (port > 16) { - throw std::runtime_error("Trying to set an invalid port mask (" + std::to_string(port) + ") to a Dynamic Block object"); - } - if (port > 0 && v4 != 32) { - throw std::runtime_error("Setting a non-zero port mask for Dynamic Blocks while only considering parts of IPv4 addresses does not make sense"); - } - group->setMasks(v4, v6, port); - } - }); - luaCtx.registerFunction::*)(boost::variant, NetmaskGroup>)>("excludeRange", [](std::shared_ptr& group, boost::variant, NetmaskGroup> ranges) { - if (ranges.type() == typeid(LuaArray)) { - for (const auto& range : *boost::get>(&ranges)) { - group->excludeRange(Netmask(range.second)); - } - } - else if (ranges.type() == typeid(NetmaskGroup)) { - group->excludeRange(*boost::get(&ranges)); - } - else { - group->excludeRange(Netmask(*boost::get(&ranges))); - } - }); - luaCtx.registerFunction::*)(boost::variant, NetmaskGroup>)>("includeRange", [](std::shared_ptr& group, boost::variant, NetmaskGroup> ranges) { - if (ranges.type() == typeid(LuaArray)) { - for (const auto& range : *boost::get>(&ranges)) { - group->includeRange(Netmask(range.second)); - } + luaCtx.registerFunction::*)(unsigned int, unsigned int, const std::string&, unsigned int, boost::optional, boost::optional)>("setQueryRate", [](std::shared_ptr& group, unsigned int rate, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, boost::optional warningRate) { + if (group) { + group->setQueryRate(rate, warningRate ? *warningRate : 0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None); + } + }); + luaCtx.registerFunction::*)(unsigned int, unsigned int, const std::string&, unsigned int, boost::optional, boost::optional)>("setResponseByteRate", [](std::shared_ptr& group, unsigned int rate, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, boost::optional warningRate) { + if (group) { + group->setResponseByteRate(rate, warningRate ? *warningRate : 0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None); + } + }); + luaCtx.registerFunction::*)(unsigned int, const std::string&, unsigned int, boost::optional, DynBlockRulesGroup::smtVisitor_t)>("setSuffixMatchRule", [](std::shared_ptr& group, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, DynBlockRulesGroup::smtVisitor_t visitor) { + if (group) { + group->setSuffixMatchRule(seconds, reason, blockDuration, action ? *action : DNSAction::Action::None, std::move(visitor)); + } + }); + luaCtx.registerFunction::*)(unsigned int, const std::string&, unsigned int, boost::optional, dnsdist_ffi_stat_node_visitor_t)>("setSuffixMatchRuleFFI", [](std::shared_ptr& group, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, dnsdist_ffi_stat_node_visitor_t visitor) { + if (group) { + group->setSuffixMatchRuleFFI(seconds, reason, blockDuration, action ? *action : DNSAction::Action::None, std::move(visitor)); + } + }); + luaCtx.registerFunction::*)(const dnsdist_ffi_dynamic_block_inserted_hook&)>("setNewBlockInsertedHook", [](std::shared_ptr& group, const dnsdist_ffi_dynamic_block_inserted_hook& hook) { + if (group) { + group->setNewBlockHook(hook); + } + }); + luaCtx.registerFunction::*)(uint8_t, unsigned int, unsigned int, const std::string&, unsigned int, boost::optional, boost::optional)>("setRCodeRate", [](std::shared_ptr& group, uint8_t rcode, unsigned int rate, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, boost::optional warningRate) { + if (group) { + group->setRCodeRate(rcode, rate, warningRate ? *warningRate : 0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None); + } + }); + luaCtx.registerFunction::*)(uint8_t, double, unsigned int, const std::string&, unsigned int, size_t, boost::optional, boost::optional)>("setRCodeRatio", [](std::shared_ptr& group, uint8_t rcode, double ratio, unsigned int seconds, const std::string& reason, unsigned int blockDuration, size_t minimumNumberOfResponses, boost::optional action, boost::optional warningRatio) { + if (group) { + group->setRCodeRatio(rcode, ratio, warningRatio ? *warningRatio : 0.0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None, minimumNumberOfResponses); + } + }); + luaCtx.registerFunction::*)(uint16_t, unsigned int, unsigned int, const std::string&, unsigned int, boost::optional, boost::optional)>("setQTypeRate", [](std::shared_ptr& group, uint16_t qtype, unsigned int rate, unsigned int seconds, const std::string& reason, unsigned int blockDuration, boost::optional action, boost::optional warningRate) { + if (group) { + group->setQTypeRate(qtype, rate, warningRate ? *warningRate : 0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None); + } + }); + luaCtx.registerFunction::*)(double, unsigned int, const std::string&, unsigned int, size_t, double, boost::optional, boost::optional)>("setCacheMissRatio", [](std::shared_ptr& group, double ratio, unsigned int seconds, const std::string& reason, unsigned int blockDuration, size_t minimumNumberOfResponses, double minimumGlobalCacheHitRatio, boost::optional action, boost::optional warningRatio) { + if (group) { + group->setCacheMissRatio(ratio, warningRatio ? *warningRatio : 0.0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None, minimumNumberOfResponses, minimumGlobalCacheHitRatio); + } + }); + luaCtx.registerFunction::*)(uint8_t, uint8_t, uint8_t)>("setMasks", [](std::shared_ptr& group, uint8_t v4, uint8_t v6, uint8_t port) { + if (group) { + if (v4 > 32) { + throw std::runtime_error("Trying to set an invalid IPv4 mask (" + std::to_string(v4) + ") to a Dynamic Block object"); } - else if (ranges.type() == typeid(NetmaskGroup)) { - group->includeRange(*boost::get(&ranges)); + if (v6 > 128) { + throw std::runtime_error("Trying to set an invalid IPv6 mask (" + std::to_string(v6) + ") to a Dynamic Block object"); } - else { - group->includeRange(Netmask(*boost::get(&ranges))); + if (port > 16) { + throw std::runtime_error("Trying to set an invalid port mask (" + std::to_string(port) + ") to a Dynamic Block object"); } - }); - luaCtx.registerFunction::*)(boost::variant, NetmaskGroup>)>("removeRange", [](std::shared_ptr& group, boost::variant, NetmaskGroup> ranges) { - if (ranges.type() == typeid(LuaArray)) { - for (const auto& range : *boost::get>(&ranges)) { - group->removeRange(Netmask(range.second)); - } + if (port > 0 && v4 != 32) { + throw std::runtime_error("Setting a non-zero port mask for Dynamic Blocks while only considering parts of IPv4 addresses does not make sense"); } - else if (ranges.type() == typeid(NetmaskGroup)) { - group->removeRange(*boost::get(&ranges)); + group->setMasks(v4, v6, port); + } + }); + luaCtx.registerFunction::*)(boost::variant, NetmaskGroup>)>("excludeRange", [](std::shared_ptr& group, boost::variant, NetmaskGroup> ranges) { + if (ranges.type() == typeid(LuaArray)) { + for (const auto& range : *boost::get>(&ranges)) { + group->excludeRange(Netmask(range.second)); } - else { - group->removeRange(Netmask(*boost::get(&ranges))); + } + else if (ranges.type() == typeid(NetmaskGroup)) { + group->excludeRange(*boost::get(&ranges)); + } + else { + group->excludeRange(Netmask(*boost::get(&ranges))); + } + }); + luaCtx.registerFunction::*)(boost::variant, NetmaskGroup>)>("includeRange", [](std::shared_ptr& group, boost::variant, NetmaskGroup> ranges) { + if (ranges.type() == typeid(LuaArray)) { + for (const auto& range : *boost::get>(&ranges)) { + group->includeRange(Netmask(range.second)); } - }); - luaCtx.registerFunction::*)(LuaTypeOrArrayOf)>("excludeDomains", [](std::shared_ptr& group, LuaTypeOrArrayOf domains) { - if (domains.type() == typeid(LuaArray)) { - for (const auto& range : *boost::get>(&domains)) { - group->excludeDomain(DNSName(range.second)); - } + } + else if (ranges.type() == typeid(NetmaskGroup)) { + group->includeRange(*boost::get(&ranges)); + } + else { + group->includeRange(Netmask(*boost::get(&ranges))); + } + }); + luaCtx.registerFunction::*)(boost::variant, NetmaskGroup>)>("removeRange", [](std::shared_ptr& group, boost::variant, NetmaskGroup> ranges) { + if (ranges.type() == typeid(LuaArray)) { + for (const auto& range : *boost::get>(&ranges)) { + group->removeRange(Netmask(range.second)); } - else { - group->excludeDomain(DNSName(*boost::get(&domains))); + } + else if (ranges.type() == typeid(NetmaskGroup)) { + group->removeRange(*boost::get(&ranges)); + } + else { + group->removeRange(Netmask(*boost::get(&ranges))); + } + }); + luaCtx.registerFunction::*)(LuaTypeOrArrayOf)>("excludeDomains", [](std::shared_ptr& group, LuaTypeOrArrayOf domains) { + if (domains.type() == typeid(LuaArray)) { + for (const auto& range : *boost::get>(&domains)) { + group->excludeDomain(DNSName(range.second)); } - }); - luaCtx.registerFunction::*)()>("apply", [](std::shared_ptr& group) { + } + else { + group->excludeDomain(DNSName(*boost::get(&domains))); + } + }); + luaCtx.registerFunction::*)()>("apply", [](std::shared_ptr& group) { group->apply(); }); luaCtx.registerFunction("setQuiet", &DynBlockRulesGroup::setQuiet); @@ -957,7 +947,8 @@ void setupLuaInspection(LuaContext& luaCtx) luaCtx.registerMember("reason", &DynBlock::reason); luaCtx.registerMember("domain", &DynBlock::domain); luaCtx.registerMember("until", &DynBlock::until); - luaCtx.registerMember("blocks", [](const DynBlock& block) { return block.blocks.load(); }, [](DynBlock& block, [[maybe_unused]] unsigned int blocks) { }); + luaCtx.registerMember( + "blocks", [](const DynBlock& block) { return block.blocks.load(); }, [](DynBlock& block, [[maybe_unused]] unsigned int blocks) {}); luaCtx.registerMember("action", &DynBlock::action); luaCtx.registerMember("warning", &DynBlock::warning); luaCtx.registerMember("bpf", &DynBlock::bpf); diff --git a/pdns/dnsdistdist/dnsdist-lua-rules.cc b/pdns/dnsdistdist/dnsdist-lua-rules.cc index f53b98be3932..d58bedba765f 100644 --- a/pdns/dnsdistdist/dnsdist-lua-rules.cc +++ b/pdns/dnsdistdist/dnsdist-lua-rules.cc @@ -36,7 +36,8 @@ std::shared_ptr makeRule(const luadnsrule_t& var, const std::string& ca auto add = [&nmg, &smn, &suffixSeen](const string& src) { try { nmg.addMask(src); // need to try mask first, all masks are domain names! - } catch (...) { + } + catch (...) { suffixSeen = true; smn.add(DNSName(src)); } @@ -91,9 +92,9 @@ void parseRuleParams(boost::optional& params, boost::uuids::uui creationOrder = s_creationOrder++; } -typedef LuaAssociativeTable > > ruleparams_t; +typedef LuaAssociativeTable>> ruleparams_t; -template +template static std::string rulesToString(const std::vector& rules, boost::optional& vars) { int num = 0; @@ -108,7 +109,7 @@ static std::string rulesToString(const std::vector& rules, boost::optionaltoString().substr(0, truncateRuleWidth); result += (fmt % num % lim.d_name % boost::uuids::to_string(lim.d_id) % lim.d_creationOrder % lim.d_rule->d_matches % desc % lim.d_action->toString()).str(); ++num; @@ -117,25 +118,27 @@ static std::string rulesToString(const std::vector& rules, boost::optionaltoString().substr(0, truncateRuleWidth); - result += (fmt % num % lim.d_name % lim.d_rule->d_matches % desc % lim.d_action->toString()).str(); + result += (fmt % num % lim.d_name % lim.d_rule->d_matches % desc % lim.d_action->toString()).str(); ++num; } } return result; } -template -static void showRules(GlobalStateHolder > *someRuleActions, boost::optional& vars) { +template +static void showRules(GlobalStateHolder>* someRuleActions, boost::optional& vars) +{ setLuaNoSideEffect(); auto rules = someRuleActions->getLocal(); g_outputBuffer += rulesToString(*rules, vars); } -template -static void rmRule(GlobalStateHolder > *someRuleActions, const boost::variant& id) { +template +static void rmRule(GlobalStateHolder>* someRuleActions, const boost::variant& id) +{ setLuaSideEffect(); auto rules = someRuleActions->getCopy(); if (auto str = boost::get(&id)) { @@ -169,16 +172,17 @@ static void rmRule(GlobalStateHolder > *someRuleActions, const boost:: g_outputBuffer = "Error: attempt to delete non-existing rule\n"; return; } - rules.erase(rules.begin()+*pos); + rules.erase(rules.begin() + *pos); } someRuleActions->setState(std::move(rules)); } -template -static void moveRuleToTop(GlobalStateHolder > *someRuleActions) { +template +static void moveRuleToTop(GlobalStateHolder>* someRuleActions) +{ setLuaSideEffect(); auto rules = someRuleActions->getCopy(); - if(rules.empty()) + if (rules.empty()) return; auto subject = *rules.rbegin(); rules.erase(std::prev(rules.end())); @@ -186,27 +190,28 @@ static void moveRuleToTop(GlobalStateHolder > *someRuleActions) { someRuleActions->setState(std::move(rules)); } -template -static void mvRule(GlobalStateHolder > *someRespRuleActions, unsigned int from, unsigned int to) { +template +static void mvRule(GlobalStateHolder>* someRespRuleActions, unsigned int from, unsigned int to) +{ setLuaSideEffect(); auto rules = someRespRuleActions->getCopy(); - if(from >= rules.size() || to > rules.size()) { + if (from >= rules.size() || to > rules.size()) { g_outputBuffer = "Error: attempt to move rules from/to invalid index\n"; return; } auto subject = rules[from]; - rules.erase(rules.begin()+from); - if(to > rules.size()) + rules.erase(rules.begin() + from); + if (to > rules.size()) rules.push_back(subject); else { - if(from < to) + if (from < to) --to; - rules.insert(rules.begin()+to, subject); + rules.insert(rules.begin() + to, subject); } someRespRuleActions->setState(std::move(rules)); } -template +template static std::vector getTopRules(const std::vector& rules, unsigned int top) { std::vector> counts; @@ -218,8 +223,7 @@ static std::vector getTopRules(const std::vector& rules, unsigned int top) pos++; } - sort(counts.begin(), counts.end(), [](const decltype(counts)::value_type& a, - const decltype(counts)::value_type& b) { + sort(counts.begin(), counts.end(), [](const decltype(counts)::value_type& a, const decltype(counts)::value_type& b) { return b.first < a.first; }); @@ -238,7 +242,7 @@ static std::vector getTopRules(const std::vector& rules, unsigned int top) return results; } -template +template static LuaArray toLuaArray(std::vector&& rules) { LuaArray results; @@ -313,49 +317,49 @@ void setupLuaRules(LuaContext& luaCtx) return makeRule(var, "makeRule"); }); - luaCtx.registerFunction::*)()const>("toString", [](const std::shared_ptr& rule) { return rule->toString(); }); + luaCtx.registerFunction::*)() const>("toString", [](const std::shared_ptr& rule) { return rule->toString(); }); - luaCtx.registerFunction::*)()const>("getMatches", [](const std::shared_ptr& rule) { return rule->d_matches.load(); }); + luaCtx.registerFunction::*)() const>("getMatches", [](const std::shared_ptr& rule) { return rule->d_matches.load(); }); - luaCtx.registerFunction(DNSDistRuleAction::*)()const>("getSelector", [](const DNSDistRuleAction& rule) { return rule.d_rule; }); + luaCtx.registerFunction (DNSDistRuleAction::*)() const>("getSelector", [](const DNSDistRuleAction& rule) { return rule.d_rule; }); - luaCtx.registerFunction(DNSDistRuleAction::*)()const>("getAction", [](const DNSDistRuleAction& rule) { return rule.d_action; }); + luaCtx.registerFunction (DNSDistRuleAction::*)() const>("getAction", [](const DNSDistRuleAction& rule) { return rule.d_action; }); - luaCtx.registerFunction(DNSDistResponseRuleAction::*)()const>("getSelector", [](const DNSDistResponseRuleAction& rule) { return rule.d_rule; }); + luaCtx.registerFunction (DNSDistResponseRuleAction::*)() const>("getSelector", [](const DNSDistResponseRuleAction& rule) { return rule.d_rule; }); - luaCtx.registerFunction(DNSDistResponseRuleAction::*)()const>("getAction", [](const DNSDistResponseRuleAction& rule) { return rule.d_action; }); + luaCtx.registerFunction (DNSDistResponseRuleAction::*)() const>("getAction", [](const DNSDistResponseRuleAction& rule) { return rule.d_action; }); luaCtx.writeFunction("showResponseRules", [](boost::optional vars) { - showRules(&g_respruleactions, vars); - }); + showRules(&g_respruleactions, vars); + }); luaCtx.writeFunction("rmResponseRule", [](boost::variant id) { - rmRule(&g_respruleactions, id); - }); + rmRule(&g_respruleactions, id); + }); luaCtx.writeFunction("mvResponseRuleToTop", []() { - moveRuleToTop(&g_respruleactions); - }); + moveRuleToTop(&g_respruleactions); + }); luaCtx.writeFunction("mvResponseRule", [](unsigned int from, unsigned int to) { - mvRule(&g_respruleactions, from, to); - }); + mvRule(&g_respruleactions, from, to); + }); luaCtx.writeFunction("showCacheHitResponseRules", [](boost::optional vars) { - showRules(&g_cachehitrespruleactions, vars); - }); + showRules(&g_cachehitrespruleactions, vars); + }); luaCtx.writeFunction("rmCacheHitResponseRule", [](boost::variant id) { - rmRule(&g_cachehitrespruleactions, id); - }); + rmRule(&g_cachehitrespruleactions, id); + }); luaCtx.writeFunction("mvCacheHitResponseRuleToTop", []() { - moveRuleToTop(&g_cachehitrespruleactions); - }); + moveRuleToTop(&g_cachehitrespruleactions); + }); luaCtx.writeFunction("mvCacheHitResponseRule", [](unsigned int from, unsigned int to) { - mvRule(&g_cachehitrespruleactions, from, to); - }); + mvRule(&g_cachehitrespruleactions, from, to); + }); luaCtx.writeFunction("showCacheInsertedResponseRules", [](boost::optional vars) { showRules(&g_cacheInsertedRespRuleActions, vars); @@ -374,53 +378,53 @@ void setupLuaRules(LuaContext& luaCtx) }); luaCtx.writeFunction("showSelfAnsweredResponseRules", [](boost::optional vars) { - showRules(&g_selfansweredrespruleactions, vars); - }); + showRules(&g_selfansweredrespruleactions, vars); + }); luaCtx.writeFunction("rmSelfAnsweredResponseRule", [](boost::variant id) { - rmRule(&g_selfansweredrespruleactions, id); - }); + rmRule(&g_selfansweredrespruleactions, id); + }); luaCtx.writeFunction("mvSelfAnsweredResponseRuleToTop", []() { - moveRuleToTop(&g_selfansweredrespruleactions); - }); + moveRuleToTop(&g_selfansweredrespruleactions); + }); luaCtx.writeFunction("mvSelfAnsweredResponseRule", [](unsigned int from, unsigned int to) { - mvRule(&g_selfansweredrespruleactions, from, to); - }); + mvRule(&g_selfansweredrespruleactions, from, to); + }); luaCtx.writeFunction("rmRule", [](boost::variant id) { - rmRule(&g_ruleactions, id); - }); + rmRule(&g_ruleactions, id); + }); luaCtx.writeFunction("mvRuleToTop", []() { - moveRuleToTop(&g_ruleactions); - }); + moveRuleToTop(&g_ruleactions); + }); luaCtx.writeFunction("mvRule", [](unsigned int from, unsigned int to) { - mvRule(&g_ruleactions, from, to); - }); + mvRule(&g_ruleactions, from, to); + }); luaCtx.writeFunction("clearRules", []() { - setLuaSideEffect(); - g_ruleactions.modify([](decltype(g_ruleactions)::value_type& ruleactions) { - ruleactions.clear(); - }); + setLuaSideEffect(); + g_ruleactions.modify([](decltype(g_ruleactions)::value_type& ruleactions) { + ruleactions.clear(); }); + }); luaCtx.writeFunction("setRules", [](const LuaArray>& newruleactions) { - setLuaSideEffect(); - g_ruleactions.modify([newruleactions](decltype(g_ruleactions)::value_type& gruleactions) { - gruleactions.clear(); - for (const auto& pair : newruleactions) { - const auto& newruleaction = pair.second; - if (newruleaction->d_action) { - auto rule = newruleaction->d_rule; - gruleactions.push_back({std::move(rule), newruleaction->d_action, newruleaction->d_name, newruleaction->d_id, newruleaction->d_creationOrder}); - } - } - }); + setLuaSideEffect(); + g_ruleactions.modify([newruleactions](decltype(g_ruleactions)::value_type& gruleactions) { + gruleactions.clear(); + for (const auto& pair : newruleactions) { + const auto& newruleaction = pair.second; + if (newruleaction->d_action) { + auto rule = newruleaction->d_rule; + gruleactions.push_back({std::move(rule), newruleaction->d_action, newruleaction->d_name, newruleaction->d_id, newruleaction->d_creationOrder}); + } + } }); + }); luaCtx.writeFunction("getRule", [](boost::variant selector) -> boost::optional { auto rules = g_ruleactions.getLocal(); @@ -509,39 +513,39 @@ void setupLuaRules(LuaContext& luaCtx) luaCtx.writeFunction("MaxQPSIPRule", [](unsigned int qps, boost::optional ipv4trunc, boost::optional ipv6trunc, boost::optional burst, boost::optional expiration, boost::optional cleanupDelay, boost::optional scanFraction, boost::optional shards) { return std::shared_ptr(new MaxQPSIPRule(qps, (burst ? *burst : qps), (ipv4trunc ? *ipv4trunc : 32), (ipv6trunc ? *ipv6trunc : 64), (expiration ? *expiration : 300), (cleanupDelay ? *cleanupDelay : 60), (scanFraction ? *scanFraction : 10), (shards ? *shards : 10))); - }); + }); luaCtx.writeFunction("MaxQPSRule", [](unsigned int qps, boost::optional burst) { - if(!burst) - return std::shared_ptr(new MaxQPSRule(qps)); - else - return std::shared_ptr(new MaxQPSRule(qps, *burst)); - }); + if (!burst) + return std::shared_ptr(new MaxQPSRule(qps)); + else + return std::shared_ptr(new MaxQPSRule(qps, *burst)); + }); luaCtx.writeFunction("RegexRule", [](const std::string& str) { - return std::shared_ptr(new RegexRule(str)); - }); + return std::shared_ptr(new RegexRule(str)); + }); #ifdef HAVE_DNS_OVER_HTTPS luaCtx.writeFunction("HTTPHeaderRule", [](const std::string& header, const std::string& regex) { - return std::shared_ptr(new HTTPHeaderRule(header, regex)); - }); + return std::shared_ptr(new HTTPHeaderRule(header, regex)); + }); luaCtx.writeFunction("HTTPPathRule", [](const std::string& path) { - return std::shared_ptr(new HTTPPathRule(path)); - }); + return std::shared_ptr(new HTTPPathRule(path)); + }); luaCtx.writeFunction("HTTPPathRegexRule", [](const std::string& regex) { - return std::shared_ptr(new HTTPPathRegexRule(regex)); - }); + return std::shared_ptr(new HTTPPathRegexRule(regex)); + }); #endif #ifdef HAVE_RE2 luaCtx.writeFunction("RE2Rule", [](const std::string& str) { - return std::shared_ptr(new RE2Rule(str)); - }); + return std::shared_ptr(new RE2Rule(str)); + }); #endif luaCtx.writeFunction("SNIRule", [](const std::string& name) { - return std::shared_ptr(new SNIRule(name)); + return std::shared_ptr(new SNIRule(name)); }); luaCtx.writeFunction("SuffixMatchNodeRule", qnameSuffixRule); @@ -565,175 +569,175 @@ void setupLuaRules(LuaContext& luaCtx) return std::shared_ptr(new NetmaskGroupRule(nmg, src ? *src : true, quiet ? *quiet : false)); }); - luaCtx.writeFunction("benchRule", [](std::shared_ptr rule, boost::optional times_, boost::optional suffix_) { - setLuaNoSideEffect(); - unsigned int times = times_ ? *times_ : 100000; - DNSName suffix(suffix_ ? *suffix_ : "powerdns.com"); - struct item { - PacketBuffer packet; - InternalQueryState ids; - }; - vector items; - items.reserve(1000); - for (int n = 0; n < 1000; ++n) { - struct item i; - i.ids.qname = DNSName(std::to_string(dns_random_uint32())); - i.ids.qname += suffix; - i.ids.qtype = dns_random(0xff); - i.ids.qclass = QClass::IN; - i.ids.protocol = dnsdist::Protocol::DoUDP; - i.ids.origRemote = ComboAddress("127.0.0.1"); - i.ids.origRemote.sin4.sin_addr.s_addr = random(); - i.ids.queryRealTime.start(); - GenericDNSPacketWriter pw(i.packet, i.ids.qname, i.ids.qtype); - items.push_back(std::move(i)); - } + luaCtx.writeFunction("benchRule", [](std::shared_ptr rule, boost::optional times_, boost::optional suffix_) { + setLuaNoSideEffect(); + unsigned int times = times_ ? *times_ : 100000; + DNSName suffix(suffix_ ? *suffix_ : "powerdns.com"); + struct item + { + PacketBuffer packet; + InternalQueryState ids; + }; + vector items; + items.reserve(1000); + for (int n = 0; n < 1000; ++n) { + struct item i; + i.ids.qname = DNSName(std::to_string(dns_random_uint32())); + i.ids.qname += suffix; + i.ids.qtype = dns_random(0xff); + i.ids.qclass = QClass::IN; + i.ids.protocol = dnsdist::Protocol::DoUDP; + i.ids.origRemote = ComboAddress("127.0.0.1"); + i.ids.origRemote.sin4.sin_addr.s_addr = random(); + i.ids.queryRealTime.start(); + GenericDNSPacketWriter pw(i.packet, i.ids.qname, i.ids.qtype); + items.push_back(std::move(i)); + } - int matches = 0; - ComboAddress dummy("127.0.0.1"); - StopWatch sw; - sw.start(); - for (unsigned int n = 0; n < times; ++n) { - item& i = items[n % items.size()]; - DNSQuestion dq(i.ids, i.packet); + int matches = 0; + ComboAddress dummy("127.0.0.1"); + StopWatch sw; + sw.start(); + for (unsigned int n = 0; n < times; ++n) { + item& i = items[n % items.size()]; + DNSQuestion dq(i.ids, i.packet); - if (rule->matches(&dq)) { - matches++; - } + if (rule->matches(&dq)) { + matches++; } - double udiff = sw.udiff(); - g_outputBuffer=(boost::format("Had %d matches out of %d, %.1f qps, in %.1f us\n") % matches % times % (1000000*(1.0*times/udiff)) % udiff).str(); - - }); + } + double udiff = sw.udiff(); + g_outputBuffer = (boost::format("Had %d matches out of %d, %.1f qps, in %.1f us\n") % matches % times % (1000000 * (1.0 * times / udiff)) % udiff).str(); + }); luaCtx.writeFunction("AllRule", []() { - return std::shared_ptr(new AllRule()); - }); + return std::shared_ptr(new AllRule()); + }); luaCtx.writeFunction("ProbaRule", [](double proba) { - return std::shared_ptr(new ProbaRule(proba)); - }); + return std::shared_ptr(new ProbaRule(proba)); + }); luaCtx.writeFunction("QNameRule", [](const std::string& qname) { - return std::shared_ptr(new QNameRule(DNSName(qname))); - }); + return std::shared_ptr(new QNameRule(DNSName(qname))); + }); luaCtx.writeFunction("QNameSuffixRule", qnameSuffixRule); luaCtx.writeFunction("QTypeRule", [](boost::variant str) { - uint16_t qtype; - if (auto dir = boost::get(&str)) { - qtype = *dir; - } - else { - string val = boost::get(str); - qtype = QType::chartocode(val.c_str()); - if (!qtype) { - throw std::runtime_error("Unable to convert '"+val+"' to a DNS type"); - } + uint16_t qtype; + if (auto dir = boost::get(&str)) { + qtype = *dir; + } + else { + string val = boost::get(str); + qtype = QType::chartocode(val.c_str()); + if (!qtype) { + throw std::runtime_error("Unable to convert '" + val + "' to a DNS type"); } - return std::shared_ptr(new QTypeRule(qtype)); - }); + } + return std::shared_ptr(new QTypeRule(qtype)); + }); luaCtx.writeFunction("QClassRule", [](uint64_t c) { - checkParameterBound("QClassRule", c, std::numeric_limits::max()); - return std::shared_ptr(new QClassRule(c)); - }); + checkParameterBound("QClassRule", c, std::numeric_limits::max()); + return std::shared_ptr(new QClassRule(c)); + }); luaCtx.writeFunction("OpcodeRule", [](uint64_t code) { - checkParameterBound("OpcodeRule", code, std::numeric_limits::max()); - return std::shared_ptr(new OpcodeRule(code)); - }); + checkParameterBound("OpcodeRule", code, std::numeric_limits::max()); + return std::shared_ptr(new OpcodeRule(code)); + }); luaCtx.writeFunction("AndRule", [](const LuaArray>& a) { - return std::shared_ptr(new AndRule(a)); - }); + return std::shared_ptr(new AndRule(a)); + }); luaCtx.writeFunction("OrRule", [](const LuaArray>& a) { - return std::shared_ptr(new OrRule(a)); - }); + return std::shared_ptr(new OrRule(a)); + }); luaCtx.writeFunction("DSTPortRule", [](uint64_t port) { - checkParameterBound("DSTPortRule", port, std::numeric_limits::max()); - return std::shared_ptr(new DSTPortRule(port)); - }); + checkParameterBound("DSTPortRule", port, std::numeric_limits::max()); + return std::shared_ptr(new DSTPortRule(port)); + }); luaCtx.writeFunction("TCPRule", [](bool tcp) { - return std::shared_ptr(new TCPRule(tcp)); - }); + return std::shared_ptr(new TCPRule(tcp)); + }); luaCtx.writeFunction("DNSSECRule", []() { - return std::shared_ptr(new DNSSECRule()); - }); + return std::shared_ptr(new DNSSECRule()); + }); luaCtx.writeFunction("NotRule", [](const std::shared_ptr& rule) { - return std::shared_ptr(new NotRule(rule)); - }); + return std::shared_ptr(new NotRule(rule)); + }); luaCtx.writeFunction("RecordsCountRule", [](uint64_t section, uint64_t minCount, uint64_t maxCount) { - checkParameterBound("RecordsCountRule", section, std::numeric_limits::max()); - checkParameterBound("RecordsCountRule", minCount, std::numeric_limits::max()); - checkParameterBound("RecordsCountRule", maxCount, std::numeric_limits::max()); - return std::shared_ptr(new RecordsCountRule(section, minCount, maxCount)); - }); + checkParameterBound("RecordsCountRule", section, std::numeric_limits::max()); + checkParameterBound("RecordsCountRule", minCount, std::numeric_limits::max()); + checkParameterBound("RecordsCountRule", maxCount, std::numeric_limits::max()); + return std::shared_ptr(new RecordsCountRule(section, minCount, maxCount)); + }); luaCtx.writeFunction("RecordsTypeCountRule", [](uint64_t section, uint64_t type, uint64_t minCount, uint64_t maxCount) { - checkParameterBound("RecordsTypeCountRule", section, std::numeric_limits::max()); - checkParameterBound("RecordsTypeCountRule", type, std::numeric_limits::max()); - checkParameterBound("RecordsTypeCountRule", minCount, std::numeric_limits::max()); - checkParameterBound("RecordsTypeCountRule", maxCount, std::numeric_limits::max()); - return std::shared_ptr(new RecordsTypeCountRule(section, type, minCount, maxCount)); - }); + checkParameterBound("RecordsTypeCountRule", section, std::numeric_limits::max()); + checkParameterBound("RecordsTypeCountRule", type, std::numeric_limits::max()); + checkParameterBound("RecordsTypeCountRule", minCount, std::numeric_limits::max()); + checkParameterBound("RecordsTypeCountRule", maxCount, std::numeric_limits::max()); + return std::shared_ptr(new RecordsTypeCountRule(section, type, minCount, maxCount)); + }); luaCtx.writeFunction("TrailingDataRule", []() { - return std::shared_ptr(new TrailingDataRule()); - }); + return std::shared_ptr(new TrailingDataRule()); + }); luaCtx.writeFunction("QNameLabelsCountRule", [](uint64_t minLabelsCount, uint64_t maxLabelsCount) { - checkParameterBound("QNameLabelsCountRule", minLabelsCount, std::numeric_limits::max()); - checkParameterBound("QNameLabelsCountRule", maxLabelsCount, std::numeric_limits::max()); - return std::shared_ptr(new QNameLabelsCountRule(minLabelsCount, maxLabelsCount)); - }); + checkParameterBound("QNameLabelsCountRule", minLabelsCount, std::numeric_limits::max()); + checkParameterBound("QNameLabelsCountRule", maxLabelsCount, std::numeric_limits::max()); + return std::shared_ptr(new QNameLabelsCountRule(minLabelsCount, maxLabelsCount)); + }); luaCtx.writeFunction("QNameWireLengthRule", [](uint64_t min, uint64_t max) { - return std::shared_ptr(new QNameWireLengthRule(min, max)); - }); + return std::shared_ptr(new QNameWireLengthRule(min, max)); + }); luaCtx.writeFunction("RCodeRule", [](uint64_t rcode) { - checkParameterBound("RCodeRule", rcode, std::numeric_limits::max()); - return std::shared_ptr(new RCodeRule(rcode)); - }); + checkParameterBound("RCodeRule", rcode, std::numeric_limits::max()); + return std::shared_ptr(new RCodeRule(rcode)); + }); luaCtx.writeFunction("ERCodeRule", [](uint64_t rcode) { - checkParameterBound("ERCodeRule", rcode, std::numeric_limits::max()); - return std::shared_ptr(new ERCodeRule(rcode)); - }); + checkParameterBound("ERCodeRule", rcode, std::numeric_limits::max()); + return std::shared_ptr(new ERCodeRule(rcode)); + }); luaCtx.writeFunction("EDNSVersionRule", [](uint64_t version) { - checkParameterBound("EDNSVersionRule", version, std::numeric_limits::max()); - return std::shared_ptr(new EDNSVersionRule(version)); - }); + checkParameterBound("EDNSVersionRule", version, std::numeric_limits::max()); + return std::shared_ptr(new EDNSVersionRule(version)); + }); luaCtx.writeFunction("EDNSOptionRule", [](uint64_t optcode) { - checkParameterBound("EDNSOptionRule", optcode, std::numeric_limits::max()); - return std::shared_ptr(new EDNSOptionRule(optcode)); - }); + checkParameterBound("EDNSOptionRule", optcode, std::numeric_limits::max()); + return std::shared_ptr(new EDNSOptionRule(optcode)); + }); luaCtx.writeFunction("showRules", [](boost::optional vars) { - showRules(&g_ruleactions, vars); - }); + showRules(&g_ruleactions, vars); + }); luaCtx.writeFunction("RDRule", []() { - return std::shared_ptr(new RDRule()); - }); + return std::shared_ptr(new RDRule()); + }); luaCtx.writeFunction("TagRule", [](const std::string& tag, boost::optional value) { - return std::shared_ptr(new TagRule(tag, std::move(value))); - }); + return std::shared_ptr(new TagRule(tag, std::move(value))); + }); luaCtx.writeFunction("TimedIPSetRule", []() { - return std::shared_ptr(new TimedIPSetRule()); - }); + return std::shared_ptr(new TimedIPSetRule()); + }); luaCtx.writeFunction("PoolAvailableRule", [](const std::string& poolname) { return std::shared_ptr(new PoolAvailableRule(poolname)); @@ -743,56 +747,56 @@ void setupLuaRules(LuaContext& luaCtx) return std::shared_ptr(new PoolOutstandingRule(poolname, limit)); }); - luaCtx.registerFunction::*)()>("clear", [](std::shared_ptr tisr) { - tisr->clear(); - }); + luaCtx.registerFunction::*)()>("clear", [](std::shared_ptr tisr) { + tisr->clear(); + }); - luaCtx.registerFunction::*)()>("cleanup", [](std::shared_ptr tisr) { - tisr->cleanup(); - }); + luaCtx.registerFunction::*)()>("cleanup", [](std::shared_ptr tisr) { + tisr->cleanup(); + }); - luaCtx.registerFunction::*)(const ComboAddress& ca, int t)>("add", [](std::shared_ptr tisr, const ComboAddress& ca, int t) { - tisr->add(ca, time(0)+t); - }); + luaCtx.registerFunction::*)(const ComboAddress& ca, int t)>("add", [](std::shared_ptr tisr, const ComboAddress& ca, int t) { + tisr->add(ca, time(0) + t); + }); - luaCtx.registerFunction(std::shared_ptr::*)()>("slice", [](std::shared_ptr tisr) { - return std::dynamic_pointer_cast(tisr); - }); - luaCtx.registerFunction::*)()>("__tostring", [](std::shared_ptr tisr) { - tisr->toString(); - }); + luaCtx.registerFunction (std::shared_ptr::*)()>("slice", [](std::shared_ptr tisr) { + return std::dynamic_pointer_cast(tisr); + }); + luaCtx.registerFunction::*)()>("__tostring", [](std::shared_ptr tisr) { + tisr->toString(); + }); luaCtx.writeFunction("QNameSetRule", [](const DNSNameSet& names) { - return std::shared_ptr(new QNameSetRule(names)); - }); + return std::shared_ptr(new QNameSetRule(names)); + }); #if defined(HAVE_LMDB) || defined(HAVE_CDB) luaCtx.writeFunction("KeyValueStoreLookupRule", [](std::shared_ptr& kvs, std::shared_ptr& lookupKey) { - return std::shared_ptr(new KeyValueStoreLookupRule(kvs, lookupKey)); - }); + return std::shared_ptr(new KeyValueStoreLookupRule(kvs, lookupKey)); + }); luaCtx.writeFunction("KeyValueStoreRangeLookupRule", [](std::shared_ptr& kvs, std::shared_ptr& lookupKey) { - return std::shared_ptr(new KeyValueStoreRangeLookupRule(kvs, lookupKey)); - }); + return std::shared_ptr(new KeyValueStoreRangeLookupRule(kvs, lookupKey)); + }); #endif /* defined(HAVE_LMDB) || defined(HAVE_CDB) */ luaCtx.writeFunction("LuaRule", [](LuaRule::func_t func) { - return std::shared_ptr(new LuaRule(func)); - }); + return std::shared_ptr(new LuaRule(func)); + }); luaCtx.writeFunction("LuaFFIRule", [](LuaFFIRule::func_t func) { - return std::shared_ptr(new LuaFFIRule(func)); - }); + return std::shared_ptr(new LuaFFIRule(func)); + }); luaCtx.writeFunction("LuaFFIPerThreadRule", [](const std::string& code) { - return std::shared_ptr(new LuaFFIPerThreadRule(code)); - }); + return std::shared_ptr(new LuaFFIPerThreadRule(code)); + }); luaCtx.writeFunction("ProxyProtocolValueRule", [](uint8_t type, boost::optional value) { - return std::shared_ptr(new ProxyProtocolValueRule(type, std::move(value))); - }); + return std::shared_ptr(new ProxyProtocolValueRule(type, std::move(value))); + }); luaCtx.writeFunction("PayloadSizeRule", [](const std::string& comparison, uint16_t size) { return std::shared_ptr(new PayloadSizeRule(comparison, size)); - }); + }); } diff --git a/pdns/dnsdistdist/dnsdist-lua-vars.cc b/pdns/dnsdistdist/dnsdist-lua-vars.cc index 89927b72456a..e237204220f1 100644 --- a/pdns/dnsdistdist/dnsdist-lua-vars.cc +++ b/pdns/dnsdistdist/dnsdist-lua-vars.cc @@ -23,96 +23,23 @@ #include "dnsdist-lua.hh" #include "ednsoptions.hh" -#undef BADSIG // signal.h SIG_ERR +#undef BADSIG // signal.h SIG_ERR void setupLuaVars(LuaContext& luaCtx) { - luaCtx.writeVariable("DNSAction", LuaAssociativeTable{ - {"Drop", (int)DNSAction::Action::Drop}, - {"Nxdomain", (int)DNSAction::Action::Nxdomain}, - {"Refused", (int)DNSAction::Action::Refused}, - {"Spoof", (int)DNSAction::Action::Spoof}, - {"SpoofPacket", (int)DNSAction::Action::SpoofPacket}, - {"SpoofRaw", (int)DNSAction::Action::SpoofRaw}, - {"Allow", (int)DNSAction::Action::Allow}, - {"HeaderModify", (int)DNSAction::Action::HeaderModify}, - {"Pool", (int)DNSAction::Action::Pool}, - {"None",(int)DNSAction::Action::None}, - {"NoOp",(int)DNSAction::Action::NoOp}, - {"Delay", (int)DNSAction::Action::Delay}, - {"Truncate", (int)DNSAction::Action::Truncate}, - {"ServFail", (int)DNSAction::Action::ServFail}, - {"NoRecurse", (int)DNSAction::Action::NoRecurse} - }); + luaCtx.writeVariable("DNSAction", LuaAssociativeTable{{"Drop", (int)DNSAction::Action::Drop}, {"Nxdomain", (int)DNSAction::Action::Nxdomain}, {"Refused", (int)DNSAction::Action::Refused}, {"Spoof", (int)DNSAction::Action::Spoof}, {"SpoofPacket", (int)DNSAction::Action::SpoofPacket}, {"SpoofRaw", (int)DNSAction::Action::SpoofRaw}, {"Allow", (int)DNSAction::Action::Allow}, {"HeaderModify", (int)DNSAction::Action::HeaderModify}, {"Pool", (int)DNSAction::Action::Pool}, {"None", (int)DNSAction::Action::None}, {"NoOp", (int)DNSAction::Action::NoOp}, {"Delay", (int)DNSAction::Action::Delay}, {"Truncate", (int)DNSAction::Action::Truncate}, {"ServFail", (int)DNSAction::Action::ServFail}, {"NoRecurse", (int)DNSAction::Action::NoRecurse}}); - luaCtx.writeVariable("DNSResponseAction", LuaAssociativeTable{ - {"Allow", (int)DNSResponseAction::Action::Allow }, - {"Delay", (int)DNSResponseAction::Action::Delay }, - {"Drop", (int)DNSResponseAction::Action::Drop }, - {"HeaderModify", (int)DNSResponseAction::Action::HeaderModify }, - {"ServFail", (int)DNSResponseAction::Action::ServFail }, - {"Truncate", (int)DNSResponseAction::Action::Truncate }, - {"None", (int)DNSResponseAction::Action::None } - }); + luaCtx.writeVariable("DNSResponseAction", LuaAssociativeTable{{"Allow", (int)DNSResponseAction::Action::Allow}, {"Delay", (int)DNSResponseAction::Action::Delay}, {"Drop", (int)DNSResponseAction::Action::Drop}, {"HeaderModify", (int)DNSResponseAction::Action::HeaderModify}, {"ServFail", (int)DNSResponseAction::Action::ServFail}, {"Truncate", (int)DNSResponseAction::Action::Truncate}, {"None", (int)DNSResponseAction::Action::None}}); - luaCtx.writeVariable("DNSClass", LuaAssociativeTable{ - {"IN", QClass::IN }, - {"CHAOS", QClass::CHAOS }, - {"NONE", QClass::NONE }, - {"ANY", QClass::ANY } - }); + luaCtx.writeVariable("DNSClass", LuaAssociativeTable{{"IN", QClass::IN}, {"CHAOS", QClass::CHAOS}, {"NONE", QClass::NONE}, {"ANY", QClass::ANY}}); - luaCtx.writeVariable("DNSOpcode", LuaAssociativeTable{ - {"Query", Opcode::Query }, - {"IQuery", Opcode::IQuery }, - {"Status", Opcode::Status }, - {"Notify", Opcode::Notify }, - {"Update", Opcode::Update } - }); + luaCtx.writeVariable("DNSOpcode", LuaAssociativeTable{{"Query", Opcode::Query}, {"IQuery", Opcode::IQuery}, {"Status", Opcode::Status}, {"Notify", Opcode::Notify}, {"Update", Opcode::Update}}); - luaCtx.writeVariable("DNSSection", LuaAssociativeTable{ - {"Question", 0 }, - {"Answer", 1 }, - {"Authority", 2 }, - {"Additional",3 } - }); + luaCtx.writeVariable("DNSSection", LuaAssociativeTable{{"Question", 0}, {"Answer", 1}, {"Authority", 2}, {"Additional", 3}}); - luaCtx.writeVariable("EDNSOptionCode", LuaAssociativeTable{ - {"NSID", EDNSOptionCode::NSID }, - {"DAU", EDNSOptionCode::DAU }, - {"DHU", EDNSOptionCode::DHU }, - {"N3U", EDNSOptionCode::N3U }, - {"ECS", EDNSOptionCode::ECS }, - {"EXPIRE", EDNSOptionCode::EXPIRE }, - {"COOKIE", EDNSOptionCode::COOKIE }, - {"TCPKEEPALIVE", EDNSOptionCode::TCPKEEPALIVE }, - {"PADDING", EDNSOptionCode::PADDING }, - {"CHAIN", EDNSOptionCode::CHAIN }, - {"KEYTAG", EDNSOptionCode::KEYTAG } - }); + luaCtx.writeVariable("EDNSOptionCode", LuaAssociativeTable{{"NSID", EDNSOptionCode::NSID}, {"DAU", EDNSOptionCode::DAU}, {"DHU", EDNSOptionCode::DHU}, {"N3U", EDNSOptionCode::N3U}, {"ECS", EDNSOptionCode::ECS}, {"EXPIRE", EDNSOptionCode::EXPIRE}, {"COOKIE", EDNSOptionCode::COOKIE}, {"TCPKEEPALIVE", EDNSOptionCode::TCPKEEPALIVE}, {"PADDING", EDNSOptionCode::PADDING}, {"CHAIN", EDNSOptionCode::CHAIN}, {"KEYTAG", EDNSOptionCode::KEYTAG}}); - luaCtx.writeVariable("DNSRCode", LuaAssociativeTable{ - {"NOERROR", RCode::NoError }, - {"FORMERR", RCode::FormErr }, - {"SERVFAIL", RCode::ServFail }, - {"NXDOMAIN", RCode::NXDomain }, - {"NOTIMP", RCode::NotImp }, - {"REFUSED", RCode::Refused }, - {"YXDOMAIN", RCode::YXDomain }, - {"YXRRSET", RCode::YXRRSet }, - {"NXRRSET", RCode::NXRRSet }, - {"NOTAUTH", RCode::NotAuth }, - {"NOTZONE", RCode::NotZone }, - {"BADVERS", ERCode::BADVERS }, - {"BADSIG", ERCode::BADSIG }, - {"BADKEY", ERCode::BADKEY }, - {"BADTIME", ERCode::BADTIME }, - {"BADMODE", ERCode::BADMODE }, - {"BADNAME", ERCode::BADNAME }, - {"BADALG", ERCode::BADALG }, - {"BADTRUNC", ERCode::BADTRUNC }, - {"BADCOOKIE",ERCode::BADCOOKIE } - }); + luaCtx.writeVariable("DNSRCode", LuaAssociativeTable{{"NOERROR", RCode::NoError}, {"FORMERR", RCode::FormErr}, {"SERVFAIL", RCode::ServFail}, {"NXDOMAIN", RCode::NXDomain}, {"NOTIMP", RCode::NotImp}, {"REFUSED", RCode::Refused}, {"YXDOMAIN", RCode::YXDomain}, {"YXRRSET", RCode::YXRRSet}, {"NXRRSET", RCode::NXRRSet}, {"NOTAUTH", RCode::NotAuth}, {"NOTZONE", RCode::NotZone}, {"BADVERS", ERCode::BADVERS}, {"BADSIG", ERCode::BADSIG}, {"BADKEY", ERCode::BADKEY}, {"BADTIME", ERCode::BADTIME}, {"BADMODE", ERCode::BADMODE}, {"BADNAME", ERCode::BADNAME}, {"BADALG", ERCode::BADALG}, {"BADTRUNC", ERCode::BADTRUNC}, {"BADCOOKIE", ERCode::BADCOOKIE}}); LuaAssociativeTable dd; for (const auto& n : QType::names) { @@ -121,9 +48,9 @@ void setupLuaVars(LuaContext& luaCtx) luaCtx.writeVariable("DNSQType", dd); #ifdef HAVE_DNSCRYPT - luaCtx.writeVariable("DNSCryptExchangeVersion", LuaAssociativeTable{ - { "VERSION1", DNSCryptExchangeVersion::VERSION1 }, - { "VERSION2", DNSCryptExchangeVersion::VERSION2 }, - }); + luaCtx.writeVariable("DNSCryptExchangeVersion", LuaAssociativeTable{ + {"VERSION1", DNSCryptExchangeVersion::VERSION1}, + {"VERSION2", DNSCryptExchangeVersion::VERSION2}, + }); #endif } diff --git a/pdns/dnsdistdist/dnsdist-lua.hh b/pdns/dnsdistdist/dnsdist-lua.hh index 5c35c3fb9d02..8a6363300a5c 100644 --- a/pdns/dnsdistdist/dnsdist-lua.hh +++ b/pdns/dnsdistdist/dnsdist-lua.hh @@ -38,7 +38,8 @@ void setResponseHeadersFromConfig(dnsheader& dnsheader, const ResponseConfig& co class SpoofAction : public DNSAction { public: - SpoofAction(const vector& addrs): d_addrs(addrs) + SpoofAction(const vector& addrs) : + d_addrs(addrs) { for (const auto& addr : d_addrs) { if (addr.isIPv4()) { @@ -54,15 +55,18 @@ public: } } - SpoofAction(const DNSName& cname): d_cname(cname) + SpoofAction(const DNSName& cname) : + d_cname(cname) { } - SpoofAction(const char* rawresponse, size_t len): d_raw(rawresponse, rawresponse + len) + SpoofAction(const char* rawresponse, size_t len) : + d_raw(rawresponse, rawresponse + len) { } - SpoofAction(const vector& raws, std::optional typeForAny): d_rawResponses(raws), d_rawTypeForAny(typeForAny) + SpoofAction(const vector& raws, std::optional typeForAny) : + d_rawResponses(raws), d_rawTypeForAny(typeForAny) { } @@ -78,8 +82,8 @@ public: ret += "raw bytes "; } else { - for(const auto& a : d_addrs) - ret += a.toString()+" "; + for (const auto& a : d_addrs) + ret += a.toString() + " "; } return ret; } @@ -105,7 +109,8 @@ class LimitTTLResponseAction : public DNSResponseAction, public boost::noncopyab public: LimitTTLResponseAction() {} - LimitTTLResponseAction(uint32_t min, uint32_t max = std::numeric_limits::max(), const std::unordered_set& types = {}) : d_types(types), d_min(min), d_max(max) + LimitTTLResponseAction(uint32_t min, uint32_t max = std::numeric_limits::max(), const std::unordered_set& types = {}) : + d_types(types), d_min(min), d_max(max) { } @@ -126,7 +131,7 @@ public: } return ttl; }; - editDNSPacketTTL(reinterpret_cast(dr->getMutableData().data()), dr->getData().size(), visitor); + editDNSPacketTTL(reinterpret_cast(dr->getMutableData().data()), dr->getData().size(), visitor); return DNSResponseAction::Action::None; } @@ -147,7 +152,7 @@ public: } result += "]"; } - result += + ")"; + result += +")"; return result; } @@ -157,9 +162,12 @@ private: uint32_t d_max{std::numeric_limits::max()}; }; -template using LuaArray = std::vector>; -template using LuaAssociativeTable = std::unordered_map; -template using LuaTypeOrArrayOf = boost::variant>; +template +using LuaArray = std::vector>; +template +using LuaAssociativeTable = std::unordered_map; +template +using LuaTypeOrArrayOf = boost::variant>; using luaruleparams_t = LuaAssociativeTable; using nmts_t = NetmaskTree; @@ -195,8 +203,9 @@ void setupLuaLoadBalancingContext(LuaContext& luaCtx); * * returns: -1 if type wasn't compatible, 0 if not found or number of element(s) found */ -template -static inline int getOptionalValue(boost::optional& vars, const std::string& key, T& value, bool warnOnWrongType = true) { +template +static inline int getOptionalValue(boost::optional& vars, const std::string& key, T& value, bool warnOnWrongType = true) +{ /* nothing found, nothing to return */ if (!vars) { return 0; @@ -205,7 +214,8 @@ static inline int getOptionalValue(boost::optional& vars, const std::string& if (vars->count(key)) { try { value = boost::get((*vars)[key]); - } catch (const boost::bad_get& e) { + } + catch (const boost::bad_get& e) { /* key is there but isn't compatible */ if (warnOnWrongType) { warnlog("Invalid type for key '%s' - ignored", key); @@ -217,8 +227,9 @@ static inline int getOptionalValue(boost::optional& vars, const std::string& return vars->erase(key); } -template -static inline int getOptionalIntegerValue(const std::string& func, boost::optional& vars, const std::string& key, T& value) { +template +static inline int getOptionalIntegerValue(const std::string& func, boost::optional& vars, const std::string& key, T& value) +{ std::string valueStr; auto ret = getOptionalValue(vars, key, valueStr, true); if (ret == 1) { @@ -233,8 +244,9 @@ static inline int getOptionalIntegerValue(const std::string& func, boost::option return ret; } -template -static inline void checkAllParametersConsumed(const std::string& func, const boost::optional& vars) { +template +static inline void checkAllParametersConsumed(const std::string& func, const boost::optional& vars) +{ /* no vars */ if (!vars) { return; diff --git a/pdns/dnsdistdist/dnsdist-rings.cc b/pdns/dnsdistdist/dnsdist-rings.cc index b97b44e6459d..7ab00f1b7ba4 100644 --- a/pdns/dnsdistdist/dnsdist-rings.cc +++ b/pdns/dnsdistdist/dnsdist-rings.cc @@ -65,7 +65,8 @@ void Rings::setNumberOfLockRetries(size_t retries) { if (d_numberOfShards <= 1) { d_nbLockTries = 0; - } else { + } + else { d_nbLockTries = retries; } } @@ -92,23 +93,23 @@ size_t Rings::numDistinctRequestors() return s.size(); } -std::unordered_map>> Rings::getTopBandwidth(unsigned int numentries) +std::unordered_map>> Rings::getTopBandwidth(unsigned int numentries) { map counts; - uint64_t total=0; + uint64_t total = 0; for (const auto& shard : d_shards) { { auto rl = shard->queryRing.lock(); - for(const auto& q : *rl) { + for (const auto& q : *rl) { counts[q.requestor] += q.size; - total+=q.size; + total += q.size; } } { auto rl = shard->respRing.lock(); - for(const auto& r : *rl) { + for (const auto& r : *rl) { counts[r.requestor] += r.size; - total+=r.size; + total += r.size; } } } @@ -116,30 +117,29 @@ std::unordered_map>> Rings::getTopBand typedef vector> ret_t; ret_t rcounts; rcounts.reserve(counts.size()); - for(const auto& p : counts) + for (const auto& p : counts) rcounts.push_back({p.second, p.first}); numentries = rcounts.size() < numentries ? rcounts.size() : numentries; - partial_sort(rcounts.begin(), rcounts.begin()+numentries, rcounts.end(), [](const ret_t::value_type&a, const ret_t::value_type&b) - { - return(b.first < a.first); - }); - std::unordered_map>> ret; + partial_sort(rcounts.begin(), rcounts.begin() + numentries, rcounts.end(), [](const ret_t::value_type& a, const ret_t::value_type& b) { + return (b.first < a.first); + }); + std::unordered_map>> ret; uint64_t rest = 0; int count = 1; - for(const auto& rc : rcounts) { + for (const auto& rc : rcounts) { if (count == static_cast(numentries + 1)) { - rest+=rc.first; + rest += rc.first; } else { - ret.insert({count++, {rc.second.toString(), rc.first, 100.0*rc.first/total}}); + ret.insert({count++, {rc.second.toString(), rc.first, 100.0 * rc.first / total}}); } } if (total > 0) { - ret.insert({count, {"Rest", rest, 100.0*rest/total}}); + ret.insert({count, {"Rest", rest, 100.0 * rest / total}}); } else { - ret.insert({count, {"Rest", rest, 100.0 }}); + ret.insert({count, {"Rest", rest, 100.0}}); } return ret; @@ -170,7 +170,7 @@ size_t Rings::loadFromFile(const std::string& filepath, const struct timespec& n isResponse = true; } else { - cerr<<"skipping line with "< timeStr; stringtok(timeStr, parts.at(idx++), "."); if (timeStr.size() != 2) { - cerr<<"skipping invalid time "<> respRing; }; - Rings(size_t capacity=10000, size_t numberOfShards=10, size_t nbLockTries=5, bool keepLockingStats=false): d_blockingQueryInserts(0), d_blockingResponseInserts(0), d_deferredQueryInserts(0), d_deferredResponseInserts(0), d_nbQueryEntries(0), d_nbResponseEntries(0), d_currentShardId(0), d_capacity(capacity), d_numberOfShards(numberOfShards), d_nbLockTries(nbLockTries), d_keepLockingStats(keepLockingStats) + Rings(size_t capacity = 10000, size_t numberOfShards = 10, size_t nbLockTries = 5, bool keepLockingStats = false) : + d_blockingQueryInserts(0), d_blockingResponseInserts(0), d_deferredQueryInserts(0), d_deferredResponseInserts(0), d_nbQueryEntries(0), d_nbResponseEntries(0), d_currentShardId(0), d_capacity(capacity), d_numberOfShards(numberOfShards), d_nbLockTries(nbLockTries), d_keepLockingStats(keepLockingStats) { } - std::unordered_map > > getTopBandwidth(unsigned int numentries); + std::unordered_map>> getTopBandwidth(unsigned int numentries); size_t numDistinctRequestors(); /* this function should not be called after init() has been called */ void setCapacity(size_t newCapacity, size_t numberOfShards); @@ -201,7 +203,7 @@ struct Rings { return d_recordResponses; } - std::vector > d_shards; + std::vector> d_shards; pdns::stat_t d_blockingQueryInserts; pdns::stat_t d_blockingResponseInserts; pdns::stat_t d_deferredQueryInserts; diff --git a/pdns/dnsdistdist/dnsdist-snmp.cc b/pdns/dnsdistdist/dnsdist-snmp.cc index 856fccb111d1..6081d11f9ec5 100644 --- a/pdns/dnsdistdist/dnsdist-snmp.cc +++ b/pdns/dnsdistdist/dnsdist-snmp.cc @@ -15,46 +15,46 @@ DNSDistSNMPAgent* g_snmpAgent{nullptr}; #define DNSDIST_TRAPS_OID DNSDIST_OID, 10, 0 #define DNSDIST_TRAP_OBJECTS_OID DNSDIST_OID, 11 -static const oid queriesOID[] = { DNSDIST_STATS_OID, 1 }; -static const oid responsesOID[] = { DNSDIST_STATS_OID, 2 }; -static const oid servfailResponsesOID[] = { DNSDIST_STATS_OID, 3 }; -static const oid aclDropsOID[] = { DNSDIST_STATS_OID, 4 }; +static const oid queriesOID[] = {DNSDIST_STATS_OID, 1}; +static const oid responsesOID[] = {DNSDIST_STATS_OID, 2}; +static const oid servfailResponsesOID[] = {DNSDIST_STATS_OID, 3}; +static const oid aclDropsOID[] = {DNSDIST_STATS_OID, 4}; // 5 was BlockFilter, removed in 1.2.0 -static const oid ruleDropOID[] = { DNSDIST_STATS_OID, 6 }; -static const oid ruleNXDomainOID[] = { DNSDIST_STATS_OID, 7 }; -static const oid ruleRefusedOID[] = { DNSDIST_STATS_OID, 8 }; -static const oid selfAnsweredOID[] = { DNSDIST_STATS_OID, 9 }; -static const oid downstreamTimeoutsOID[] = { DNSDIST_STATS_OID, 10 }; -static const oid downstreamSendErrorsOID[] = { DNSDIST_STATS_OID, 11 }; -static const oid truncFailOID[] = { DNSDIST_STATS_OID, 12 }; -static const oid noPolicyOID[] = { DNSDIST_STATS_OID, 13 }; -static const oid latency0_1OID[] = { DNSDIST_STATS_OID, 14 }; -static const oid latency1_10OID[] = { DNSDIST_STATS_OID, 15 }; -static const oid latency10_50OID[] = { DNSDIST_STATS_OID, 16 }; -static const oid latency50_100OID[] = { DNSDIST_STATS_OID, 17 }; -static const oid latency100_1000OID[] = { DNSDIST_STATS_OID, 18 }; -static const oid latencySlowOID[] = { DNSDIST_STATS_OID, 19 }; -static const oid latencyAvg100OID[] = { DNSDIST_STATS_OID, 20 }; -static const oid latencyAvg1000OID[] = { DNSDIST_STATS_OID, 21 }; -static const oid latencyAvg10000OID[] = { DNSDIST_STATS_OID, 22 }; -static const oid latencyAvg1000000OID[] = { DNSDIST_STATS_OID, 23 }; -static const oid uptimeOID[] = { DNSDIST_STATS_OID, 24 }; -static const oid realMemoryUsageOID[] = { DNSDIST_STATS_OID, 25 }; -static const oid nonCompliantQueriesOID[] = { DNSDIST_STATS_OID, 26 }; -static const oid nonCompliantResponsesOID[] = { DNSDIST_STATS_OID, 27 }; -static const oid rdQueriesOID[] = { DNSDIST_STATS_OID, 28 }; -static const oid emptyQueriesOID[] = { DNSDIST_STATS_OID, 29 }; -static const oid cacheHitsOID[] = { DNSDIST_STATS_OID, 30 }; -static const oid cacheMissesOID[] = { DNSDIST_STATS_OID, 31 }; -static const oid cpuUserMSecOID[] = { DNSDIST_STATS_OID, 32 }; -static const oid cpuSysMSecOID[] = { DNSDIST_STATS_OID, 33 }; -static const oid fdUsageOID[] = { DNSDIST_STATS_OID, 34 }; -static const oid dynBlockedOID[] = { DNSDIST_STATS_OID, 35 }; -static const oid dynBlockedNMGSizeOID[] = { DNSDIST_STATS_OID, 36 }; -static const oid ruleServFailOID[] = { DNSDIST_STATS_OID, 37 }; -static const oid securityStatusOID[] = { DNSDIST_STATS_OID, 38 }; -static const oid specialMemoryUsageOID[] = { DNSDIST_STATS_OID, 39 }; -static const oid ruleTruncatedOID[] = { DNSDIST_STATS_OID, 40 }; +static const oid ruleDropOID[] = {DNSDIST_STATS_OID, 6}; +static const oid ruleNXDomainOID[] = {DNSDIST_STATS_OID, 7}; +static const oid ruleRefusedOID[] = {DNSDIST_STATS_OID, 8}; +static const oid selfAnsweredOID[] = {DNSDIST_STATS_OID, 9}; +static const oid downstreamTimeoutsOID[] = {DNSDIST_STATS_OID, 10}; +static const oid downstreamSendErrorsOID[] = {DNSDIST_STATS_OID, 11}; +static const oid truncFailOID[] = {DNSDIST_STATS_OID, 12}; +static const oid noPolicyOID[] = {DNSDIST_STATS_OID, 13}; +static const oid latency0_1OID[] = {DNSDIST_STATS_OID, 14}; +static const oid latency1_10OID[] = {DNSDIST_STATS_OID, 15}; +static const oid latency10_50OID[] = {DNSDIST_STATS_OID, 16}; +static const oid latency50_100OID[] = {DNSDIST_STATS_OID, 17}; +static const oid latency100_1000OID[] = {DNSDIST_STATS_OID, 18}; +static const oid latencySlowOID[] = {DNSDIST_STATS_OID, 19}; +static const oid latencyAvg100OID[] = {DNSDIST_STATS_OID, 20}; +static const oid latencyAvg1000OID[] = {DNSDIST_STATS_OID, 21}; +static const oid latencyAvg10000OID[] = {DNSDIST_STATS_OID, 22}; +static const oid latencyAvg1000000OID[] = {DNSDIST_STATS_OID, 23}; +static const oid uptimeOID[] = {DNSDIST_STATS_OID, 24}; +static const oid realMemoryUsageOID[] = {DNSDIST_STATS_OID, 25}; +static const oid nonCompliantQueriesOID[] = {DNSDIST_STATS_OID, 26}; +static const oid nonCompliantResponsesOID[] = {DNSDIST_STATS_OID, 27}; +static const oid rdQueriesOID[] = {DNSDIST_STATS_OID, 28}; +static const oid emptyQueriesOID[] = {DNSDIST_STATS_OID, 29}; +static const oid cacheHitsOID[] = {DNSDIST_STATS_OID, 30}; +static const oid cacheMissesOID[] = {DNSDIST_STATS_OID, 31}; +static const oid cpuUserMSecOID[] = {DNSDIST_STATS_OID, 32}; +static const oid cpuSysMSecOID[] = {DNSDIST_STATS_OID, 33}; +static const oid fdUsageOID[] = {DNSDIST_STATS_OID, 34}; +static const oid dynBlockedOID[] = {DNSDIST_STATS_OID, 35}; +static const oid dynBlockedNMGSizeOID[] = {DNSDIST_STATS_OID, 36}; +static const oid ruleServFailOID[] = {DNSDIST_STATS_OID, 37}; +static const oid securityStatusOID[] = {DNSDIST_STATS_OID, 38}; +static const oid specialMemoryUsageOID[] = {DNSDIST_STATS_OID, 39}; +static const oid ruleTruncatedOID[] = {DNSDIST_STATS_OID, 40}; static std::unordered_map s_statsMap; @@ -202,40 +202,40 @@ static void registerGauge64Stat(const char* name, const oid statOID[], size_t st } /* column number definitions for table backendStatTable */ -#define COLUMN_BACKENDID 1 -#define COLUMN_BACKENDNAME 2 -#define COLUMN_BACKENDLATENCY 3 -#define COLUMN_BACKENDWEIGHT 4 -#define COLUMN_BACKENDOUTSTANDING 5 -#define COLUMN_BACKENDQPSLIMIT 6 -#define COLUMN_BACKENDREUSED 7 -#define COLUMN_BACKENDSTATE 8 -#define COLUMN_BACKENDADDRESS 9 -#define COLUMN_BACKENDPOOLS 10 -#define COLUMN_BACKENDQPS 11 -#define COLUMN_BACKENDQUERIES 12 -#define COLUMN_BACKENDORDER 13 - -static const oid backendStatTableOID[] = { DNSDIST_STATS_TABLE_OID }; -static const oid backendNameOID[] = { DNSDIST_STATS_TABLE_OID, 1, 2 }; -static const oid backendStateOID[] = { DNSDIST_STATS_TABLE_OID, 1, 8}; -static const oid backendAddressOID[] = { DNSDIST_STATS_TABLE_OID, 1, 9}; - -static const oid socketFamilyOID[] = { DNSDIST_TRAP_OBJECTS_OID, 1, 0 }; -static const oid socketProtocolOID[] = { DNSDIST_TRAP_OBJECTS_OID, 2, 0 }; -static const oid fromAddressOID[] = { DNSDIST_TRAP_OBJECTS_OID, 3, 0 }; -static const oid toAddressOID[] = { DNSDIST_TRAP_OBJECTS_OID, 4, 0 }; -static const oid queryTypeOID[] = { DNSDIST_TRAP_OBJECTS_OID, 5, 0 }; -static const oid querySizeOID[] = { DNSDIST_TRAP_OBJECTS_OID, 6, 0 }; -static const oid queryIDOID[] = { DNSDIST_TRAP_OBJECTS_OID, 7, 0 }; -static const oid qNameOID[] = { DNSDIST_TRAP_OBJECTS_OID, 8, 0 }; -static const oid qClassOID[] = { DNSDIST_TRAP_OBJECTS_OID, 9, 0 }; -static const oid qTypeOID[] = { DNSDIST_TRAP_OBJECTS_OID, 10, 0 }; -static const oid trapReasonOID[] = { DNSDIST_TRAP_OBJECTS_OID, 11, 0 }; - -static const oid backendStatusChangeTrapOID[] = { DNSDIST_TRAPS_OID, 1 }; -static const oid actionTrapOID[] = { DNSDIST_TRAPS_OID, 2 }; -static const oid customTrapOID[] = { DNSDIST_TRAPS_OID, 3 }; +#define COLUMN_BACKENDID 1 +#define COLUMN_BACKENDNAME 2 +#define COLUMN_BACKENDLATENCY 3 +#define COLUMN_BACKENDWEIGHT 4 +#define COLUMN_BACKENDOUTSTANDING 5 +#define COLUMN_BACKENDQPSLIMIT 6 +#define COLUMN_BACKENDREUSED 7 +#define COLUMN_BACKENDSTATE 8 +#define COLUMN_BACKENDADDRESS 9 +#define COLUMN_BACKENDPOOLS 10 +#define COLUMN_BACKENDQPS 11 +#define COLUMN_BACKENDQUERIES 12 +#define COLUMN_BACKENDORDER 13 + +static const oid backendStatTableOID[] = {DNSDIST_STATS_TABLE_OID}; +static const oid backendNameOID[] = {DNSDIST_STATS_TABLE_OID, 1, 2}; +static const oid backendStateOID[] = {DNSDIST_STATS_TABLE_OID, 1, 8}; +static const oid backendAddressOID[] = {DNSDIST_STATS_TABLE_OID, 1, 9}; + +static const oid socketFamilyOID[] = {DNSDIST_TRAP_OBJECTS_OID, 1, 0}; +static const oid socketProtocolOID[] = {DNSDIST_TRAP_OBJECTS_OID, 2, 0}; +static const oid fromAddressOID[] = {DNSDIST_TRAP_OBJECTS_OID, 3, 0}; +static const oid toAddressOID[] = {DNSDIST_TRAP_OBJECTS_OID, 4, 0}; +static const oid queryTypeOID[] = {DNSDIST_TRAP_OBJECTS_OID, 5, 0}; +static const oid querySizeOID[] = {DNSDIST_TRAP_OBJECTS_OID, 6, 0}; +static const oid queryIDOID[] = {DNSDIST_TRAP_OBJECTS_OID, 7, 0}; +static const oid qNameOID[] = {DNSDIST_TRAP_OBJECTS_OID, 8, 0}; +static const oid qClassOID[] = {DNSDIST_TRAP_OBJECTS_OID, 9, 0}; +static const oid qTypeOID[] = {DNSDIST_TRAP_OBJECTS_OID, 10, 0}; +static const oid trapReasonOID[] = {DNSDIST_TRAP_OBJECTS_OID, 11, 0}; + +static const oid backendStatusChangeTrapOID[] = {DNSDIST_TRAPS_OID, 1}; +static const oid actionTrapOID[] = {DNSDIST_TRAPS_OID, 2}; +static const oid customTrapOID[] = {DNSDIST_TRAPS_OID, 3}; static servers_t s_servers; static size_t s_currentServerIdx = 0; @@ -249,7 +249,7 @@ static netsnmp_variable_list* backendStatTable_get_next_data_point(void** loop_c return NULL; } - *my_data_context = (void*) (s_servers[s_currentServerIdx]).get(); + *my_data_context = (void*)(s_servers[s_currentServerIdx]).get(); snmp_set_var_typed_integer(put_index_data, ASN_UNSIGNED, s_currentServerIdx); s_currentServerIdx++; @@ -289,7 +289,7 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler, case MODE_GET: for (request = requests; request; request = request->next) { netsnmp_table_request_info* table_info = netsnmp_extract_table_info(request); - const DownstreamState* server = (const DownstreamState*) netsnmp_extract_iterator_context(request); + const DownstreamState* server = (const DownstreamState*)netsnmp_extract_iterator_context(request); if (!server) { continue; @@ -321,8 +321,7 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler, case COLUMN_BACKENDREUSED: DNSDistSNMPAgent::setCounter64Value(request, server->reuseds.load()); break; - case COLUMN_BACKENDSTATE: - { + case COLUMN_BACKENDSTATE: { std::string state(server->getStatus()); snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR, @@ -330,8 +329,7 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler, state.size()); break; } - case COLUMN_BACKENDADDRESS: - { + case COLUMN_BACKENDADDRESS: { std::string addr(server->d_config.remote.toStringWithPort()); snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR, @@ -339,12 +337,11 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler, addr.size()); break; } - case COLUMN_BACKENDPOOLS: - { + case COLUMN_BACKENDPOOLS: { std::string pools; for (const auto& p : server->d_config.pools) { if (!pools.empty()) { - pools+=" "; + pools += " "; } pools += p; } @@ -388,8 +385,7 @@ bool DNSDistSNMPAgent::sendBackendStatusChangeTrap(const DownstreamState& dss) snmpTrapOID.size(), ASN_OBJECT_ID, backendStatusChangeTrapOID, - OID_LENGTH(backendStatusChangeTrapOID) * sizeof(oid)); - + OID_LENGTH(backendStatusChangeTrapOID) * sizeof(oid)); snmp_varlist_add_variable(&varList, backendNameOID, @@ -428,7 +424,7 @@ bool DNSDistSNMPAgent::sendCustomTrap(const std::string& reason) snmpTrapOID.size(), ASN_OBJECT_ID, customTrapOID, - OID_LENGTH(customTrapOID) * sizeof(oid)); + OID_LENGTH(customTrapOID) * sizeof(oid)); snmp_varlist_add_variable(&varList, trapReasonOID, @@ -452,10 +448,10 @@ bool DNSDistSNMPAgent::sendDNSTrap(const DNSQuestion& dq, const std::string& rea const uint32_t socketFamily = dq.ids.origRemote.isIPv4() ? 1 : 2; const uint32_t socketProtocol = dq.overTCP() ? 2 : 1; const uint32_t queryType = dq.getHeader()->qr ? 2 : 1; - const uint32_t querySize = (uint32_t) dq.getData().size(); - const uint32_t queryID = (uint32_t) ntohs(dq.getHeader()->id); - const uint32_t qType = (uint32_t) dq.ids.qtype; - const uint32_t qClass = (uint32_t) dq.ids.qclass; + const uint32_t querySize = (uint32_t)dq.getData().size(); + const uint32_t queryID = (uint32_t)ntohs(dq.getHeader()->id); + const uint32_t qType = (uint32_t)dq.ids.qtype; + const uint32_t qClass = (uint32_t)dq.ids.qclass; netsnmp_variable_list* varList = nullptr; @@ -464,7 +460,7 @@ bool DNSDistSNMPAgent::sendDNSTrap(const DNSQuestion& dq, const std::string& rea snmpTrapOID.size(), ASN_OBJECT_ID, actionTrapOID, - OID_LENGTH(actionTrapOID) * sizeof(oid)); + OID_LENGTH(actionTrapOID) * sizeof(oid)); snmp_varlist_add_variable(&varList, socketFamilyOID, @@ -549,7 +545,8 @@ bool DNSDistSNMPAgent::sendDNSTrap(const DNSQuestion& dq, const std::string& rea #endif /* HAVE_NET_SNMP */ } -DNSDistSNMPAgent::DNSDistSNMPAgent(const std::string& name, const std::string& daemonSocket): SNMPAgent(name, daemonSocket) +DNSDistSNMPAgent::DNSDistSNMPAgent(const std::string& name, const std::string& daemonSocket) : + SNMPAgent(name, daemonSocket) { #ifdef HAVE_NET_SNMP @@ -593,10 +590,9 @@ DNSDistSNMPAgent::DNSDistSNMPAgent(const std::string& name, const std::string& d registerGauge64Stat("securityStatus", securityStatusOID, OID_LENGTH(securityStatusOID), [](const std::string&) { return dnsdist::metrics::g_stats.securityStatus.load(); }); registerGauge64Stat("realMemoryUsage", realMemoryUsageOID, OID_LENGTH(realMemoryUsageOID), &getRealMemoryUsage); - netsnmp_table_registration_info* table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info); netsnmp_table_helper_add_indexes(table_info, - ASN_GAUGE, /* index: backendId */ + ASN_GAUGE, /* index: backendId */ 0); table_info->min_column = COLUMN_BACKENDNAME; table_info->max_column = COLUMN_BACKENDORDER; diff --git a/pdns/dnsdistdist/dnsdist-snmp.hh b/pdns/dnsdistdist/dnsdist-snmp.hh index 283d43c6a579..7c1deff9b321 100644 --- a/pdns/dnsdistdist/dnsdist-snmp.hh +++ b/pdns/dnsdistdist/dnsdist-snmp.hh @@ -27,11 +27,11 @@ class DNSDistSNMPAgent; #include "dnsdist.hh" -class DNSDistSNMPAgent: public SNMPAgent +class DNSDistSNMPAgent : public SNMPAgent { public: DNSDistSNMPAgent(const std::string& name, const std::string& daemonSocket); bool sendBackendStatusChangeTrap(const DownstreamState&); bool sendCustomTrap(const std::string& reason); - bool sendDNSTrap(const DNSQuestion&, const std::string& reason=""); + bool sendDNSTrap(const DNSQuestion&, const std::string& reason = ""); }; diff --git a/pdns/dnsdistdist/dnsdist-web.cc b/pdns/dnsdistdist/dnsdist-web.cc index 066b5c177f54..7462c43bf11d 100644 --- a/pdns/dnsdistdist/dnsdist-web.cc +++ b/pdns/dnsdistdist/dnsdist-web.cc @@ -53,7 +53,7 @@ struct WebserverConfig NetmaskGroup acl; std::unique_ptr password; std::unique_ptr apiKey; - boost::optional > customHeaders; + boost::optional> customHeaders; bool apiRequiresAuthentication{true}; bool dashboardRequiresAuthentication{true}; bool statsRequireAuthentication{true}; @@ -99,13 +99,15 @@ std::string getWebserverConfig() class WebClientConnection { public: - WebClientConnection(const ComboAddress& client, int fd): d_client(client), d_socket(fd) + 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(WebClientConnection&& rhs) : + d_client(rhs.d_client), d_socket(std::move(rhs.d_socket)) { } @@ -138,87 +140,88 @@ class WebClientConnection static MetricDefinitionStorage s_metricDefinitions; std::map 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") }, + {"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) { +bool addMetricDefinition(const dnsdist::prometheus::PrometheusMetricDefinition& def) +{ #ifndef DISABLE_PROMETHEUS return MetricDefinitionStorage::addMetricDefinition(def); #else @@ -341,7 +344,7 @@ static bool handleAuthorization(const YaHTTP::Request& req) if (isAnAPIRequest(req)) { /* Access to the API requires a valid API key */ - if (!config->apiRequiresAuthentication || checkAPIKey(req, config->apiKey)) { + if (!config->apiRequiresAuthentication || checkAPIKey(req, config->apiKey)) { return true; } @@ -399,14 +402,14 @@ static void handleCORS(const YaHTTP::Request& req, YaHTTP::Response& resp) } } -static void addSecurityHeaders(YaHTTP::Response& resp, const boost::optional >& customHeaders) +static void addSecurityHeaders(YaHTTP::Response& resp, const boost::optional>& customHeaders) { - static const std::vector > 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'" }, + static const std::vector> 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) { @@ -420,7 +423,7 @@ static void addSecurityHeaders(YaHTTP::Response& resp, const boost::optional >& customHeaders) +static void addCustomHeaders(YaHTTP::Response& resp, const boost::optional>& customHeaders) { if (!customHeaders) return; @@ -432,31 +435,31 @@ static void addCustomHeaders(YaHTTP::Response& resp, const boost::optional +template static json11::Json::array someResponseRulesToJson(GlobalStateHolder>* someResponseRules) { using namespace json11; Json::array responseRules; - int num=0; + 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()}, - }); + {"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 -static void addRulesToPrometheusOutput(std::ostringstream& output, GlobalStateHolder >& rules) +template +static void addRulesToPrometheusOutput(std::ostringstream& output, GlobalStateHolder>& rules) { auto localRules = rules.getLocal(); for (const auto& entry : *localRules) { @@ -471,7 +474,7 @@ static void handlePrometheus(const YaHTTP::Request& req, YaHTTP::Response& resp) resp.status = 200; std::ostringstream output; - static const std::set metricBlacklist = { "special-memory-usage", "latency-count", "latency-sum" }; + static const std::set metricBlacklist = {"special-memory-usage", "latency-count", "latency-sum"}; { auto entries = dnsdist::metrics::g_stats.entries.read_lock(); for (const auto& entry : *entries) { @@ -505,7 +508,7 @@ static void handlePrometheus(const YaHTTP::Request& req, YaHTTP::Response& resp) // 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('{')); - output << "# HELP " << helpName << " " << metricDetails.description << "\n"; + output << "# HELP " << helpName << " " << metricDetails.description << "\n"; output << "# TYPE " << helpName << " " << prometheusTypeName << "\n"; output << prometheusMetricName << " "; @@ -547,6 +550,7 @@ static void handlePrometheus(const YaHTTP::Request& req, YaHTTP::Response& resp) auto states = g_dstates.getLocal(); const string statesbase = "dnsdist_server_"; + // clang-format off 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"; @@ -910,6 +914,7 @@ static void handlePrometheus(const YaHTTP::Request& req, YaHTTP::Response& resp) resp.body = output.str(); resp.headers["Content-Type"] = "text/plain"; + // clang-format on } #endif /* DISABLE_PROMETHEUS */ @@ -924,11 +929,14 @@ static void addStatsToJSONObject(Json::object& obj) } if (const auto& val = std::get_if(&entry.d_value)) { obj.emplace(entry.d_name, (double)(*val)->load()); - } else if (const auto& adval = std::get_if*>(&entry.d_value)) { + } + else if (const auto& adval = std::get_if*>(&entry.d_value)) { obj.emplace(entry.d_name, (*adval)->load()); - } else if (const auto& dval = std::get_if(&entry.d_value)) { + } + else if (const auto& dval = std::get_if(&entry.d_value)) { obj.emplace(entry.d_name, (**dval)); - } else if (const auto& func = std::get_if(&entry.d_value)) { + } + else if (const auto& func = std::get_if(&entry.d_value)) { obj.emplace(entry.d_name, (double)(*func)(entry.d_name)); } } @@ -948,13 +956,12 @@ static void handleJSONStats(const YaHTTP::Request& req, YaHTTP::Response& resp) 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()} - }; + 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); @@ -968,7 +975,7 @@ static void handleJSONStats(const YaHTTP::Request& req, YaHTTP::Response& resp) auto nmg = g_dynblockNMG.getLocal(); struct timespec now; gettime(&now); - for (const auto& entry: *nmg) { + for (const auto& entry : *nmg) { if (!(now < entry.second.until)) { continue; } @@ -982,13 +989,12 @@ static void handleJSONStats(const YaHTTP::Request& req, YaHTTP::Response& resp) {"blocks", static_cast(counter)}, {"action", DNSAction::typeToString(entry.second.action != DNSAction::Action::None ? entry.second.action : g_dynBlockAction)}, {"warning", entry.second.warning}, - {"ebpf", entry.second.bpf} - }; + {"ebpf", entry.second.bpf}}; obj.emplace(entry.first.toString(), thing); } auto smt = g_dynblockSMT.getLocal(); - smt->visit([&now,&obj](const SuffixMatchTree& node) { + smt->visit([&now, &obj](const SuffixMatchTree& node) { if (!(now < node.d_value.until)) { return; } @@ -1001,8 +1007,7 @@ static void handleJSONStats(const YaHTTP::Request& req, YaHTTP::Response& resp) {"seconds", static_cast(node.d_value.until.tv_sec - now.tv_sec)}, {"blocks", static_cast(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} - }; + {"ebpf", node.d_value.bpf}}; obj.emplace(dom, thing); }); #endif /* DISABLE_DYNBLOCKS */ @@ -1016,19 +1021,17 @@ static void handleJSONStats(const YaHTTP::Request& req, YaHTTP::Response& resp) struct timespec now; gettime(&now); for (const auto& dynbpf : g_dynBPFFilters) { - std::vector > addrStats = dynbpf->getAddrStats(); + std::vector> 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 ); + 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) { + for (const auto& entry : *nmg) { if (!(now < entry.second.until) || !entry.second.bpf) { continue; } @@ -1069,11 +1072,11 @@ static void addServerToJSON(Json::array& servers, int id, const std::shared_ptr< Json::array pools; pools.reserve(a->d_config.pools.size()); - for (const auto& p: a->d_config.pools) { + for (const auto& p : a->d_config.pools) { pools.push_back(p); } - Json::object server { + Json::object server{ {"id", id}, {"name", a->getName()}, {"address", a->d_config.remote.toStringWithPort()}, @@ -1086,7 +1089,7 @@ static void addServerToJSON(Json::array& servers, int id, const std::shared_ptr< {"weight", (double)a->d_config.d_weight}, {"order", (double)a->d_config.order}, {"pools", std::move(pools)}, - {"latency", (double)(a->latencyUsec/1000.0)}, + {"latency", (double)(a->latencyUsec / 1000.0)}, {"queries", (double)a->queries}, {"responses", (double)a->responses}, {"nonCompliantResponses", (double)a->nonCompliantResponses}, @@ -1105,15 +1108,14 @@ static void addServerToJSON(Json::array& servers, int id, const std::shared_ptr< {"tcpAvgQueriesPerConnection", (double)a->tcpAvgQueriesPerConnection}, {"tcpAvgConnectionDuration", (double)a->tcpAvgConnectionDuration}, {"tlsResumptions", (double)a->tlsResumptions}, - {"tcpLatency", (double)(a->latencyUsecTCP/1000.0)}, + {"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} - }; + {"dropRate", (double)a->dropRate}}; /* sending a latency for a DOWN server doesn't make sense */ if (a->d_config.availability == DownstreamState::Availability::Down) { @@ -1146,33 +1148,33 @@ static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp) 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 }, + 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) { @@ -1201,30 +1203,29 @@ static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp) 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 } - }); + {"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 */ @@ -1236,21 +1237,20 @@ static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp) 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) } - }; + 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)); } } @@ -1271,8 +1271,7 @@ static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp) {"matches", (double)a.d_rule->d_matches}, {"rule", a.d_rule->toString()}, {"action", a.d_action->toString()}, - {"action-stats", a.d_action->getStats()} - }; + {"action-stats", a.d_action->getStats()}}; rules.push_back(std::move(rule)); } } @@ -1310,22 +1309,20 @@ static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp) 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) } - })); + 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(); @@ -1352,20 +1349,19 @@ static void handlePoolStats(const YaHTTP::Request& req, YaHTTP::Response& resp) 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::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; @@ -1375,10 +1371,9 @@ static void handlePoolStats(const YaHTTP::Request& req, YaHTTP::Response& resp) } resp.headers["Content-Type"] = "application/json"; - Json my_json = Json::object { - { "stats", entry }, - { "servers", servers } - }; + Json my_json = Json::object{ + {"stats", entry}, + {"servers", servers}}; resp.body = my_json.dump(); } @@ -1397,32 +1392,28 @@ static void handleStatsOnly(const YaHTTP::Request& req, YaHTTP::Response& resp) } if (const auto& val = std::get_if(&item.d_value)) { - doc.push_back(Json::object { - { "type", "StatisticItem" }, - { "name", item.d_name }, - { "value", (double)(*val)->load() } - }); + doc.push_back(Json::object{ + {"type", "StatisticItem"}, + {"name", item.d_name}, + {"value", (double)(*val)->load()}}); } else if (const auto& adval = std::get_if*>(&item.d_value)) { - doc.push_back(Json::object { - { "type", "StatisticItem" }, - { "name", item.d_name }, - { "value", (*adval)->load() } - }); + doc.push_back(Json::object{ + {"type", "StatisticItem"}, + {"name", item.d_name}, + {"value", (*adval)->load()}}); } else if (const auto& dval = std::get_if(&item.d_value)) { - doc.push_back(Json::object { - { "type", "StatisticItem" }, - { "name", item.d_name }, - { "value", (**dval) } - }); + doc.push_back(Json::object{ + {"type", "StatisticItem"}, + {"name", item.d_name}, + {"value", (**dval)}}); } else if (const auto& func = std::get_if(&item.d_value)) { - doc.push_back(Json::object { - { "type", "StatisticItem" }, - { "name", item.d_name }, - { "value", (double)(*func)(item.d_name) } - }); + doc.push_back(Json::object{ + {"type", "StatisticItem"}, + {"name", item.d_name}, + {"value", (double)(*func)(item.d_name)}}); } } } @@ -1439,44 +1430,40 @@ static void handleConfigDump(const YaHTTP::Request& req, YaHTTP::Response& resp) Json::array doc; typedef boost::variant configentry_t; - std::vector > 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) { + std::vector> 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(&item.second)) { - doc.push_back(Json::object { - { "type", "ConfigSetting" }, - { "name", item.first }, - { "value", *bval } - }); + doc.push_back(Json::object{ + {"type", "ConfigSetting"}, + {"name", item.first}, + {"value", *bval}}); } else if (const auto& sval = boost::get(&item.second)) { - doc.push_back(Json::object { - { "type", "ConfigSetting" }, - { "name", item.first }, - { "value", *sval } - }); + doc.push_back(Json::object{ + {"type", "ConfigSetting"}, + {"name", item.first}, + {"value", *sval}}); } else if (const auto& dval = boost::get(&item.second)) { - doc.push_back(Json::object { - { "type", "ConfigSetting" }, - { "name", item.first }, - { "value", *dval } - }); + doc.push_back(Json::object{ + {"type", "ConfigSetting"}, + {"name", item.first}, + {"value", *dval}}); } } Json my_json = doc; @@ -1503,7 +1490,8 @@ static void handleAllowFrom(const YaHTTP::Request& req, YaHTTP::Response& resp) for (const auto& value : aclList.array_items()) { try { nmg.addMask(value.string_value()); - } catch (NetmaskException &e) { + } + catch (NetmaskException& e) { resp.status = 400; break; } @@ -1527,10 +1515,9 @@ static void handleAllowFrom(const YaHTTP::Request& req, YaHTTP::Response& resp) auto aclEntries = g_ACL.getLocal()->toStringVector(); Json::object obj{ - { "type", "ConfigSetting" }, - { "name", "allow-from" }, - { "value", aclEntries } - }; + {"type", "ConfigSetting"}, + {"name", "allow-from"}, + {"value", aclEntries}}; Json my_json = obj; resp.body = my_json.dump(); } @@ -1548,9 +1535,8 @@ static void handleCacheManagement(const YaHTTP::Request& req, YaHTTP::Response& if (req.method != "DELETE") { resp.status = 400; Json::object obj{ - { "status", "denied" }, - { "error", "invalid method" } - }; + {"status", "denied"}, + {"error", "invalid method"}}; resp.body = Json(obj).dump(); return; } @@ -1562,8 +1548,8 @@ static void handleCacheManagement(const YaHTTP::Request& req, YaHTTP::Response& if (poolName == req.getvars.end() || expungeName == req.getvars.end()) { resp.status = 400; Json::object obj{ - { "status", "denied" }, - { "error", "missing 'pool' or 'name' parameter" }, + {"status", "denied"}, + {"error", "missing 'pool' or 'name' parameter"}, }; resp.body = Json(obj).dump(); return; @@ -1577,8 +1563,8 @@ static void handleCacheManagement(const YaHTTP::Request& req, YaHTTP::Response& catch (const std::exception& e) { resp.status = 400; Json::object obj{ - { "status", "error" }, - { "error", "unable to parse the requested name" }, + {"status", "error"}, + {"error", "unable to parse the requested name"}, }; resp.body = Json(obj).dump(); return; @@ -1594,8 +1580,8 @@ static void handleCacheManagement(const YaHTTP::Request& req, YaHTTP::Response& catch (const std::exception& e) { resp.status = 404; Json::object obj{ - { "status", "not found" }, - { "error", "the requested pool does not exist" }, + {"status", "not found"}, + {"error", "the requested pool does not exist"}, }; resp.body = Json(obj).dump(); return; @@ -1605,8 +1591,8 @@ static void handleCacheManagement(const YaHTTP::Request& req, YaHTTP::Response& if (cache == nullptr) { resp.status = 404; Json::object obj{ - { "status", "not found" }, - { "error", "there is no cache associated with the requested pool" }, + {"status", "not found"}, + {"error", "there is no cache associated with the requested pool"}, }; resp.body = Json(obj).dump(); return; @@ -1615,25 +1601,25 @@ static void handleCacheManagement(const YaHTTP::Request& req, YaHTTP::Response& auto removed = cache->expungeByName(name, type.getCode(), suffix != req.getvars.end()); Json::object obj{ - { "status", "purged" }, - { "count", std::to_string(removed) } - }; + {"status", "purged"}, + {"count", std::to_string(removed)}}; resp.body = Json(obj).dump(); } #endif /* DISABLE_WEB_CACHE_MANAGEMENT */ -template static void addRingEntryToList(const struct timespec& now, Json::array& list, const T& entry) +template +static void addRingEntryToList(const struct timespec& now, Json::array& list, const T& entry) { constexpr bool response = std::is_same_v; Json::object tmp{ - { "age", static_cast(DiffTime(entry.when, now)) }, - { "id", ntohs(entry.dh.id) }, - { "name", entry.name.toString() }, - { "requestor", entry.requestor.toStringWithPort() }, - { "size", static_cast(entry.size) }, - { "qtype", entry.qtype }, - { "protocol", entry.protocol.toString() }, - { "rd", static_cast(entry.dh.rd) }, + {"age", static_cast(DiffTime(entry.when, now))}, + {"id", ntohs(entry.dh.id)}, + {"name", entry.name.toString()}, + {"requestor", entry.requestor.toStringWithPort()}, + {"size", static_cast(entry.size)}, + {"qtype", entry.qtype}, + {"protocol", entry.protocol.toString()}, + {"rd", static_cast(entry.dh.rd)}, }; if constexpr (!response) { #if defined(DNSDIST_RINGS_WITH_MACADDRESS) @@ -1747,20 +1733,20 @@ static void redirectToIndex(const YaHTTP::Request& req, YaHTTP::Response& resp) static void handleBuiltInFiles(const YaHTTP::Request& req, YaHTTP::Response& resp) { - if (req.url.path.empty() || !s_urlmap.count(req.url.path.c_str()+1)) { + 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)); + resp.body.assign(s_urlmap.at(req.url.path.c_str() + 1)); vector parts; stringtok(parts, req.url.path, "."); static const std::unordered_map contentTypeMap = { - { "html", "text/html" }, - { "css", "text/css" }, - { "js", "application/javascript" }, - { "png", "image/png" }, + {"html", "text/html"}, + {"css", "text/css"}, + {"js", "application/javascript"}, + {"png", "image/png"}, }; const auto& it = contentTypeMap.find(parts.back()); @@ -1820,7 +1806,8 @@ static void connectionThread(WebClientConnection&& conn) if (bytes > 0) { string data = string(buf, bytes); finished = yarl.feed(data); - } else { + } + else { // read error OR EOF break; } @@ -1893,7 +1880,8 @@ void setWebserverAPIKey(std::unique_ptr&& apiKey) if (apiKey) { config->apiKey = std::move(apiKey); - } else { + } + else { config->apiKey.reset(); } } @@ -1911,7 +1899,7 @@ void setWebserverACL(const std::string& acl) g_webserverConfig.lock()->acl = std::move(newACL); } -void setWebserverCustomHeaders(const boost::optional > customHeaders) +void setWebserverCustomHeaders(const boost::optional> customHeaders) { g_webserverConfig.lock()->customHeaders = customHeaders; } diff --git a/pdns/dnsdistdist/dnsdist-xpf.cc b/pdns/dnsdistdist/dnsdist-xpf.cc index eb2ba5785571..305bf0433e48 100644 --- a/pdns/dnsdistdist/dnsdist-xpf.cc +++ b/pdns/dnsdistdist/dnsdist-xpf.cc @@ -53,7 +53,7 @@ bool addXPF(DNSQuestion& dq, uint16_t optionCode) pos += sizeof(drh); memcpy(reinterpret_cast(&data.at(pos)), payload.data(), payload.size()); pos += payload.size(); - (void) pos; + (void)pos; dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [](dnsheader& header) { header.arcount = htons(ntohs(header.arcount) + 1); diff --git a/pdns/dnsdistdist/dnsdist-xpf.hh b/pdns/dnsdistdist/dnsdist-xpf.hh index 2e66f655880a..30de2234c0db 100644 --- a/pdns/dnsdistdist/dnsdist-xpf.hh +++ b/pdns/dnsdistdist/dnsdist-xpf.hh @@ -24,4 +24,3 @@ #include "dnsdist.hh" bool addXPF(DNSQuestion& dq, uint16_t optionCode); - diff --git a/pdns/dnsdistdist/dnsdist.cc b/pdns/dnsdistdist/dnsdist.cc index 6f0d4080ab8a..97f834ffd980 100644 --- a/pdns/dnsdistdist/dnsdist.cc +++ b/pdns/dnsdistdist/dnsdist.cc @@ -34,7 +34,7 @@ #include #ifdef HAVE_LIBEDIT -#if defined (__OpenBSD__) || defined(__NetBSD__) +#if defined(__OpenBSD__) || defined(__NetBSD__) // If this is not undeffed, __attribute__ wil be redefined by /usr/include/readline/rlstdc.h #undef __STRICT_ANSI__ #include @@ -117,7 +117,7 @@ std::vector> g_doh3locals; std::vector> g_dnsCryptLocals; shared_ptr g_defaultBPFFilter{nullptr}; -std::vector > g_dynBPFFilters; +std::vector> g_dynBPFFilters; std::vector> g_frontends; GlobalStateHolder g_pools; @@ -138,11 +138,11 @@ std::vector g_TCPFastOpenKey; IDs are assigned by atomic increments of the socket offset. */ -GlobalStateHolder > g_ruleactions; -GlobalStateHolder > g_respruleactions; -GlobalStateHolder > g_cachehitrespruleactions; -GlobalStateHolder > g_cacheInsertedRespRuleActions; -GlobalStateHolder > g_selfansweredrespruleactions; +GlobalStateHolder> g_ruleactions; +GlobalStateHolder> g_respruleactions; +GlobalStateHolder> g_cachehitrespruleactions; +GlobalStateHolder> g_cacheInsertedRespRuleActions; +GlobalStateHolder> g_selfansweredrespruleactions; Rings g_rings; QueryCount g_qcount; @@ -185,15 +185,14 @@ static ssize_t sendfromto(int sock, const void* data, size_t len, int flags, con addCMsgSrcAddr(&msgh, &cbuf, &from, 0); } else { - msgh.msg_control=nullptr; + msgh.msg_control = nullptr; } return sendmsg(sock, &msgh, flags); } static void truncateTC(PacketBuffer& packet, size_t maximumSize, unsigned int qnameWireLength) { - try - { + try { bool hadEDNS = false; uint16_t payloadSize = 0; uint16_t z = 0; @@ -202,7 +201,7 @@ static void truncateTC(PacketBuffer& packet, size_t maximumSize, unsigned int qn hadEDNS = getEDNSUDPPayloadSizeAndZ(reinterpret_cast(packet.data()), packet.size(), &payloadSize, &z); } - packet.resize(static_cast(sizeof(dnsheader)+qnameWireLength+DNS_TYPE_SIZE+DNS_CLASS_SIZE)); + packet.resize(static_cast(sizeof(dnsheader) + qnameWireLength + DNS_TYPE_SIZE + DNS_CLASS_SIZE)); dnsdist::PacketMangling::editDNSHeaderFromPacket(packet, [](dnsheader& header) { header.ancount = 0; header.arcount = 0; @@ -214,8 +213,7 @@ static void truncateTC(PacketBuffer& packet, size_t maximumSize, unsigned int qn addEDNS(packet, maximumSize, z & EDNS_HEADER_FLAG_DO, payloadSize, 0); } } - catch(...) - { + catch (...) { ++dnsdist::metrics::g_stats.truncFail; } } @@ -273,7 +271,7 @@ bool DNSQuestion::editHeader(const std::function& editFunction static void doLatencyStats(dnsdist::Protocol protocol, double udiff) { constexpr auto doAvg = [](double& var, double n, double weight) { - var = (weight -1) * var/weight + n/weight; + var = (weight - 1) * var / weight + n / weight; }; if (protocol == dnsdist::Protocol::DoUDP || protocol == dnsdist::Protocol::DNSCryptUDP) { @@ -299,39 +297,39 @@ static void doLatencyStats(dnsdist::Protocol protocol, double udiff) dnsdist::metrics::g_stats.latencySum += udiff / 1000; ++dnsdist::metrics::g_stats.latencyCount; - doAvg(dnsdist::metrics::g_stats.latencyAvg100, udiff, 100); - doAvg(dnsdist::metrics::g_stats.latencyAvg1000, udiff, 1000); - doAvg(dnsdist::metrics::g_stats.latencyAvg10000, udiff, 10000); + doAvg(dnsdist::metrics::g_stats.latencyAvg100, udiff, 100); + doAvg(dnsdist::metrics::g_stats.latencyAvg1000, udiff, 1000); + doAvg(dnsdist::metrics::g_stats.latencyAvg10000, udiff, 10000); doAvg(dnsdist::metrics::g_stats.latencyAvg1000000, udiff, 1000000); } else if (protocol == dnsdist::Protocol::DoTCP || protocol == dnsdist::Protocol::DNSCryptTCP) { - doAvg(dnsdist::metrics::g_stats.latencyTCPAvg100, udiff, 100); - doAvg(dnsdist::metrics::g_stats.latencyTCPAvg1000, udiff, 1000); - doAvg(dnsdist::metrics::g_stats.latencyTCPAvg10000, udiff, 10000); + doAvg(dnsdist::metrics::g_stats.latencyTCPAvg100, udiff, 100); + doAvg(dnsdist::metrics::g_stats.latencyTCPAvg1000, udiff, 1000); + doAvg(dnsdist::metrics::g_stats.latencyTCPAvg10000, udiff, 10000); doAvg(dnsdist::metrics::g_stats.latencyTCPAvg1000000, udiff, 1000000); } else if (protocol == dnsdist::Protocol::DoT) { - doAvg(dnsdist::metrics::g_stats.latencyDoTAvg100, udiff, 100); - doAvg(dnsdist::metrics::g_stats.latencyDoTAvg1000, udiff, 1000); - doAvg(dnsdist::metrics::g_stats.latencyDoTAvg10000, udiff, 10000); + doAvg(dnsdist::metrics::g_stats.latencyDoTAvg100, udiff, 100); + doAvg(dnsdist::metrics::g_stats.latencyDoTAvg1000, udiff, 1000); + doAvg(dnsdist::metrics::g_stats.latencyDoTAvg10000, udiff, 10000); doAvg(dnsdist::metrics::g_stats.latencyDoTAvg1000000, udiff, 1000000); } else if (protocol == dnsdist::Protocol::DoH) { - doAvg(dnsdist::metrics::g_stats.latencyDoHAvg100, udiff, 100); - doAvg(dnsdist::metrics::g_stats.latencyDoHAvg1000, udiff, 1000); - doAvg(dnsdist::metrics::g_stats.latencyDoHAvg10000, udiff, 10000); + doAvg(dnsdist::metrics::g_stats.latencyDoHAvg100, udiff, 100); + doAvg(dnsdist::metrics::g_stats.latencyDoHAvg1000, udiff, 1000); + doAvg(dnsdist::metrics::g_stats.latencyDoHAvg10000, udiff, 10000); doAvg(dnsdist::metrics::g_stats.latencyDoHAvg1000000, udiff, 1000000); } else if (protocol == dnsdist::Protocol::DoQ) { - doAvg(dnsdist::metrics::g_stats.latencyDoQAvg100, udiff, 100); - doAvg(dnsdist::metrics::g_stats.latencyDoQAvg1000, udiff, 1000); - doAvg(dnsdist::metrics::g_stats.latencyDoQAvg10000, udiff, 10000); + doAvg(dnsdist::metrics::g_stats.latencyDoQAvg100, udiff, 100); + doAvg(dnsdist::metrics::g_stats.latencyDoQAvg1000, udiff, 1000); + doAvg(dnsdist::metrics::g_stats.latencyDoQAvg10000, udiff, 10000); doAvg(dnsdist::metrics::g_stats.latencyDoQAvg1000000, udiff, 1000000); } else if (protocol == dnsdist::Protocol::DoH3) { - doAvg(dnsdist::metrics::g_stats.latencyDoH3Avg100, udiff, 100); - doAvg(dnsdist::metrics::g_stats.latencyDoH3Avg1000, udiff, 1000); - doAvg(dnsdist::metrics::g_stats.latencyDoH3Avg10000, udiff, 10000); + doAvg(dnsdist::metrics::g_stats.latencyDoH3Avg100, udiff, 100); + doAvg(dnsdist::metrics::g_stats.latencyDoH3Avg1000, udiff, 1000); + doAvg(dnsdist::metrics::g_stats.latencyDoH3Avg10000, udiff, 10000); doAvg(dnsdist::metrics::g_stats.latencyDoH3Avg1000000, udiff, 1000000); } } @@ -814,107 +812,106 @@ bool processResponderPacket(std::shared_ptr& dss, PacketBuffer& void responderThread(std::shared_ptr dss) { try { - setThreadName("dnsdist/respond"); - auto localRespRuleActions = g_respruleactions.getLocal(); - auto localCacheInsertedRespRuleActions = g_cacheInsertedRespRuleActions.getLocal(); - const size_t initialBufferSize = getInitialUDPPacketBufferSize(false); - /* allocate one more byte so we can detect truncation */ - PacketBuffer response(initialBufferSize + 1); - uint16_t queryId = 0; - std::vector sockets; - sockets.reserve(dss->sockets.size()); - - for (;;) { - try { - if (dss->isStopped()) { - break; - } - - if (!dss->connected) { - /* the sockets are not connected yet, likely because we detected a problem, - tried to reconnect and it failed. We will try to reconnect after the next - successful health-check (unless reconnectOnUp is false), or when trying - to send in the UDP listener thread, but until then we simply need to wait. */ - dss->waitUntilConnected(); - continue; - } - - dss->pickSocketsReadyForReceiving(sockets); - - /* check a second time here because we might have waited quite a bit - since the first check */ - if (dss->isStopped()) { - break; - } - - for (const auto& fd : sockets) { - /* allocate one more byte so we can detect truncation */ - // NOLINTNEXTLINE(bugprone-use-after-move): resizing a vector has no preconditions so it is valid to do so after moving it - response.resize(initialBufferSize + 1); - ssize_t got = recv(fd, response.data(), response.size(), 0); - - if (got == 0 && dss->isStopped()) { + setThreadName("dnsdist/respond"); + auto localRespRuleActions = g_respruleactions.getLocal(); + auto localCacheInsertedRespRuleActions = g_cacheInsertedRespRuleActions.getLocal(); + const size_t initialBufferSize = getInitialUDPPacketBufferSize(false); + /* allocate one more byte so we can detect truncation */ + PacketBuffer response(initialBufferSize + 1); + uint16_t queryId = 0; + std::vector sockets; + sockets.reserve(dss->sockets.size()); + + for (;;) { + try { + if (dss->isStopped()) { break; } - if (got < 0 || static_cast(got) < sizeof(dnsheader) || static_cast(got) == (initialBufferSize + 1)) { + if (!dss->connected) { + /* the sockets are not connected yet, likely because we detected a problem, + tried to reconnect and it failed. We will try to reconnect after the next + successful health-check (unless reconnectOnUp is false), or when trying + to send in the UDP listener thread, but until then we simply need to wait. */ + dss->waitUntilConnected(); continue; } - response.resize(static_cast(got)); - const dnsheader_aligned dnsHeader(response.data()); - queryId = dnsHeader->id; + dss->pickSocketsReadyForReceiving(sockets); - auto ids = dss->getState(queryId); - if (!ids) { - continue; + /* check a second time here because we might have waited quite a bit + since the first check */ + if (dss->isStopped()) { + break; } - if (!ids->isXSK() && fd != ids->backendFD) { - dss->restoreState(queryId, std::move(*ids)); - continue; - } + for (const auto& fd : sockets) { + /* allocate one more byte so we can detect truncation */ + // NOLINTNEXTLINE(bugprone-use-after-move): resizing a vector has no preconditions so it is valid to do so after moving it + response.resize(initialBufferSize + 1); + ssize_t got = recv(fd, response.data(), response.size(), 0); - if (processResponderPacket(dss, response, *localRespRuleActions, *localCacheInsertedRespRuleActions, std::move(*ids)) && ids->isXSK() && ids->cs->xskInfo) { -#ifdef HAVE_XSK - auto& xskInfo = ids->cs->xskInfo; - auto xskPacket = xskInfo->getEmptyFrame(); - if (!xskPacket) { + if (got == 0 && dss->isStopped()) { + break; + } + + if (got < 0 || static_cast(got) < sizeof(dnsheader) || static_cast(got) == (initialBufferSize + 1)) { + continue; + } + + response.resize(static_cast(got)); + const dnsheader_aligned dnsHeader(response.data()); + queryId = dnsHeader->id; + + auto ids = dss->getState(queryId); + if (!ids) { continue; } - xskPacket->setHeader(ids->xskPacketHeader); - if (!xskPacket->setPayload(response)) { - } - if (ids->delayMsec > 0) { - xskPacket->addDelay(ids->delayMsec); + + if (!ids->isXSK() && fd != ids->backendFD) { + dss->restoreState(queryId, std::move(*ids)); + continue; } - xskPacket->updatePacket(); - xskInfo->pushToSendQueue(*xskPacket); - xskInfo->notifyXskSocket(); + + if (processResponderPacket(dss, response, *localRespRuleActions, *localCacheInsertedRespRuleActions, std::move(*ids)) && ids->isXSK() && ids->cs->xskInfo) { +#ifdef HAVE_XSK + auto& xskInfo = ids->cs->xskInfo; + auto xskPacket = xskInfo->getEmptyFrame(); + if (!xskPacket) { + continue; + } + xskPacket->setHeader(ids->xskPacketHeader); + if (!xskPacket->setPayload(response)) { + } + if (ids->delayMsec > 0) { + xskPacket->addDelay(ids->delayMsec); + } + xskPacket->updatePacket(); + xskInfo->pushToSendQueue(*xskPacket); + xskInfo->notifyXskSocket(); #endif /* HAVE_XSK */ + } } } - } - catch (const std::exception& e) { - vinfolog("Got an error in UDP responder thread while parsing a response from %s, id %d: %s", dss->d_config.remote.toStringWithPort(), queryId, e.what()); + catch (const std::exception& e) { + vinfolog("Got an error in UDP responder thread while parsing a response from %s, id %d: %s", dss->d_config.remote.toStringWithPort(), queryId, e.what()); + } } } -} -catch (const std::exception& e) { - errlog("UDP responder thread died because of exception: %s", e.what()); -} -catch (const PDNSException& e) { - errlog("UDP responder thread died because of PowerDNS exception: %s", e.reason); -} -catch (...) { - errlog("UDP responder thread died because of an exception: %s", "unknown"); -} + catch (const std::exception& e) { + errlog("UDP responder thread died because of exception: %s", e.what()); + } + catch (const PDNSException& e) { + errlog("UDP responder thread died because of PowerDNS exception: %s", e.reason); + } + catch (...) { + errlog("UDP responder thread died because of an exception: %s", "unknown"); + } } LockGuarded g_lua{LuaContext()}; ComboAddress g_serverControl{"127.0.0.1:5199"}; - static void spoofResponseFromString(DNSQuestion& dq, const string& spoofContent, bool raw) { string result; @@ -935,12 +932,13 @@ static void spoofResponseFromString(DNSQuestion& dq, const string& spoofContent, SpoofAction tempSpoofAction({spoofAddr}); tempSpoofAction(&dq, &result); } - catch(const PDNSException &e) { + catch (const PDNSException& e) { DNSName cname(spoofContent); SpoofAction tempSpoofAction(cname); // CNAME then tempSpoofAction(&dq, &result); } - } else { + } + else { std::vector cas; for (const auto& addr : addrs) { try { @@ -1054,7 +1052,6 @@ bool processRulesResult(const DNSAction::Action& action, DNSQuestion& dq, std::s return false; } - static bool applyRulesToQuery(LocalHolders& holders, DNSQuestion& dq, const struct timespec& now) { if (g_rings.shouldRecordQueries()) { @@ -1066,7 +1063,7 @@ static bool applyRulesToQuery(LocalHolders& holders, DNSQuestion& dq, const stru bool countQuery{true}; if (g_qcount.filter) { auto lock = g_lua.lock(); - std::tie (countQuery, qname) = g_qcount.filter(&dq); + std::tie(countQuery, qname) = g_qcount.filter(&dq); } if (countQuery) { @@ -1248,7 +1245,7 @@ ssize_t udpClientSendRequestToBackend(const std::shared_ptr& ss struct iovec iov; cmsgbuf_aligned cbuf; ComboAddress remote(ss->d_config.remote); - fillMSGHdr(&msgh, &iov, &cbuf, sizeof(cbuf), const_cast(reinterpret_cast(request.data())), request.size(), &remote); + fillMSGHdr(&msgh, &iov, &cbuf, sizeof(cbuf), const_cast(reinterpret_cast(request.data())), request.size(), &remote); addCMsgSrcAddr(&msgh, &cbuf, &ss->d_config.sourceAddr, ss->d_config.sourceItf); result = sendmsg(sd, &msgh, 0); } @@ -1341,7 +1338,7 @@ bool checkDNSCryptQuery(const ClientState& cs, PacketBuffer& query, std::unique_ bool checkQueryHeaders(const struct dnsheader& dnsHeader, ClientState& clientState) { - if (dnsHeader.qr) { // don't respond to responses + if (dnsHeader.qr) { // don't respond to responses ++dnsdist::metrics::g_stats.nonCompliantQueries; ++clientState.nonCompliantQueries; return false; @@ -1366,7 +1363,7 @@ bool checkQueryHeaders(const struct dnsheader& dnsHeader, ClientState& clientSta static void queueResponse(const ClientState& cs, const PacketBuffer& response, const ComboAddress& dest, const ComboAddress& remote, struct mmsghdr& outMsg, struct iovec* iov, cmsgbuf_aligned* cbuf) { outMsg.msg_len = 0; - fillMSGHdr(&outMsg.msg_hdr, iov, nullptr, 0, const_cast(reinterpret_cast(&response.at(0))), response.size(), const_cast(&remote)); + fillMSGHdr(&outMsg.msg_hdr, iov, nullptr, 0, const_cast(reinterpret_cast(&response.at(0))), response.size(), const_cast(&remote)); if (dest.sin4.sin_family == 0) { outMsg.msg_hdr.msg_control = nullptr; @@ -1499,7 +1496,7 @@ ProcessQueryResult processQueryAfterRules(DNSQuestion& dq, LocalHolders& holders yet, as we will do a second-lookup */ if (dq.ids.packetCache->get(dq, dq.getHeader()->id, &dq.ids.cacheKey, dq.ids.subnet, dq.ids.dnssecOK, forwardedOverUDP, allowExpired, false, true, dq.ids.protocol != dnsdist::Protocol::DoH || forwardedOverUDP)) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [flags=dq.ids.origFlags](dnsheader& header) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [flags = dq.ids.origFlags](dnsheader& header) { restoreFlags(&header, flags); return true; }); @@ -1574,7 +1571,7 @@ ProcessQueryResult processQueryAfterRules(DNSQuestion& dq, LocalHolders& holders selectedBackend->incQueriesCount(); return ProcessQueryResult::PassToBackend; } - catch (const std::exception& e){ + catch (const std::exception& e) { vinfolog("Got an error while parsing a %s query (after applying rules) from %s, id %d: %s", (dq.overTCP() ? "TCP" : "UDP"), dq.ids.origRemote.toStringWithPort(), queryId, e.what()); } return ProcessQueryResult::Drop; @@ -1624,7 +1621,8 @@ class UDPTCPCrossQuerySender : public TCPQuerySender class UDPCrossProtocolQuery : public CrossProtocolQuery { public: - UDPCrossProtocolQuery(PacketBuffer&& buffer_, InternalQueryState&& ids_, std::shared_ptr ds): CrossProtocolQuery(InternalQuery(std::move(buffer_), std::move(ids_)), ds) + UDPCrossProtocolQuery(PacketBuffer&& buffer_, InternalQueryState&& ids_, std::shared_ptr ds) : + CrossProtocolQuery(InternalQuery(std::move(buffer_), std::move(ids_)), ds) { auto& ids = query.d_idstate; const auto& buffer = query.d_buffer; @@ -1646,6 +1644,7 @@ class UDPCrossProtocolQuery : public CrossProtocolQuery { return s_sender; } + private: static std::shared_ptr s_sender; }; @@ -1680,7 +1679,7 @@ ProcessQueryResult processQuery(DNSQuestion& dq, LocalHolders& holders, std::sha return processQueryAfterRules(dq, holders, selectedBackend); } - catch (const std::exception& e){ + catch (const std::exception& e) { vinfolog("Got an error while parsing a %s query from %s, id %d: %s", (dq.overTCP() ? "TCP" : "UDP"), dq.ids.origRemote.toStringWithPort(), queryId, e.what()); } return ProcessQueryResult::Drop; @@ -1877,7 +1876,7 @@ static void processUDPQuery(ClientState& cs, LocalHolders& holders, const struct assignOutgoingUDPQueryToBackend(ss, dh->id, dq, query); } - catch(const std::exception& e){ + catch (const std::exception& e) { vinfolog("Got an error in UDP question thread while parsing a query from %s, id %d: %s", ids.origRemote.toStringWithPort(), queryId, e.what()); } } @@ -2050,7 +2049,7 @@ static void MultipleMessagesUDPClientThread(ClientState* cs, LocalHolders& holde } /* go now */ - for(;;) { + for (;;) { /* reset the IO vector, since it's also used to send the vector of responses to avoid having to copy the data around */ @@ -2097,7 +2096,6 @@ static void MultipleMessagesUDPClientThread(ClientState* cs, LocalHolders& holde vinfolog("Error sending responses with sendmmsg() (%d on %u): %s", sent, msgsToSend, stringerror()); } } - } } #endif /* defined(HAVE_RECVMMSG) && defined(HAVE_SENDMMSG) && defined(MSG_WAITFORONE) */ @@ -2210,10 +2208,10 @@ static void udpClientThread(std::vector states) } } } - catch (const std::exception &e) { + catch (const std::exception& e) { errlog("UDP client thread died because of exception: %s", e.what()); } - catch (const PDNSException &e) { + catch (const PDNSException& e) { errlog("UDP client thread died because of PowerDNS exception: %s", e.reason); } catch (...) { @@ -2238,14 +2236,14 @@ static void maintThread() { auto lua = g_lua.lock(); try { - auto maintenanceCallback = lua->readVariable > >("maintenance"); + auto maintenanceCallback = lua->readVariable>>("maintenance"); if (maintenanceCallback) { (*maintenanceCallback)(); } dnsdist::lua::hooks::runMaintenanceHooks(*lua); secondsToWaitLog = 0; } - catch (const std::exception &e) { + catch (const std::exception& e) { if (secondsToWaitLog <= 0) { warnlog("Error during execution of maintenance function(s): %s", e.what()); secondsToWaitLog = 61; @@ -2291,7 +2289,7 @@ static void maintThread() continue; } const auto& packetCache = pair.first; - size_t upTo = (packetCache->getMaxEntries()* (100 - g_cacheCleaningPercentage)) / 100; + size_t upTo = (packetCache->getMaxEntries() * (100 - g_cacheCleaningPercentage)) / 100; packetCache->purgeExpired(upTo, now); } counter = 0; @@ -2317,7 +2315,7 @@ static void secPollThread() try { doSecPoll(g_secPollSuffix); } - catch(...) { + catch (...) { } // coverity[store_truncates_time_t] sleep(g_secPollInterval); @@ -2330,7 +2328,8 @@ static void healthChecksThread() setThreadName("dnsdist/healthC"); constexpr int intervalUsec = 1000 * 1000; - struct timeval lastRound{ + struct timeval lastRound + { .tv_sec = 0, .tv_usec = 0 }; @@ -2475,7 +2474,7 @@ static bool g_warned_ipv6_recvpktinfo = false; static void setupLocalSocket(ClientState& clientState, const ComboAddress& addr, int& socket, bool tcp, bool warn) { - (void) warn; + (void)warn; socket = SSocket(addr.sin4.sin_family, !tcp ? SOCK_DGRAM : SOCK_STREAM, 0); if (tcp) { @@ -2510,10 +2509,9 @@ static void setupLocalSocket(ClientState& clientState, const ComboAddress& addr, if (!tcp && IsAnyAddress(addr)) { int one = 1; - (void) setsockopt(socket, IPPROTO_IP, GEN_IP_PKTINFO, &one, sizeof(one)); // linux supports this, so why not - might fail on other systems + (void)setsockopt(socket, IPPROTO_IP, GEN_IP_PKTINFO, &one, sizeof(one)); // linux supports this, so why not - might fail on other systems #ifdef IPV6_RECVPKTINFO - if (addr.isIPv6() && setsockopt(socket, IPPROTO_IPV6, IPV6_RECVPKTINFO, &one, sizeof(one)) < 0 && - !g_warned_ipv6_recvpktinfo) { + if (addr.isIPv6() && setsockopt(socket, IPPROTO_IPV6, IPV6_RECVPKTINFO, &one, sizeof(one)) < 0 && !g_warned_ipv6_recvpktinfo) { warnlog("Warning: IPV6_RECVPKTINFO setsockopt failed: %s", stringerror()); g_warned_ipv6_recvpktinfo = true; } @@ -2559,13 +2557,15 @@ static void setupLocalSocket(ClientState& clientState, const ComboAddress& addr, catch (const std::exception& e) { warnlog(e.what()); } - } else { + } + else { try { auto result = raiseSocketSendBufferToMax(socket); if (result > 0) { infolog("Raised send buffer to %u for local address '%s'", result, addr.toStringWithPort()); } - } catch (const std::exception& e) { + } + catch (const std::exception& e) { warnlog(e.what()); } } @@ -2577,13 +2577,15 @@ static void setupLocalSocket(ClientState& clientState, const ComboAddress& addr, catch (const std::exception& e) { warnlog(e.what()); } - } else { + } + else { try { auto result = raiseSocketReceiveBufferToMax(socket); if (result > 0) { infolog("Raised receive buffer to %u for local address '%s'", result, addr.toStringWithPort()); } - } catch (const std::exception& e) { + } + catch (const std::exception& e) { warnlog(e.what()); } } @@ -2627,10 +2629,12 @@ static void setupLocalSocket(ClientState& clientState, const ComboAddress& addr, else { infolog("Listening on %s", addr.toStringWithPort()); } - } else { + } + else { if (clientState.doqFrontend != nullptr) { infolog("Listening on %s for DoQ", addr.toStringWithPort()); - } else if (clientState.doh3Frontend != nullptr) { + } + else if (clientState.doh3Frontend != nullptr) { infolog("Listening on %s for DoH3", addr.toStringWithPort()); } #ifdef HAVE_XSK @@ -2646,7 +2650,7 @@ static void setUpLocalBind(std::unique_ptr& cstate) /* skip some warnings if there is an identical UDP context */ bool warn = !cstate->tcp || cstate->tlsFrontend != nullptr || cstate->dohFrontend != nullptr; int& descriptor = !cstate->tcp ? cstate->udpFD : cstate->tcpFD; - (void) warn; + (void)warn; setupLocalSocket(*cstate, cstate->local, descriptor, cstate->tcp, warn); @@ -2691,37 +2695,37 @@ std::atomic g_configurationDone{false}; static void usage() { - cout< longopts{{ - {"acl", required_argument, nullptr, 'a'}, - {"check-config", no_argument, nullptr, 1}, - {"client", no_argument, nullptr, 'c'}, - {"config", required_argument, nullptr, 'C'}, - {"disable-syslog", no_argument, nullptr, 2}, - {"execute", required_argument, nullptr, 'e'}, - {"gid", required_argument, nullptr, 'g'}, - {"help", no_argument, nullptr, 'h'}, - {"local", required_argument, nullptr, 'l'}, - {"log-timestamps", no_argument, nullptr, 4}, - {"setkey", required_argument, nullptr, 'k'}, - {"supervised", no_argument, nullptr, 3}, - {"uid", required_argument, nullptr, 'u'}, - {"verbose", no_argument, nullptr, 'v'}, - {"version", no_argument, nullptr, 'V'}, - {nullptr, 0, nullptr, 0} - }}; + const std::array longopts{{{"acl", required_argument, nullptr, 'a'}, + {"check-config", no_argument, nullptr, 1}, + {"client", no_argument, nullptr, 'c'}, + {"config", required_argument, nullptr, 'C'}, + {"disable-syslog", no_argument, nullptr, 2}, + {"execute", required_argument, nullptr, 'e'}, + {"gid", required_argument, nullptr, 'g'}, + {"help", no_argument, nullptr, 'h'}, + {"local", required_argument, nullptr, 'l'}, + {"log-timestamps", no_argument, nullptr, 4}, + {"setkey", required_argument, nullptr, 'k'}, + {"supervised", no_argument, nullptr, 3}, + {"uid", required_argument, nullptr, 'u'}, + {"verbose", no_argument, nullptr, 'v'}, + {"version", no_argument, nullptr, 'V'}, + {nullptr, 0, nullptr, 0}}}; int longindex = 0; string optstring; while (true) { @@ -2917,9 +2919,9 @@ static void parseParameters(int argc, char** argv, ComboAddress& clientAddress) g_cmdLine.gid = optarg; break; case 'h': - cout<<"dnsdist "<getName() == "chashed") { precompute = true; - } else { - for (const auto& entry: pools) { + } + else { + for (const auto& entry : pools) { if (entry.second->policy != nullptr && entry.second->policy->getName() == "chashed") { precompute = true; - break ; + break; } } } @@ -2994,7 +2998,7 @@ static void setupPools() vinfolog("Pre-computing hashes for consistent hash load-balancing policy"); // pre compute hashes auto backends = g_dstates.getLocal(); - for (const auto& backend: *backends) { + for (const auto& backend : *backends) { if (backend->d_config.d_weight < 100) { vinfolog("Warning, the backend '%s' has a very low weight (%d), which will not yield a good distribution of queries with the 'chashed' policy. Please consider raising it to at least '100'.", backend->getName(), backend->d_config.d_weight); } @@ -3019,8 +3023,7 @@ static void dropPrivileges() } bool retainedCapabilities = true; - if (!g_capabilitiesToRetain.empty() && - (getegid() != newgid || geteuid() != newuid)) { + if (!g_capabilitiesToRetain.empty() && (getegid() != newgid || geteuid() != newuid)) { retainedCapabilities = keepCapabilitiesAfterSwitchingIDs(); } @@ -3061,7 +3064,7 @@ static void dropPrivileges() static void initFrontends() { if (!g_cmdLine.locals.empty()) { - for (auto it = g_frontends.begin(); it != g_frontends.end(); ) { + for (auto it = g_frontends.begin(); it != g_frontends.end();) { /* DoH, DoT and DNSCrypt frontends are separate */ if ((*it)->dohFrontend == nullptr && (*it)->tlsFrontend == nullptr && (*it)->dnscryptCtx == nullptr && (*it)->doqFrontend == nullptr && (*it)->doh3Frontend == nullptr) { it = g_frontends.erase(it); @@ -3081,9 +3084,9 @@ static void initFrontends() if (g_frontends.empty()) { /* UDP */ - g_frontends.emplace_back(std::make_unique(ComboAddress("127.0.0.1", 53), false, false, 0, "", std::set{}, true)); + g_frontends.emplace_back(std::make_unique(ComboAddress("127.0.0.1", 53), false, false, 0, "", std::set{}, true)); /* TCP */ - g_frontends.emplace_back(std::make_unique(ComboAddress("127.0.0.1", 53), true, false, 0, "", std::set{}, true)); + g_frontends.emplace_back(std::make_unique(ComboAddress("127.0.0.1", 53), true, false, 0, "", std::set{}, true)); } } @@ -3123,59 +3126,59 @@ static void startFrontends() dotThreadHandle.detach(); #endif /* HAVE_LIBH2OEVLOOP */ #endif /* HAVE_DNS_OVER_HTTPS */ - continue; - } - if (clientState->doqFrontend != nullptr) { + continue; + } + if (clientState->doqFrontend != nullptr) { #ifdef HAVE_DNS_OVER_QUIC - std::thread doqThreadHandle(doqThread, clientState.get()); - if (!clientState->cpus.empty()) { - mapThreadToCPUList(doqThreadHandle.native_handle(), clientState->cpus); - } - doqThreadHandle.detach(); -#endif /* HAVE_DNS_OVER_QUIC */ - continue; + std::thread doqThreadHandle(doqThread, clientState.get()); + if (!clientState->cpus.empty()) { + mapThreadToCPUList(doqThreadHandle.native_handle(), clientState->cpus); } - if (clientState->doh3Frontend != nullptr) { + doqThreadHandle.detach(); +#endif /* HAVE_DNS_OVER_QUIC */ + continue; + } + if (clientState->doh3Frontend != nullptr) { #ifdef HAVE_DNS_OVER_HTTP3 - std::thread doh3ThreadHandle(doh3Thread, clientState.get()); - if (!clientState->cpus.empty()) { - mapThreadToCPUList(doh3ThreadHandle.native_handle(), clientState->cpus); - } - doh3ThreadHandle.detach(); -#endif /* HAVE_DNS_OVER_HTTP3 */ - continue; + std::thread doh3ThreadHandle(doh3Thread, clientState.get()); + if (!clientState->cpus.empty()) { + mapThreadToCPUList(doh3ThreadHandle.native_handle(), clientState->cpus); } - if (clientState->udpFD >= 0) { + doh3ThreadHandle.detach(); +#endif /* HAVE_DNS_OVER_HTTP3 */ + continue; + } + if (clientState->udpFD >= 0) { #ifdef USE_SINGLE_ACCEPTOR_THREAD - udpStates.push_back(clientState.get()); + udpStates.push_back(clientState.get()); #else /* USE_SINGLE_ACCEPTOR_THREAD */ - std::thread udpClientThreadHandle(udpClientThread, std::vector{ clientState.get() }); - if (!clientState->cpus.empty()) { - mapThreadToCPUList(udpClientThreadHandle.native_handle(), clientState->cpus); - } - udpClientThreadHandle.detach(); -#endif /* USE_SINGLE_ACCEPTOR_THREAD */ + std::thread udpClientThreadHandle(udpClientThread, std::vector{clientState.get()}); + if (!clientState->cpus.empty()) { + mapThreadToCPUList(udpClientThreadHandle.native_handle(), clientState->cpus); } - else if (clientState->tcpFD >= 0) { + udpClientThreadHandle.detach(); +#endif /* USE_SINGLE_ACCEPTOR_THREAD */ + } + else if (clientState->tcpFD >= 0) { #ifdef USE_SINGLE_ACCEPTOR_THREAD - tcpStates.push_back(clientState.get()); + tcpStates.push_back(clientState.get()); #else /* USE_SINGLE_ACCEPTOR_THREAD */ - std::thread tcpAcceptorThreadHandle(tcpAcceptorThread, std::vector{clientState.get() }); - if (!clientState->cpus.empty()) { - mapThreadToCPUList(tcpAcceptorThreadHandle.native_handle(), clientState->cpus); - } - tcpAcceptorThreadHandle.detach(); -#endif /* USE_SINGLE_ACCEPTOR_THREAD */ + std::thread tcpAcceptorThreadHandle(tcpAcceptorThread, std::vector{clientState.get()}); + if (!clientState->cpus.empty()) { + mapThreadToCPUList(tcpAcceptorThreadHandle.native_handle(), clientState->cpus); } + tcpAcceptorThreadHandle.detach(); +#endif /* USE_SINGLE_ACCEPTOR_THREAD */ } + } #ifdef USE_SINGLE_ACCEPTOR_THREAD - if (!udpStates.empty()) { - std::thread udpThreadHandle(udpClientThread, udpStates); - udpThreadHandle.detach(); - } - if (!tcpStates.empty()) { - g_tcpclientthreads = std::make_unique(1, tcpStates); - } + if (!udpStates.empty()) { + std::thread udpThreadHandle(udpClientThread, udpStates); + udpThreadHandle.detach(); + } + if (!tcpStates.empty()) { + g_tcpclientthreads = std::make_unique(1, tcpStates); + } #endif /* USE_SINGLE_ACCEPTOR_THREAD */ } } @@ -3198,11 +3201,11 @@ int main(int argc, char** argv) signal(SIGCHLD, SIG_IGN); signal(SIGTERM, sigTermHandler); - openlog("dnsdist", LOG_PID|LOG_NDELAY, LOG_DAEMON); + openlog("dnsdist", LOG_PID | LOG_NDELAY, LOG_DAEMON); #ifdef HAVE_LIBSODIUM if (sodium_init() == -1) { - cerr<<"Unable to initialize crypto library"<(); } ids.qTag->insert_or_assign(std::move(key), std::move(value)); } - void setTag(const std::string& key, const std::string& value) { + void setTag(const std::string& key, const std::string& value) + { if (!ids.qTag) { ids.qTag = std::make_unique(); } ids.qTag->insert_or_assign(key, value); } - void setTag(const std::string& key, std::string&& value) { + void setTag(const std::string& key, std::string&& value) + { if (!ids.qTag) { ids.qTag = std::make_unique(); } @@ -198,8 +202,8 @@ struct DownstreamState; struct DNSResponse : DNSQuestion { - DNSResponse(InternalQueryState& ids_, PacketBuffer& data_, const std::shared_ptr& downstream): - DNSQuestion(ids_, data_), d_downstream(downstream) { } + DNSResponse(InternalQueryState& ids_, PacketBuffer& data_, const std::shared_ptr& downstream) : + DNSQuestion(ids_, data_), d_downstream(downstream) {} DNSResponse(const DNSResponse&) = delete; DNSResponse& operator=(const DNSResponse&) = delete; DNSResponse(DNSResponse&&) = default; @@ -219,10 +223,27 @@ struct DNSResponse : DNSQuestion class DNSAction { public: - enum class Action : uint8_t { Drop, Nxdomain, Refused, Spoof, Allow, HeaderModify, Pool, Delay, Truncate, ServFail, None, NoOp, NoRecurse, SpoofRaw, SpoofPacket }; + enum class Action : uint8_t + { + Drop, + Nxdomain, + Refused, + Spoof, + Allow, + HeaderModify, + Pool, + Delay, + Truncate, + ServFail, + None, + NoOp, + NoRecurse, + SpoofRaw, + SpoofPacket + }; static std::string typeToString(const Action& action) { - switch(action) { + switch (action) { case Action::Drop: return "Drop"; case Action::Nxdomain: @@ -257,7 +278,7 @@ public: return "Unknown"; } - virtual Action operator()(DNSQuestion*, string* ruleresult) const =0; + virtual Action operator()(DNSQuestion*, string* ruleresult) const = 0; virtual ~DNSAction() { } @@ -274,8 +295,17 @@ public: class DNSResponseAction { public: - enum class Action : uint8_t { Allow, Delay, Drop, HeaderModify, ServFail, Truncate, None }; - virtual Action operator()(DNSResponse*, string* ruleresult) const =0; + enum class Action : uint8_t + { + Allow, + Delay, + Drop, + HeaderModify, + ServFail, + Truncate, + None + }; + virtual Action operator()(DNSResponse*, string* ruleresult) const = 0; virtual ~DNSResponseAction() { } @@ -287,22 +317,26 @@ public: struct DynBlock { - DynBlock(): action(DNSAction::Action::None), warning(false) + DynBlock() : + action(DNSAction::Action::None), warning(false) { until.tv_sec = 0; until.tv_nsec = 0; } - DynBlock(const std::string& reason_, const struct timespec& until_, const DNSName& domain_, DNSAction::Action action_): reason(reason_), domain(domain_), until(until_), action(action_), warning(false) + DynBlock(const std::string& reason_, const struct timespec& until_, const DNSName& domain_, DNSAction::Action action_) : + reason(reason_), domain(domain_), until(until_), action(action_), warning(false) { } - DynBlock(const DynBlock& rhs): reason(rhs.reason), domain(rhs.domain), until(rhs.until), action(rhs.action), warning(rhs.warning), bpf(rhs.bpf) + DynBlock(const DynBlock& rhs) : + reason(rhs.reason), domain(rhs.domain), until(rhs.until), action(rhs.action), warning(rhs.warning), bpf(rhs.bpf) { blocks.store(rhs.blocks); } - DynBlock(DynBlock&& rhs): reason(std::move(rhs.reason)), domain(std::move(rhs.domain)), until(rhs.until), action(rhs.action), warning(rhs.warning), bpf(rhs.bpf) + DynBlock(DynBlock&& rhs) : + reason(std::move(rhs.reason)), domain(std::move(rhs.domain)), until(rhs.until), action(rhs.action), warning(rhs.warning), bpf(rhs.bpf) { blocks.store(rhs.blocks); } @@ -342,7 +376,7 @@ struct DynBlock extern GlobalStateHolder> g_dynblockNMG; -extern vector > g_confDelta; +extern vector> g_confDelta; using pdns::stat_t; @@ -353,7 +387,8 @@ public: { } - BasicQPSLimiter(unsigned int burst): d_tokens(burst) + BasicQPSLimiter(unsigned int burst) : + d_tokens(burst) { d_prev.start(); } @@ -377,7 +412,7 @@ public: auto delta = d_prev.udiffAndSet(); if (delta > 0.0) { // time, frequently, does go backwards.. - d_tokens += 1.0 * rate * (delta/1000000.0); + d_tokens += 1.0 * rate * (delta / 1000000.0); } if (d_tokens > burst) { @@ -410,11 +445,13 @@ protected: class QPSLimiter : public BasicQPSLimiter { public: - QPSLimiter(): BasicQPSLimiter() + QPSLimiter() : + BasicQPSLimiter() { } - QPSLimiter(unsigned int rate, unsigned int burst): BasicQPSLimiter(burst), d_rate(rate), d_burst(burst), d_passthrough(false) + QPSLimiter(unsigned int rate, unsigned int burst) : + BasicQPSLimiter(burst), d_rate(rate), d_burst(burst), d_passthrough(false) { d_prev.start(); } @@ -457,7 +494,8 @@ private: typedef std::unordered_map QueryCountRecords; typedef std::function(const DNSQuestion* dq)> QueryCountFilter; -struct QueryCount { +struct QueryCount +{ QueryCount() { } @@ -477,7 +515,8 @@ class XskWorker; struct ClientState { - ClientState(const ComboAddress& local_, bool isTCP_, bool doReusePort, int fastOpenQueue, const std::string& itfName, const std::set& cpus_, bool enableProxyProtocol): cpus(cpus_), interface(itfName), local(local_), fastOpenQueueSize(fastOpenQueue), tcp(isTCP_), reuseport(doReusePort), d_enableProxyProtocol(enableProxyProtocol) + ClientState(const ComboAddress& local_, bool isTCP_, bool doReusePort, int fastOpenQueue, const std::string& itfName, const std::set& cpus_, bool enableProxyProtocol) : + cpus(cpus_), interface(itfName), local(local_), fastOpenQueueSize(fastOpenQueue), tcp(isTCP_), reuseport(doReusePort), d_enableProxyProtocol(enableProxyProtocol) { } @@ -497,11 +536,11 @@ struct ClientState stat_t tlsResumptions{0}; // A TLS session has been resumed, either via session id or via a TLS ticket stat_t tlsUnknownTicketKey{0}; // A TLS ticket has been presented but we don't have the associated key (might have expired) stat_t tlsInactiveTicketKey{0}; // A TLS ticket has been successfully resumed but the key is no longer active, we should issue a new one - stat_t tls10queries{0}; // valid DNS queries received via TLSv1.0 - stat_t tls11queries{0}; // valid DNS queries received via TLSv1.1 - stat_t tls12queries{0}; // valid DNS queries received via TLSv1.2 - stat_t tls13queries{0}; // valid DNS queries received via TLSv1.3 - stat_t tlsUnknownqueries{0}; // valid DNS queries received via unknown TLS version + stat_t tls10queries{0}; // valid DNS queries received via TLSv1.0 + stat_t tls11queries{0}; // valid DNS queries received via TLSv1.1 + stat_t tls12queries{0}; // valid DNS queries received via TLSv1.2 + stat_t tls13queries{0}; // valid DNS queries received via TLSv1.3 + stat_t tlsUnknownqueries{0}; // valid DNS queries received via unknown TLS version pdns::stat_t_trait tcpAvgQueriesPerConnection{0.0}; /* in ms */ pdns::stat_t_trait tcpAvgConnectionDuration{0.0}; @@ -641,7 +680,7 @@ struct ClientState if (d_filter) { detachFilter(getSocket()); for (const auto& [addr, socket] : d_additionalAddresses) { - (void) addr; + (void)addr; if (socket != -1) { detachFilter(socket); } @@ -657,7 +696,7 @@ struct ClientState bpf->addSocket(getSocket()); for (const auto& [addr, socket] : d_additionalAddresses) { - (void) addr; + (void)addr; if (socket != -1) { bpf->addSocket(socket); } @@ -674,7 +713,7 @@ struct ClientState struct CrossProtocolQuery; -struct DownstreamState: public std::enable_shared_from_this +struct DownstreamState : public std::enable_shared_from_this { DownstreamState(const DownstreamState&) = delete; DownstreamState(DownstreamState&&) = delete; @@ -682,15 +721,26 @@ struct DownstreamState: public std::enable_shared_from_this DownstreamState& operator=(DownstreamState&&) = delete; typedef std::function(const DNSName&, uint16_t, uint16_t, dnsheader*)> checkfunc_t; - enum class Availability : uint8_t { Up, Down, Auto, Lazy }; - enum class LazyHealthCheckMode : uint8_t { TimeoutOnly, TimeoutOrServFail }; + enum class Availability : uint8_t + { + Up, + Down, + Auto, + Lazy + }; + enum class LazyHealthCheckMode : uint8_t + { + TimeoutOnly, + TimeoutOrServFail + }; struct Config { Config() { } - Config(const ComboAddress& remote_): remote(remote_) + Config(const ComboAddress& remote_) : + remote(remote_) { } @@ -764,7 +814,8 @@ struct DownstreamState: public std::enable_shared_from_this }; DownstreamState(DownstreamState::Config&& config, std::shared_ptr tlsCtx, bool connect); - DownstreamState(const ComboAddress& remote): DownstreamState(DownstreamState::Config(remote), nullptr, false) + DownstreamState(const ComboAddress& remote) : + DownstreamState(DownstreamState::Config(remote), nullptr, false) { } @@ -778,7 +829,8 @@ struct DownstreamState: public std::enable_shared_from_this stat_t queries{0}; stat_t responses{0}; stat_t nonCompliantResponses{0}; - struct { + struct + { stat_t sendErrors{0}; stat_t reuseds{0}; stat_t queries{0}; @@ -806,6 +858,7 @@ struct DownstreamState: public std::enable_shared_from_this SharedLockGuarded> hashes; LockGuarded> mplexer{nullptr}; + private: LockGuarded> d_idStatesMap; vector idStates; @@ -814,7 +867,12 @@ private: { boost::circular_buffer d_lastResults; time_t d_nextCheck{0}; - enum class LazyStatus: uint8_t { Healthy = 0, PotentialFailure, Failed }; + enum class LazyStatus : uint8_t + { + Healthy = 0, + PotentialFailure, + Failed + }; LazyStatus d_status{LazyStatus::Healthy}; }; LockGuarded d_lazyHealthCheckStats; @@ -855,6 +913,7 @@ private: std::atomic_flag threadStarted; uint8_t consecutiveSuccessfulChecks{0}; bool d_stopped{false}; + public: void updateStatisticsInfo() { @@ -877,7 +936,8 @@ public: return upStatus; } - void setUp() { + void setUp() + { d_config.availability = Availability::Up; } @@ -895,25 +955,29 @@ public: latencyUsec = 0.0; latencyUsecTCP = 0.0; } - void setAuto() { + void setAuto() + { d_config.availability = Availability::Auto; } - void setLazyAuto() { + void setLazyAuto() + { d_config.availability = Availability::Lazy; d_lazyHealthCheckStats.lock()->d_lastResults.set_capacity(d_config.d_lazyHealthCheckSampleSize); } bool healthCheckRequired(std::optional currentTime = std::nullopt); - const string& getName() const { + const string& getName() const + { return d_config.name; } - const string& getNameWithAddr() const { + const string& getNameWithAddr() const + { return d_config.nameWithAddr; } void setName(const std::string& newName) { d_config.name = newName; - d_config.nameWithAddr = newName.empty() ? d_config.remote.toStringWithPort() : (d_config.name + " (" + d_config.remote.toStringWithPort()+ ")"); + d_config.nameWithAddr = newName.empty() ? d_config.remote.toStringWithPort() : (d_config.name + " (" + d_config.remote.toStringWithPort() + ")"); } string getStatus() const @@ -1032,7 +1096,7 @@ extern std::string g_outputBuffer; // locking for this is ok, as locked by g_lua class DNSRule { public: - virtual ~DNSRule () + virtual ~DNSRule() { } virtual bool matches(const DNSQuestion* dq) const = 0; @@ -1042,7 +1106,8 @@ public: struct ServerPool { - ServerPool(): d_servers(std::make_shared()) + ServerPool() : + d_servers(std::make_shared()) { } @@ -1076,7 +1141,8 @@ private: bool d_useECS{false}; }; -enum ednsHeaderFlags { +enum ednsHeaderFlags +{ EDNS_HEADER_FLAG_NONE = 0, EDNS_HEADER_FLAG_DO = 32768 }; @@ -1105,11 +1171,11 @@ extern DNSAction::Action g_dynBlockAction; extern GlobalStateHolder g_policy; extern GlobalStateHolder g_dstates; extern GlobalStateHolder g_pools; -extern GlobalStateHolder > g_ruleactions; -extern GlobalStateHolder > g_respruleactions; -extern GlobalStateHolder > g_cachehitrespruleactions; -extern GlobalStateHolder > g_selfansweredrespruleactions; -extern GlobalStateHolder > g_cacheInsertedRespRuleActions; +extern GlobalStateHolder> g_ruleactions; +extern GlobalStateHolder> g_respruleactions; +extern GlobalStateHolder> g_cachehitrespruleactions; +extern GlobalStateHolder> g_selfansweredrespruleactions; +extern GlobalStateHolder> g_cacheInsertedRespRuleActions; extern GlobalStateHolder g_ACL; extern ComboAddress g_serverControl; // not changed during runtime @@ -1142,30 +1208,31 @@ extern uint32_t g_socketUDPSendBuffer; extern uint32_t g_socketUDPRecvBuffer; extern shared_ptr g_defaultBPFFilter; -extern std::vector > g_dynBPFFilters; +extern std::vector> g_dynBPFFilters; struct LocalHolders { - LocalHolders(): acl(g_ACL.getLocal()), policy(g_policy.getLocal()), ruleactions(g_ruleactions.getLocal()), cacheHitRespRuleactions(g_cachehitrespruleactions.getLocal()), cacheInsertedRespRuleActions(g_cacheInsertedRespRuleActions.getLocal()), selfAnsweredRespRuleactions(g_selfansweredrespruleactions.getLocal()), servers(g_dstates.getLocal()), dynNMGBlock(g_dynblockNMG.getLocal()), dynSMTBlock(g_dynblockSMT.getLocal()), pools(g_pools.getLocal()) + LocalHolders() : + acl(g_ACL.getLocal()), policy(g_policy.getLocal()), ruleactions(g_ruleactions.getLocal()), cacheHitRespRuleactions(g_cachehitrespruleactions.getLocal()), cacheInsertedRespRuleActions(g_cacheInsertedRespRuleActions.getLocal()), selfAnsweredRespRuleactions(g_selfansweredrespruleactions.getLocal()), servers(g_dstates.getLocal()), dynNMGBlock(g_dynblockNMG.getLocal()), dynSMTBlock(g_dynblockSMT.getLocal()), pools(g_pools.getLocal()) { } LocalStateHolder acl; LocalStateHolder policy; - LocalStateHolder > ruleactions; - LocalStateHolder > cacheHitRespRuleactions; - LocalStateHolder > cacheInsertedRespRuleActions; - LocalStateHolder > selfAnsweredRespRuleactions; + LocalStateHolder> ruleactions; + LocalStateHolder> cacheHitRespRuleactions; + LocalStateHolder> cacheInsertedRespRuleActions; + LocalStateHolder> selfAnsweredRespRuleactions; LocalStateHolder servers; - LocalStateHolder > dynNMGBlock; - LocalStateHolder > dynSMTBlock; + LocalStateHolder> dynNMGBlock; + LocalStateHolder> dynSMTBlock; LocalStateHolder pools; }; void tcpAcceptorThread(const std::vector& states); void setLuaNoSideEffect(); // if nothing has been declared, set that there are no side effects -void setLuaSideEffect(); // set to report a side effect, cancelling all _no_ side effect calls +void setLuaSideEffect(); // set to report a side effect, cancelling all _no_ side effect calls bool getLuaNoSideEffect(); // set if there were only explicit declarations of _no_ side effect void resetLuaSideEffect(); // reset to indeterminate state @@ -1187,7 +1254,13 @@ extern bool g_addEDNSToSelfGeneratedResponses; extern std::set g_capabilitiesToRetain; static const uint16_t s_udpIncomingBufferSize{1500}; // don't accept UDP queries larger than this value -enum class ProcessQueryResult : uint8_t { Drop, SendAnswer, PassToBackend, Asynchronous }; +enum class ProcessQueryResult : uint8_t +{ + Drop, + SendAnswer, + PassToBackend, + Asynchronous +}; ProcessQueryResult processQuery(DNSQuestion& dq, LocalHolders& holders, std::shared_ptr& selectedBackend); ProcessQueryResult processQueryAfterRules(DNSQuestion& dq, LocalHolders& holders, std::shared_ptr& selectedBackend); bool processResponse(PacketBuffer& response, const std::vector& respRuleActions, const std::vector& insertedRespRuleActions, DNSResponse& dr, bool muted); diff --git a/pdns/dnsdistdist/test-dnsdist_cc.cc b/pdns/dnsdistdist/test-dnsdist_cc.cc index 90a513fc8809..1254c7e35708 100644 --- a/pdns/dnsdistdist/test-dnsdist_cc.cc +++ b/pdns/dnsdistdist/test-dnsdist_cc.cc @@ -63,7 +63,8 @@ bool assignOutgoingUDPQueryToBackend(std::shared_ptr& downstrea return true; } -namespace dnsdist { +namespace dnsdist +{ std::unique_ptr getInternalQueryFromDQ(DNSQuestion& dq, bool isResponse) { return nullptr; @@ -92,7 +93,7 @@ BOOST_AUTO_TEST_SUITE(test_dnsdist_cc) static const uint16_t ECSSourcePrefixV4 = 24; static const uint16_t ECSSourcePrefixV6 = 56; -static void validateQuery(const PacketBuffer& packet, bool hasEdns=true, bool hasXPF=false, uint16_t additionals=0, uint16_t answers=0, uint16_t authorities=0) +static void validateQuery(const PacketBuffer& packet, bool hasEdns = true, bool hasXPF = false, uint16_t additionals = 0, uint16_t answers = 0, uint16_t authorities = 0) { MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); @@ -125,7 +126,7 @@ static void validateECS(const PacketBuffer& packet, const ComboAddress& expected BOOST_CHECK_EQUAL(expectedOption.substr(EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE), std::string(ecsOption->second.values.at(0).content, ecsOption->second.values.at(0).size)); } -static void validateResponse(const PacketBuffer& packet, bool hasEdns, uint8_t additionalCount=0) +static void validateResponse(const PacketBuffer& packet, bool hasEdns, uint8_t additionalCount = 0) { MOADNSParser mdp(false, reinterpret_cast(packet.data()), packet.size()); @@ -372,7 +373,7 @@ BOOST_AUTO_TEST_CASE(addECSWithoutEDNSAlreadyParsed) auto packet = query; - ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); + ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); BOOST_CHECK_EQUAL(ids.qname, name); BOOST_CHECK(ids.qtype == QType::A); BOOST_CHECK(ids.qclass == QClass::IN); @@ -411,7 +412,8 @@ BOOST_AUTO_TEST_CASE(addECSWithoutEDNSAlreadyParsed) validateECS(packet, ids.origRemote); } -BOOST_AUTO_TEST_CASE(addECSWithEDNSNoECS) { +BOOST_AUTO_TEST_CASE(addECSWithEDNSNoECS) +{ bool ednsAdded = false; bool ecsAdded = false; ComboAddress remote; @@ -457,7 +459,8 @@ BOOST_AUTO_TEST_CASE(addECSWithEDNSNoECS) { validateQuery(packet); } -BOOST_AUTO_TEST_CASE(addECSWithEDNSNoECSAlreadyParsed) { +BOOST_AUTO_TEST_CASE(addECSWithEDNSNoECSAlreadyParsed) +{ InternalQueryState ids; ids.origRemote = ComboAddress("2001:DB8::1"); ids.protocol = dnsdist::Protocol::DoUDP; @@ -510,7 +513,8 @@ BOOST_AUTO_TEST_CASE(addECSWithEDNSNoECSAlreadyParsed) { validateECS(packet, ids.origRemote); } -BOOST_AUTO_TEST_CASE(replaceECSWithSameSize) { +BOOST_AUTO_TEST_CASE(replaceECSWithSameSize) +{ bool ednsAdded = false; bool ecsAdded = false; ComboAddress remote("192.168.1.25"); @@ -547,7 +551,8 @@ BOOST_AUTO_TEST_CASE(replaceECSWithSameSize) { validateECS(packet, remote); } -BOOST_AUTO_TEST_CASE(replaceECSWithSameSizeAlreadyParsed) { +BOOST_AUTO_TEST_CASE(replaceECSWithSameSizeAlreadyParsed) +{ bool ednsAdded = false; bool ecsAdded = false; ComboAddress remote("192.168.1.25"); @@ -593,7 +598,8 @@ BOOST_AUTO_TEST_CASE(replaceECSWithSameSizeAlreadyParsed) { validateECS(packet, remote); } -BOOST_AUTO_TEST_CASE(replaceECSWithSmaller) { +BOOST_AUTO_TEST_CASE(replaceECSWithSmaller) +{ bool ednsAdded = false; bool ecsAdded = false; ComboAddress remote("192.168.1.25"); @@ -629,7 +635,8 @@ BOOST_AUTO_TEST_CASE(replaceECSWithSmaller) { validateECS(packet, remote); } -BOOST_AUTO_TEST_CASE(replaceECSWithLarger) { +BOOST_AUTO_TEST_CASE(replaceECSWithLarger) +{ bool ednsAdded = false; bool ecsAdded = false; ComboAddress remote("192.168.1.25"); @@ -684,7 +691,8 @@ BOOST_AUTO_TEST_CASE(replaceECSWithLarger) { validateQuery(packet); } -BOOST_AUTO_TEST_CASE(replaceECSFollowedByTSIG) { +BOOST_AUTO_TEST_CASE(replaceECSFollowedByTSIG) +{ bool ednsAdded = false; bool ecsAdded = false; ComboAddress remote("192.168.1.25"); @@ -738,7 +746,8 @@ BOOST_AUTO_TEST_CASE(replaceECSFollowedByTSIG) { validateQuery(packet, true, false, 1); } -BOOST_AUTO_TEST_CASE(replaceECSAfterAN) { +BOOST_AUTO_TEST_CASE(replaceECSAfterAN) +{ bool ednsAdded = false; bool ecsAdded = false; ComboAddress remote("192.168.1.25"); @@ -793,7 +802,8 @@ BOOST_AUTO_TEST_CASE(replaceECSAfterAN) { validateQuery(packet, true, false, 0, 1, 0); } -BOOST_AUTO_TEST_CASE(replaceECSAfterAuth) { +BOOST_AUTO_TEST_CASE(replaceECSAfterAuth) +{ bool ednsAdded = false; bool ecsAdded = false; ComboAddress remote("192.168.1.25"); @@ -848,7 +858,8 @@ BOOST_AUTO_TEST_CASE(replaceECSAfterAuth) { validateQuery(packet, true, false, 0, 0, 1); } -BOOST_AUTO_TEST_CASE(replaceECSBetweenTwoRecords) { +BOOST_AUTO_TEST_CASE(replaceECSBetweenTwoRecords) +{ bool ednsAdded = false; bool ecsAdded = false; ComboAddress remote("192.168.1.25"); @@ -904,7 +915,8 @@ BOOST_AUTO_TEST_CASE(replaceECSBetweenTwoRecords) { validateQuery(packet, true, false, 2); } -BOOST_AUTO_TEST_CASE(insertECSInEDNSBetweenTwoRecords) { +BOOST_AUTO_TEST_CASE(insertECSInEDNSBetweenTwoRecords) +{ bool ednsAdded = false; bool ecsAdded = false; ComboAddress remote("192.168.1.25"); @@ -955,7 +967,8 @@ BOOST_AUTO_TEST_CASE(insertECSInEDNSBetweenTwoRecords) { validateQuery(packet, true, false, 2); } -BOOST_AUTO_TEST_CASE(insertECSAfterTSIG) { +BOOST_AUTO_TEST_CASE(insertECSAfterTSIG) +{ bool ednsAdded = false; bool ecsAdded = false; ComboAddress remote("192.168.1.25"); @@ -1004,8 +1017,8 @@ BOOST_AUTO_TEST_CASE(insertECSAfterTSIG) { validateQuery(packet, true, false); } - -BOOST_AUTO_TEST_CASE(removeEDNSWhenFirst) { +BOOST_AUTO_TEST_CASE(removeEDNSWhenFirst) +{ DNSName name("www.powerdns.com."); PacketBuffer response; @@ -1025,7 +1038,7 @@ BOOST_AUTO_TEST_CASE(removeEDNSWhenFirst) { unsigned int consumed = 0; uint16_t qtype; - DNSName qname((const char*) newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); size_t const ednsOptRRSize = sizeof(struct dnsrecordheader) + 1 /* root in OPT RR */; @@ -1034,7 +1047,8 @@ BOOST_AUTO_TEST_CASE(removeEDNSWhenFirst) { validateResponse(newResponse, false, 1); } -BOOST_AUTO_TEST_CASE(removeEDNSWhenIntermediary) { +BOOST_AUTO_TEST_CASE(removeEDNSWhenIntermediary) +{ DNSName name("www.powerdns.com."); PacketBuffer response; @@ -1057,7 +1071,7 @@ BOOST_AUTO_TEST_CASE(removeEDNSWhenIntermediary) { unsigned int consumed = 0; uint16_t qtype; - DNSName qname((const char*) newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); size_t const ednsOptRRSize = sizeof(struct dnsrecordheader) + 1 /* root in OPT RR */; @@ -1066,7 +1080,8 @@ BOOST_AUTO_TEST_CASE(removeEDNSWhenIntermediary) { validateResponse(newResponse, false, 2); } -BOOST_AUTO_TEST_CASE(removeEDNSWhenLast) { +BOOST_AUTO_TEST_CASE(removeEDNSWhenLast) +{ DNSName name("www.powerdns.com."); PacketBuffer response; @@ -1088,7 +1103,7 @@ BOOST_AUTO_TEST_CASE(removeEDNSWhenLast) { unsigned int consumed = 0; uint16_t qtype; - DNSName qname((const char*) newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); size_t const ednsOptRRSize = sizeof(struct dnsrecordheader) + 1 /* root in OPT RR */; @@ -1097,7 +1112,8 @@ BOOST_AUTO_TEST_CASE(removeEDNSWhenLast) { validateResponse(newResponse, false, 1); } -BOOST_AUTO_TEST_CASE(removeECSWhenOnlyOption) { +BOOST_AUTO_TEST_CASE(removeECSWhenOnlyOption) +{ DNSName name("www.powerdns.com."); ComboAddress origRemote("127.0.0.1"); @@ -1130,21 +1146,22 @@ BOOST_AUTO_TEST_CASE(removeECSWhenOnlyOption) { size_t responseLen = response.size(); size_t existingOptLen = optLen; BOOST_CHECK(existingOptLen < responseLen); - res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); + res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); BOOST_CHECK_EQUAL(res, 0); BOOST_CHECK_EQUAL(optLen, existingOptLen - (origECSOptionStr.size() + 4)); responseLen -= (existingOptLen - optLen); unsigned int consumed = 0; uint16_t qtype; - DNSName qname((const char*) response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); + DNSName qname((const char*)response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); validateResponse(response, true, 1); } -BOOST_AUTO_TEST_CASE(removeECSWhenFirstOption) { +BOOST_AUTO_TEST_CASE(removeECSWhenFirstOption) +{ DNSName name("www.powerdns.com."); ComboAddress origRemote("127.0.0.1"); @@ -1180,21 +1197,22 @@ BOOST_AUTO_TEST_CASE(removeECSWhenFirstOption) { size_t responseLen = response.size(); size_t existingOptLen = optLen; BOOST_CHECK(existingOptLen < responseLen); - res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); + res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); BOOST_CHECK_EQUAL(res, 0); BOOST_CHECK_EQUAL(optLen, existingOptLen - (origECSOptionStr.size() + 4)); responseLen -= (existingOptLen - optLen); unsigned int consumed = 0; uint16_t qtype; - DNSName qname((const char*) response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); + DNSName qname((const char*)response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); validateResponse(response, true, 1); } -BOOST_AUTO_TEST_CASE(removeECSWhenIntermediaryOption) { +BOOST_AUTO_TEST_CASE(removeECSWhenIntermediaryOption) +{ DNSName name("www.powerdns.com."); ComboAddress origRemote("127.0.0.1"); @@ -1234,21 +1252,22 @@ BOOST_AUTO_TEST_CASE(removeECSWhenIntermediaryOption) { size_t responseLen = response.size(); size_t existingOptLen = optLen; BOOST_CHECK(existingOptLen < responseLen); - res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); + res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); BOOST_CHECK_EQUAL(res, 0); BOOST_CHECK_EQUAL(optLen, existingOptLen - (origECSOptionStr.size() + 4)); responseLen -= (existingOptLen - optLen); unsigned int consumed = 0; uint16_t qtype; - DNSName qname((const char*) response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); + DNSName qname((const char*)response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); validateResponse(response, true, 1); } -BOOST_AUTO_TEST_CASE(removeECSWhenLastOption) { +BOOST_AUTO_TEST_CASE(removeECSWhenLastOption) +{ DNSName name("www.powerdns.com."); ComboAddress origRemote("127.0.0.1"); @@ -1284,21 +1303,22 @@ BOOST_AUTO_TEST_CASE(removeECSWhenLastOption) { size_t responseLen = response.size(); size_t existingOptLen = optLen; BOOST_CHECK(existingOptLen < responseLen); - res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); + res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); BOOST_CHECK_EQUAL(res, 0); BOOST_CHECK_EQUAL(optLen, existingOptLen - (origECSOptionStr.size() + 4)); responseLen -= (existingOptLen - optLen); unsigned int consumed = 0; uint16_t qtype; - DNSName qname((const char*) response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); + DNSName qname((const char*)response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); validateResponse(response, true, 1); } -BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenOnlyOption) { +BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenOnlyOption) +{ DNSName name("www.powerdns.com."); ComboAddress origRemote("127.0.0.1"); @@ -1328,14 +1348,15 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenOnlyOption) { unsigned int consumed = 0; uint16_t qtype; - DNSName qname((const char*) newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); validateResponse(newResponse, true, 1); } -BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenFirstOption) { +BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenFirstOption) +{ DNSName name("www.powerdns.com."); ComboAddress origRemote("127.0.0.1"); @@ -1368,14 +1389,15 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenFirstOption) { unsigned int consumed = 0; uint16_t qtype; - DNSName qname((const char*) newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); validateResponse(newResponse, true, 1); } -BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenIntermediaryOption) { +BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenIntermediaryOption) +{ DNSName name("www.powerdns.com."); ComboAddress origRemote("127.0.0.1"); @@ -1410,14 +1432,15 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenIntermediaryOption) { unsigned int consumed = 0; uint16_t qtype; - DNSName qname((const char*) newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); validateResponse(newResponse, true, 1); } -BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenLastOption) { +BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenLastOption) +{ DNSName name("www.powerdns.com."); ComboAddress origRemote("127.0.0.1"); @@ -1450,14 +1473,14 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenLastOption) { unsigned int consumed = 0; uint16_t qtype; - DNSName qname((const char*) newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); validateResponse(newResponse, true, 1); } -static DNSQuestion turnIntoResponse(InternalQueryState& ids, PacketBuffer& query, bool resizeBuffer=true) +static DNSQuestion turnIntoResponse(InternalQueryState& ids, PacketBuffer& query, bool resizeBuffer = true) { if (resizeBuffer) { query.resize(4096); @@ -1486,7 +1509,8 @@ static int getZ(const DNSName& qname, const uint16_t qtype, const uint16_t qclas return getEDNSZ(dq); } -BOOST_AUTO_TEST_CASE(test_getEDNSZ) { +BOOST_AUTO_TEST_CASE(test_getEDNSZ) +{ uint16_t z; uint16_t udpPayloadSize; @@ -1554,7 +1578,7 @@ BOOST_AUTO_TEST_CASE(test_getEDNSZ) { BOOST_CHECK_EQUAL(udpPayloadSize, 512); } - { + { /* valid EDNS, options, DO not set */ PacketBuffer query; GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); @@ -1579,10 +1603,10 @@ BOOST_AUTO_TEST_CASE(test_getEDNSZ) { BOOST_CHECK_EQUAL(z, EDNS_HEADER_FLAG_DO); BOOST_CHECK_EQUAL(udpPayloadSize, 512); } - } -BOOST_AUTO_TEST_CASE(test_addEDNSToQueryTurnedResponse) { +BOOST_AUTO_TEST_CASE(test_addEDNSToQueryTurnedResponse) +{ InternalQueryState ids; ids.qname = DNSName("www.powerdns.com."); ids.qtype = QType::A; @@ -1688,7 +1712,8 @@ BOOST_AUTO_TEST_CASE(test_addEDNSToQueryTurnedResponse) { } } -BOOST_AUTO_TEST_CASE(test_getEDNSOptionsStart) { +BOOST_AUTO_TEST_CASE(test_getEDNSOptionsStart) +{ const DNSName qname("www.powerdns.com."); const uint16_t qtype = QType::A; const uint16_t qclass = QClass::IN; @@ -1763,10 +1788,10 @@ BOOST_AUTO_TEST_CASE(test_getEDNSOptionsStart) { BOOST_CHECK_EQUAL(optRDPosition, optRDExpectedOffset); BOOST_CHECK_EQUAL(remaining, query.size() - optRDExpectedOffset); } - } -BOOST_AUTO_TEST_CASE(test_isEDNSOptionInOpt) { +BOOST_AUTO_TEST_CASE(test_isEDNSOptionInOpt) +{ auto locateEDNSOption = [](const PacketBuffer& query, uint16_t code, size_t* optContentStart, uint16_t* optContentLen) { uint16_t optStart; @@ -1932,7 +1957,8 @@ BOOST_AUTO_TEST_CASE(test_isEDNSOptionInOpt) { } } -BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { +BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) +{ InternalQueryState ids; ids.origRemote = ComboAddress("192.0.2.1"); ids.protocol = dnsdist::Protocol::DoUDP; @@ -1957,7 +1983,7 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); DNSQuestion dq(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4 , 5, false)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); BOOST_CHECK(packet.size() > query.size()); MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); @@ -1979,7 +2005,7 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); DNSQuestion dq(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4 , 5, false)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); BOOST_CHECK(packet.size() > queryWithEDNS.size()); MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); @@ -2005,7 +2031,7 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); DNSQuestion dq(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4 , 5, false)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); BOOST_CHECK(packet.size() > query.size()); MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); @@ -2027,7 +2053,7 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); DNSQuestion dq(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4 , 5, false)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); BOOST_CHECK(packet.size() > queryWithEDNS.size()); MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); @@ -2055,8 +2081,8 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); DNSQuestion dq(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4 , - 5, true)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, + 5, true)); BOOST_CHECK(packet.size() > query.size()); MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); @@ -2078,7 +2104,7 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); DNSQuestion dq(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4 , 5, true)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, true)); BOOST_CHECK(packet.size() > queryWithEDNS.size()); MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); @@ -2104,7 +2130,7 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); DNSQuestion dq(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4 , 5, true)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, true)); BOOST_CHECK(packet.size() > query.size()); MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); @@ -2126,7 +2152,7 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); DNSQuestion dq(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4 , 5, true)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, true)); BOOST_CHECK(packet.size() > queryWithEDNS.size()); MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); @@ -2145,7 +2171,8 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { } } -BOOST_AUTO_TEST_CASE(getEDNSOptionsWithoutEDNS) { +BOOST_AUTO_TEST_CASE(getEDNSOptionsWithoutEDNS) +{ InternalQueryState ids; ids.origRemote = ComboAddress("192.168.1.25"); ids.protocol = dnsdist::Protocol::DoUDP; diff --git a/pdns/dnsdistdist/test-dnsdistnghttp2-in_cc.cc b/pdns/dnsdistdist/test-dnsdistnghttp2-in_cc.cc index 3fa1eaae05f0..968e6c2d7e58 100644 --- a/pdns/dnsdistdist/test-dnsdistnghttp2-in_cc.cc +++ b/pdns/dnsdistdist/test-dnsdistnghttp2-in_cc.cc @@ -198,7 +198,7 @@ class DOHConnection static ssize_t send_callback(nghttp2_session* session, const uint8_t* data, size_t length, int flags, void* user_data) { auto* conn = static_cast(user_data); - //NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): nghttp2 API + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): nghttp2 API conn->d_clientOutBuffer.insert(conn->d_clientOutBuffer.end(), data, data + length); return static_cast(length); } @@ -233,7 +233,7 @@ class DOHConnection { auto* conn = static_cast(user_data); auto& response = conn->d_responses[stream_id]; - //NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): nghttp2 API + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): nghttp2 API response.insert(response.end(), data, data + len); return 0; } @@ -247,7 +247,7 @@ class DOHConnection try { uint16_t responseCode{0}; auto expected = s_connectionContexts.at(conn->d_connectionID).d_responseCodes.at((frame->hd.stream_id - 1) / 2); - //NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): nghttp2 API + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): nghttp2 API pdns::checked_stoi_into(responseCode, std::string(reinterpret_cast(value), valuelen)); conn->d_responseCodes[frame->hd.stream_id] = responseCode; if (responseCode != expected) { @@ -350,10 +350,10 @@ class MockupTLSConnection : public TLSConnection BOOST_REQUIRE_GE(buffer.size(), toRead); - //NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) std::copy(externalBuffer.begin(), externalBuffer.begin() + toRead, buffer.begin() + pos); pos += toRead; - //NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) externalBuffer.erase(externalBuffer.begin(), externalBuffer.begin() + toRead); return step.nextState; diff --git a/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc b/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc index 42d2bad4a1d3..ae72cf267de3 100644 --- a/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc +++ b/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc @@ -20,7 +20,8 @@ BOOST_AUTO_TEST_SUITE(test_dnsdistpacketcache_cc) static bool receivedOverUDP = true; -BOOST_AUTO_TEST_CASE(test_PacketCacheSimple) { +BOOST_AUTO_TEST_CASE(test_PacketCacheSimple) +{ const size_t maxEntries = 150000; DNSDistPacketCache PC(maxEntries, 86400, 1); BOOST_CHECK_EQUAL(PC.getSize(), 0U); @@ -36,7 +37,7 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSimple) { try { for (counter = 0; counter < 100000; ++counter) { - auto a = DNSName(std::to_string(counter))+DNSName(" hello"); + auto a = DNSName(std::to_string(counter)) + DNSName(" hello"); ids.qname = a; PacketBuffer query; @@ -77,10 +78,10 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSimple) { BOOST_CHECK_EQUAL(skipped, PC.getInsertCollisions()); BOOST_CHECK_EQUAL(PC.getSize(), counter - skipped); - size_t deleted=0; - size_t delcounter=0; - for (delcounter=0; delcounter < counter/1000; ++delcounter) { - ids.qname = DNSName(std::to_string(delcounter))+DNSName(" hello"); + size_t deleted = 0; + size_t delcounter = 0; + for (delcounter = 0; delcounter < counter / 1000; ++delcounter) { + ids.qname = DNSName(std::to_string(delcounter)) + DNSName(" hello"); PacketBuffer query; GenericDNSPacketWriter pwQ(query, ids.qname, QType::A, QClass::IN, 0); pwQ.getHeader()->rd = 1; @@ -96,10 +97,10 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSimple) { } BOOST_CHECK_EQUAL(PC.getSize(), counter - skipped - deleted); - size_t matches=0; - size_t expected=counter-skipped-deleted; + size_t matches = 0; + size_t expected = counter - skipped - deleted; for (; delcounter < counter; ++delcounter) { - ids.qname = DNSName(std::to_string(delcounter))+DNSName(" hello"); + ids.qname = DNSName(std::to_string(delcounter)) + DNSName(" hello"); PacketBuffer query; GenericDNSPacketWriter pwQ(query, ids.qname, QType::A, QClass::IN, 0); pwQ.getHeader()->rd = 1; @@ -124,12 +125,13 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSimple) { BOOST_CHECK_EQUAL(PC.purgeExpired(0, now), 0U); } catch (const PDNSException& e) { - cerr<<"Had error: "<id, &key, subnet, dnssecOK, receivedOverUDP, 0, true, allowTruncated); BOOST_CHECK_EQUAL(found, false); -} - catch(const PDNSException& e) { - cerr<<"Had error: "< pwQ(query, ids.qname, QType::A, QClass::IN, 0); pwQ.getHeader()->rd = 1; @@ -697,8 +705,8 @@ static void threadMangler(unsigned int offset) g_PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); } } - catch(PDNSException& e) { - cerr<<"Had error: "< pwQ(query, ids.qname, QType::A, QClass::IN, 0); pwQ.getHeader()->rd = 1; @@ -727,21 +734,22 @@ static void threadReader(unsigned int offset) DNSQuestion dnsQuestion(ids, query); bool found = g_PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); if (!found) { - g_missing++; + g_missing++; } } } - catch(PDNSException& e) { - cerr<<"Had error in threadReader: "< threads; for (int i = 0; i < 4; ++i) { - threads.push_back(std::thread(threadMangler, i*1000000UL)); + threads.push_back(std::thread(threadMangler, i * 1000000UL)); } for (auto& t : threads) { @@ -751,10 +759,10 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheThreaded) { threads.clear(); BOOST_CHECK_EQUAL(g_PC.getSize() + g_PC.getDeferredInserts() + g_PC.getInsertCollisions(), 400000U); - BOOST_CHECK_SMALL(1.0*g_PC.getInsertCollisions(), 10000.0); + BOOST_CHECK_SMALL(1.0 * g_PC.getInsertCollisions(), 10000.0); for (int i = 0; i < 4; ++i) { - threads.push_back(std::thread(threadReader, i*1000000UL)); + threads.push_back(std::thread(threadReader, i * 1000000UL)); } for (auto& t : threads) { @@ -763,14 +771,14 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheThreaded) { BOOST_CHECK((g_PC.getDeferredInserts() + g_PC.getDeferredLookups() + g_PC.getInsertCollisions()) >= g_missing); } - catch(PDNSException& e) { - cerr<<"Had error: "< xfrTypes = { QType::AXFR, QType::IXFR }; + const std::set xfrTypes = {QType::AXFR, QType::IXFR}; for (const auto& type : xfrTypes) { bool dnssecOK = false; InternalQueryState ids; From ee507a5581d569da9b3fe0e24fe1007271911131 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 12:11:55 +0100 Subject: [PATCH 04/25] dnsdist: Delint dnsdist-carbon.cc --- pdns/dnsdistdist/dnsdist-carbon.cc | 55 +++++++++++++++++++++--------- 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-carbon.cc b/pdns/dnsdistdist/dnsdist-carbon.cc index 1b1c0fe5525b..2be36ed3827b 100644 --- a/pdns/dnsdistdist/dnsdist-carbon.cc +++ b/pdns/dnsdistdist/dnsdist-carbon.cc @@ -46,9 +46,9 @@ static bool doOneCarbonExport(const Carbon::Endpoint& endpoint) const std::string& instance_name = endpoint.instance_name; try { - Socket s(server.sin4.sin_family, SOCK_STREAM); - s.setNonBlocking(); - s.connect(server); // we do the connect so the attempt happens while we gather stats + Socket carbonSock(server.sin4.sin_family, SOCK_STREAM); + carbonSock.setNonBlocking(); + carbonSock.connect(server); // we do the connect so the attempt happens while we gather stats ostringstream str; const time_t now = time(nullptr); @@ -77,7 +77,14 @@ static bool doOneCarbonExport(const Carbon::Endpoint& endpoint) for (const auto& state : *states) { string serverName = state->getName().empty() ? state->d_config.remote.toStringWithPort() : state->getName(); boost::replace_all(serverName, ".", "_"); - const string base = namespace_name + "." + hostname + "." + instance_name + ".servers." + serverName + "."; + string base = namespace_name; + base += "."; + base += hostname; + base += "."; + base += instance_name; + base += ".servers."; + base += serverName; + base += "."; str << base << "queries" << ' ' << state->queries.load() << " " << now << "\r\n"; str << base << "responses" << ' ' << state->responses.load() << " " << now << "\r\n"; str << base << "drops" << ' ' << state->reuseds.load() << " " << now << "\r\n"; @@ -117,11 +124,18 @@ static bool doOneCarbonExport(const Carbon::Endpoint& endpoint) boost::replace_all(frontName, ".", "_"); auto dupPair = frontendDuplicates.insert({frontName, 1}); if (!dupPair.second) { - frontName = frontName + "_" + std::to_string(dupPair.first->second); + frontName += "_" + std::to_string(dupPair.first->second); ++(dupPair.first->second); } - const string base = namespace_name + "." + hostname + "." + instance_name + ".frontends." + frontName + "."; + string base = namespace_name; + base += "."; + base += hostname; + base += "."; + base += instance_name; + base += ".frontends."; + base += frontName; + base += "."; str << base << "queries" << ' ' << front->queries.load() << " " << now << "\r\n"; str << base << "responses" << ' ' << front->responses.load() << " " << now << "\r\n"; str << base << "tcpdiedreadingquery" << ' ' << front->tcpDiedReadingQuery.load() << " " << now << "\r\n"; @@ -169,7 +183,14 @@ static bool doOneCarbonExport(const Carbon::Endpoint& endpoint) if (poolName.empty()) { poolName = "_default_"; } - const string base = namespace_name + "." + hostname + "." + instance_name + ".pools." + poolName + "."; + string base = namespace_name; + base += "."; + base += hostname; + base += "."; + base += instance_name; + base += ".pools."; + base += poolName; + base += "."; const std::shared_ptr pool = entry.second; str << base << "servers" << " " << pool->countServers(false) << " " << now << "\r\n"; @@ -213,11 +234,11 @@ static bool doOneCarbonExport(const Carbon::Endpoint& endpoint) auto dupPair = dohFrontendDuplicates.insert({name, 1}); if (!dupPair.second) { - name = name + "_" + std::to_string(dupPair.first->second); + name += "_" + std::to_string(dupPair.first->second); ++(dupPair.first->second); } - vector> v{ + const vector> values{ {"http-connects", doh->d_httpconnects}, {"http1-queries", doh->d_http1Stats.d_nbQueries}, {"http2-queries", doh->d_http2Stats.d_nbQueries}, @@ -240,7 +261,7 @@ static bool doOneCarbonExport(const Carbon::Endpoint& endpoint) {"redirect-responses", doh->d_redirectresponses}, {"valid-responses", doh->d_validresponses}}; - for (const auto& item : v) { + for (const auto& item : values) { str << base << name << "." << item.first << " " << item.second << " " << now << "\r\n"; } } @@ -260,13 +281,13 @@ static bool doOneCarbonExport(const Carbon::Endpoint& endpoint) const string msg = str.str(); - int ret = waitForRWData(s.getHandle(), false, 1, 0); + int ret = waitForRWData(carbonSock.getHandle(), false, 1, 0); if (ret <= 0) { vinfolog("Unable to write data to carbon server on %s: %s", server.toStringWithPort(), (ret < 0 ? stringerror() : "Timeout")); return false; } - s.setBlocking(); - writen2(s.getHandle(), msg.c_str(), msg.size()); + carbonSock.setBlocking(); + writen2(carbonSock.getHandle(), msg.c_str(), msg.size()); } catch (const std::exception& e) { warnlog("Problem sending carbon data to %s: %s", server.toStringWithPort(), e.what()); @@ -286,10 +307,10 @@ static void carbonHandler(Carbon::Endpoint&& endpoint) try { uint8_t consecutiveFailures = 0; do { - DTime dt; - dt.set(); + DTime dtimer; + dtimer.set(); if (doOneCarbonExport(endpoint)) { - const auto elapsedUSec = dt.udiff(); + const auto elapsedUSec = dtimer.udiff(); if (elapsedUSec < 0 || static_cast(elapsedUSec) <= intervalUSec) { useconds_t toSleepUSec = intervalUSec - elapsedUSec; usleep(toSleepUSec); @@ -305,7 +326,7 @@ static void carbonHandler(Carbon::Endpoint&& endpoint) consecutiveFailures++; } vinfolog("Run for %s - %s failed, next attempt in %d", endpoint.server.toStringWithPort(), endpoint.ourname, backOff); - sleep(backOff); + std::this_thread::sleep_for(std::chrono::seconds(backOff)); } } while (true); } From 241ef0b1d99faaeae2daf5a1b47117299359d33d Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 12:12:09 +0100 Subject: [PATCH 05/25] dnsdist: Delint dnsdist-cache.cc --- pdns/dnsdistdist/dnsdist-cache.cc | 105 ++++++++++++++++-------------- pdns/dnsdistdist/dnsdist-cache.hh | 4 +- 2 files changed, 58 insertions(+), 51 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-cache.cc b/pdns/dnsdistdist/dnsdist-cache.cc index 62d84b7d631b..fa17f0dbaa06 100644 --- a/pdns/dnsdistdist/dnsdist-cache.cc +++ b/pdns/dnsdistdist/dnsdist-cache.cc @@ -29,6 +29,7 @@ #include "ednssubnet.hh" #include "packetcache.hh" +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): too cumbersome to change at this point DNSDistPacketCache::DNSDistPacketCache(size_t maxEntries, uint32_t maxTTL, uint32_t minTTL, uint32_t tempFailureTTL, uint32_t maxNegativeTTL, uint32_t staleTTL, bool dontAge, uint32_t shards, bool deferrableInsertLock, bool parseECS) : d_maxEntries(maxEntries), d_shardCount(shards), d_maxTTL(maxTTL), d_tempFailureTTL(tempFailureTTL), d_maxNegativeTTL(maxNegativeTTL), d_minTTL(minTTL), d_staleTTL(staleTTL), d_dontAge(dontAge), d_deferrableInsertLock(deferrableInsertLock), d_parseECS(parseECS) { @@ -47,7 +48,7 @@ DNSDistPacketCache::DNSDistPacketCache(size_t maxEntries, uint32_t maxTTL, uint3 bool DNSDistPacketCache::getClientSubnet(const PacketBuffer& packet, size_t qnameWireLength, boost::optional& subnet) { - uint16_t optRDPosition; + uint16_t optRDPosition = 0; size_t remaining = 0; int res = getEDNSOptionsStart(packet, qnameWireLength, &optRDPosition, &remaining); @@ -56,12 +57,14 @@ bool DNSDistPacketCache::getClientSubnet(const PacketBuffer& packet, size_t qnam size_t ecsOptionStartPosition = 0; size_t ecsOptionSize = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) res = getEDNSOption(reinterpret_cast(&packet.at(optRDPosition)), remaining, EDNSOptionCode::ECS, &ecsOptionStartPosition, &ecsOptionSize); if (res == 0 && ecsOptionSize > (EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE)) { EDNSSubnetOpts eso; - if (getEDNSSubnetOptsFromString(reinterpret_cast(&packet.at(optRDPosition + ecsOptionStartPosition + (EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE))), ecsOptionSize - (EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE), &eso) == true) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + if (getEDNSSubnetOptsFromString(reinterpret_cast(&packet.at(optRDPosition + ecsOptionStartPosition + (EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE))), ecsOptionSize - (EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE), &eso)) { subnet = eso.source; return true; } @@ -91,9 +94,9 @@ void DNSDistPacketCache::insertLocked(CacheShard& shard, std::unordered_map::iterator it; - bool result; - std::tie(it, result) = map.insert({key, newValue}); + std::unordered_map::iterator mapIt; + bool result{false}; + std::tie(mapIt, result) = map.insert({key, newValue}); if (result) { ++shard.d_entriesCount; @@ -102,7 +105,7 @@ void DNSDistPacketCache::insertLocked(CacheShard& shard, std::unordered_mapsecond; + CacheValue& value = mapIt->second; bool wasExpired = value.validity <= newValue.added; if (!wasExpired && !cachedValueMatches(value, newValue.queryFlags, newValue.qname, newValue.qtype, newValue.qclass, newValue.receivedOverUDP, newValue.dnssecOK, newValue.subnet)) { @@ -128,7 +131,7 @@ void DNSDistPacketCache::insert(uint32_t key, const boost::optional& su return; } - uint32_t minTTL; + uint32_t minTTL{0}; if (rcode == RCode::ServFail || rcode == RCode::Refused) { minTTL = tempFailureTTL == boost::none ? d_tempFailureTTL : *tempFailureTTL; @@ -138,6 +141,7 @@ void DNSDistPacketCache::insert(uint32_t key, const boost::optional& su } else { bool seenAuthSOA = false; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) minTTL = getMinTTL(reinterpret_cast(response.data()), response.size(), &seenAuthSOA); /* no TTL found, we don't want to cache this */ @@ -182,44 +186,44 @@ void DNSDistPacketCache::insert(uint32_t key, const boost::optional& su auto& shard = d_shards.at(shardIndex); if (d_deferrableInsertLock) { - auto w = shard.d_map.try_write_lock(); + auto lock = shard.d_map.try_write_lock(); - if (!w.owns_lock()) { + if (!lock.owns_lock()) { ++d_deferredInserts; return; } - insertLocked(shard, *w, key, newValue); + insertLocked(shard, *lock, key, newValue); } else { - auto w = shard.d_map.write_lock(); + auto lock = shard.d_map.write_lock(); - insertLocked(shard, *w, key, newValue); + insertLocked(shard, *lock, key, newValue); } } -bool DNSDistPacketCache::get(DNSQuestion& dq, uint16_t queryId, uint32_t* keyOut, boost::optional& subnet, bool dnssecOK, bool receivedOverUDP, uint32_t allowExpired, bool skipAging, bool truncatedOK, bool recordMiss) +bool DNSDistPacketCache::get(DNSQuestion& dnsQuestion, uint16_t queryId, uint32_t* keyOut, boost::optional& subnet, bool dnssecOK, bool receivedOverUDP, uint32_t allowExpired, bool skipAging, bool truncatedOK, bool recordMiss) { - if (dq.ids.qtype == QType::AXFR || dq.ids.qtype == QType::IXFR) { + if (dnsQuestion.ids.qtype == QType::AXFR || dnsQuestion.ids.qtype == QType::IXFR) { ++d_misses; return false; } - const auto& dnsQName = dq.ids.qname.getStorage(); - uint32_t key = getKey(dnsQName, dq.ids.qname.wirelength(), dq.getData(), receivedOverUDP); + const auto& dnsQName = dnsQuestion.ids.qname.getStorage(); + uint32_t key = getKey(dnsQName, dnsQuestion.ids.qname.wirelength(), dnsQuestion.getData(), receivedOverUDP); - if (keyOut) { + if (keyOut != nullptr) { *keyOut = key; } if (d_parseECS) { - getClientSubnet(dq.getData(), dq.ids.qname.wirelength(), subnet); + getClientSubnet(dnsQuestion.getData(), dnsQuestion.ids.qname.wirelength(), subnet); } uint32_t shardIndex = getShardIndex(key); time_t now = time(nullptr); - time_t age; + time_t age{0}; bool stale = false; - auto& response = dq.getMutableData(); + auto& response = dnsQuestion.getMutableData(); auto& shard = d_shards.at(shardIndex); { auto map = shard.d_map.try_read_lock(); @@ -228,15 +232,15 @@ bool DNSDistPacketCache::get(DNSQuestion& dq, uint16_t queryId, uint32_t* keyOut return false; } - std::unordered_map::const_iterator it = map->find(key); - if (it == map->end()) { + auto mapIt = map->find(key); + if (mapIt == map->end()) { if (recordMiss) { ++d_misses; } return false; } - const CacheValue& value = it->second; + const CacheValue& value = mapIt->second; if (value.validity <= now) { if ((now - value.validity) >= static_cast(allowExpired)) { if (recordMiss) { @@ -244,9 +248,7 @@ bool DNSDistPacketCache::get(DNSQuestion& dq, uint16_t queryId, uint32_t* keyOut } return false; } - else { - stale = true; - } + stale = true; } if (value.len < sizeof(dnsheader)) { @@ -254,15 +256,15 @@ bool DNSDistPacketCache::get(DNSQuestion& dq, uint16_t queryId, uint32_t* keyOut } /* check for collision */ - if (!cachedValueMatches(value, *(getFlagsFromDNSHeader(dq.getHeader().get())), dq.ids.qname, dq.ids.qtype, dq.ids.qclass, receivedOverUDP, dnssecOK, subnet)) { + if (!cachedValueMatches(value, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnsQuestion.ids.qname, dnsQuestion.ids.qtype, dnsQuestion.ids.qclass, receivedOverUDP, dnssecOK, subnet)) { ++d_lookupCollisions; return false; } if (!truncatedOK) { - dnsheader dh; - memcpy(&dh, value.value.data(), sizeof(dh)); - if (dh.tc != 0) { + dnsheader dnsHeader{}; + memcpy(&dnsHeader, value.value.data(), sizeof(dnsHeader)); + if (dnsHeader.tc != 0) { return false; } } @@ -299,10 +301,12 @@ bool DNSDistPacketCache::get(DNSQuestion& dq, uint16_t queryId, uint32_t* keyOut if (!stale) { // coverity[store_truncates_time_t] dnsheader_aligned dh_aligned(response.data()); - ageDNSPacket(reinterpret_cast(&response[0]), response.size(), age, dh_aligned); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + ageDNSPacket(reinterpret_cast(response.data()), response.size(), age, dh_aligned); } else { - editDNSPacketTTL(reinterpret_cast(&response[0]), response.size(), + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + editDNSPacketTTL(reinterpret_cast(response.data()), response.size(), [staleTTL = d_staleTTL](uint8_t /* section */, uint16_t /* class_ */, uint16_t /* type */, uint32_t /* ttl */) { return staleTTL; }); } } @@ -442,20 +446,23 @@ uint32_t DNSDistPacketCache::getKey(const DNSName::string_t& qname, size_t qname } result = burtle(&packet.at(2), sizeof(dnsheader) - 2, result); - result = burtleCI((const unsigned char*)qname.c_str(), qname.length(), result); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + result = burtleCI(reinterpret_cast(qname.c_str()), qname.length(), result); if (packet.size() < sizeof(dnsheader) + qnameWireLength) { throw std::range_error("Computing packet cache key for an invalid packet (" + std::to_string(packet.size()) + " < " + std::to_string(sizeof(dnsheader) + qnameWireLength) + ")"); } if (packet.size() > ((sizeof(dnsheader) + qnameWireLength))) { if (!d_optionsToSkip.empty()) { /* skip EDNS options if any */ + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) result = PacketCache::hashAfterQname(std::string_view(reinterpret_cast(packet.data()), packet.size()), result, sizeof(dnsheader) + qnameWireLength, d_optionsToSkip); } else { result = burtle(&packet.at(sizeof(dnsheader) + qnameWireLength), packet.size() - (sizeof(dnsheader) + qnameWireLength), result); } } - result = burtle((const unsigned char*)&receivedOverUDP, sizeof(receivedOverUDP), result); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + result = burtle(reinterpret_cast(&receivedOverUDP), sizeof(receivedOverUDP), result); return result; } @@ -474,14 +481,14 @@ uint64_t DNSDistPacketCache::getEntriesCount() return getSize(); } -uint64_t DNSDistPacketCache::dump(int fd) +uint64_t DNSDistPacketCache::dump(int fileDesc) { - auto fp = std::unique_ptr(fdopen(dup(fd), "w"), fclose); - if (fp == nullptr) { + auto filePtr = std::unique_ptr(fdopen(dup(fileDesc), "w"), fclose); + if (filePtr == nullptr) { return 0; } - fprintf(fp.get(), "; dnsdist's packet cache dump follows\n;\n"); + fprintf(filePtr.get(), "; dnsdist's packet cache dump follows\n;\n"); uint64_t count = 0; time_t now = time(nullptr); @@ -495,15 +502,15 @@ uint64_t DNSDistPacketCache::dump(int fd) try { uint8_t rcode = 0; if (value.len >= sizeof(dnsheader)) { - dnsheader dh; - memcpy(&dh, value.value.data(), sizeof(dnsheader)); - rcode = dh.rcode; + dnsheader dnsHeader{}; + memcpy(&dnsHeader, value.value.data(), sizeof(dnsheader)); + rcode = dnsHeader.rcode; } - fprintf(fp.get(), "%s %" PRId64 " %s ; rcode %" PRIu8 ", key %" PRIu32 ", length %" PRIu16 ", received over UDP %d, added %" PRId64 "\n", value.qname.toString().c_str(), static_cast(value.validity - now), QType(value.qtype).toString().c_str(), rcode, entry.first, value.len, value.receivedOverUDP, static_cast(value.added)); + fprintf(filePtr.get(), "%s %" PRId64 " %s ; rcode %" PRIu8 ", key %" PRIu32 ", length %" PRIu16 ", received over UDP %d, added %" PRId64 "\n", value.qname.toString().c_str(), static_cast(value.validity - now), QType(value.qtype).toString().c_str(), rcode, entry.first, value.len, value.receivedOverUDP ? 1 : 0, static_cast(value.added)); } catch (...) { - fprintf(fp.get(), "; error printing '%s'\n", value.qname.empty() ? "EMPTY" : value.qname.toString().c_str()); + fprintf(filePtr.get(), "; error printing '%s'\n", value.qname.empty() ? "EMPTY" : value.qname.toString().c_str()); } } } @@ -527,13 +534,13 @@ std::set DNSDistPacketCache::getDomainsContainingRecords(const ComboAdd const CacheValue& value = entry.second; try { - dnsheader dh; if (value.len < sizeof(dnsheader)) { continue; } - memcpy(&dh, value.value.data(), sizeof(dnsheader)); - if (dh.rcode != RCode::NoError || (dh.ancount == 0 && dh.nscount == 0 && dh.arcount == 0)) { + dnsheader dnsHeader{}; + memcpy(&dnsHeader, value.value.data(), sizeof(dnsheader)); + if (dnsHeader.rcode != RCode::NoError || (dnsHeader.ancount == 0 && dnsHeader.nscount == 0 && dnsHeader.arcount == 0)) { continue; } @@ -589,13 +596,13 @@ std::set DNSDistPacketCache::getRecordsForDomain(const DNSName& do continue; } - dnsheader dh; + dnsheader dnsHeader{}; if (value.len < sizeof(dnsheader)) { continue; } - memcpy(&dh, value.value.data(), sizeof(dnsheader)); - if (dh.rcode != RCode::NoError || (dh.ancount == 0 && dh.nscount == 0 && dh.arcount == 0)) { + memcpy(&dnsHeader, value.value.data(), sizeof(dnsheader)); + if (dnsHeader.rcode != RCode::NoError || (dnsHeader.ancount == 0 && dnsHeader.nscount == 0 && dnsHeader.arcount == 0)) { continue; } diff --git a/pdns/dnsdistdist/dnsdist-cache.hh b/pdns/dnsdistdist/dnsdist-cache.hh index 3db5e6ab1ff4..b26fb5f666f3 100644 --- a/pdns/dnsdistdist/dnsdist-cache.hh +++ b/pdns/dnsdistdist/dnsdist-cache.hh @@ -38,7 +38,7 @@ public: DNSDistPacketCache(size_t maxEntries, uint32_t maxTTL = 86400, uint32_t minTTL = 0, uint32_t tempFailureTTL = 60, uint32_t maxNegativeTTL = 3600, uint32_t staleTTL = 60, bool dontAge = false, uint32_t shards = 1, bool deferrableInsertLock = true, bool parseECS = false); void insert(uint32_t key, const boost::optional& subnet, uint16_t queryFlags, bool dnssecOK, const DNSName& qname, uint16_t qtype, uint16_t qclass, const PacketBuffer& response, bool receivedOverUDP, uint8_t rcode, boost::optional tempFailureTTL); - bool get(DNSQuestion& dq, uint16_t queryId, uint32_t* keyOut, boost::optional& subnet, bool dnssecOK, bool receivedOverUDP, uint32_t allowExpired = 0, bool skipAging = false, bool truncatedOK = true, bool recordMiss = true); + bool get(DNSQuestion& dnsQuestion, uint16_t queryId, uint32_t* keyOut, boost::optional& subnet, bool dnssecOK, bool receivedOverUDP, uint32_t allowExpired = 0, bool skipAging = false, bool truncatedOK = true, bool recordMiss = true); size_t purgeExpired(size_t upTo, const time_t now); size_t expunge(size_t upTo = 0); size_t expungeByName(const DNSName& name, uint16_t qtype = QType::ANY, bool suffixMatch = false); @@ -55,7 +55,7 @@ public: uint64_t getTTLTooShorts() const { return d_ttlTooShorts.load(); } uint64_t getCleanupCount() const { return d_cleanupCount.load(); } uint64_t getEntriesCount(); - uint64_t dump(int fd); + uint64_t dump(int fileDesc); /* get the list of domains (qnames) that contains the given address in an A or AAAA record */ std::set getDomainsContainingRecords(const ComboAddress& addr); From be931db61559b820bac6a8215295c7ba420fd88a Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 12:12:21 +0100 Subject: [PATCH 06/25] dnsdist: Delint test-dnsdistpacketcache_cc.cc --- .../dnsdistdist/test-dnsdistpacketcache_cc.cc | 280 +++++++++--------- 1 file changed, 139 insertions(+), 141 deletions(-) diff --git a/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc b/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc index ae72cf267de3..f7d2f31750dd 100644 --- a/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc +++ b/pdns/dnsdistdist/test-dnsdistpacketcache_cc.cc @@ -23,8 +23,8 @@ static bool receivedOverUDP = true; BOOST_AUTO_TEST_CASE(test_PacketCacheSimple) { const size_t maxEntries = 150000; - DNSDistPacketCache PC(maxEntries, 86400, 1); - BOOST_CHECK_EQUAL(PC.getSize(), 0U); + DNSDistPacketCache localCache(maxEntries, 86400, 1); + BOOST_CHECK_EQUAL(localCache.getSize(), 0U); size_t counter = 0; size_t skipped = 0; @@ -37,34 +37,33 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSimple) try { for (counter = 0; counter < 100000; ++counter) { - auto a = DNSName(std::to_string(counter)) + DNSName(" hello"); - ids.qname = a; + ids.qname = DNSName(std::to_string(counter)) + DNSName(" hello"); PacketBuffer query; - GenericDNSPacketWriter pwQ(query, a, QType::A, QClass::IN, 0); + GenericDNSPacketWriter pwQ(query, ids.qname, QType::A, QClass::IN, 0); pwQ.getHeader()->rd = 1; PacketBuffer response; - GenericDNSPacketWriter pwR(response, a, QType::A, QClass::IN, 0); + GenericDNSPacketWriter pwR(response, ids.qname, QType::A, QClass::IN, 0); pwR.getHeader()->rd = 1; pwR.getHeader()->ra = 1; pwR.getHeader()->qr = 1; pwR.getHeader()->id = pwQ.getHeader()->id; - pwR.startRecord(a, QType::A, 7200, QClass::IN, DNSResourceRecord::ANSWER); + pwR.startRecord(ids.qname, QType::A, 7200, QClass::IN, DNSResourceRecord::ANSWER); pwR.xfr32BitInt(0x01020304); pwR.commit(); uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); - PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, a, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); + localCache.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); - if (found == true) { + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); + if (found) { BOOST_CHECK_EQUAL(dnsQuestion.getData().size(), response.size()); int match = memcmp(dnsQuestion.getData().data(), response.data(), dnsQuestion.getData().size()); BOOST_CHECK_EQUAL(match, 0); @@ -75,8 +74,8 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSimple) } } - BOOST_CHECK_EQUAL(skipped, PC.getInsertCollisions()); - BOOST_CHECK_EQUAL(PC.getSize(), counter - skipped); + BOOST_CHECK_EQUAL(skipped, localCache.getInsertCollisions()); + BOOST_CHECK_EQUAL(localCache.getSize(), counter - skipped); size_t deleted = 0; size_t delcounter = 0; @@ -88,14 +87,14 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSimple) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); - if (found == true) { - auto removed = PC.expungeByName(ids.qname); + bool found = localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); + if (found) { + auto removed = localCache.expungeByName(ids.qname); BOOST_CHECK_EQUAL(removed, 1U); deleted += removed; } } - BOOST_CHECK_EQUAL(PC.getSize(), counter - skipped - deleted); + BOOST_CHECK_EQUAL(localCache.getSize(), counter - skipped - deleted); size_t matches = 0; size_t expected = counter - skipped - deleted; @@ -107,22 +106,22 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSimple) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - if (PC.get(dnsQuestion, pwQ.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP)) { + if (localCache.get(dnsQuestion, pwQ.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP)) { matches++; } } /* in the unlikely event that the test took so long that the entries did expire.. */ - auto expired = PC.purgeExpired(0, now); + auto expired = localCache.purgeExpired(0, now); BOOST_CHECK_EQUAL(matches + expired, expected); - auto remaining = PC.getSize(); - auto removed = PC.expungeByName(DNSName(" hello"), QType::ANY, true); - BOOST_CHECK_EQUAL(PC.getSize(), 0U); + auto remaining = localCache.getSize(); + auto removed = localCache.expungeByName(DNSName(" hello"), QType::ANY, true); + BOOST_CHECK_EQUAL(localCache.getSize(), 0U); BOOST_CHECK_EQUAL(removed, remaining); /* nothing to remove */ - BOOST_CHECK_EQUAL(PC.purgeExpired(0, now), 0U); + BOOST_CHECK_EQUAL(localCache.purgeExpired(0, now), 0U); } catch (const PDNSException& e) { cerr << "Had error: " << e.reason << endl; @@ -134,8 +133,8 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSharded) { const size_t maxEntries = 150000; const size_t numberOfShards = 10; - DNSDistPacketCache PC(maxEntries, 86400, 1, 60, 3600, 60, false, numberOfShards); - BOOST_CHECK_EQUAL(PC.getSize(), 0U); + DNSDistPacketCache localCache(maxEntries, 86400, 1, 60, 3600, 60, false, numberOfShards); + BOOST_CHECK_EQUAL(localCache.getSize(), 0U); size_t counter = 0; size_t skipped = 0; @@ -169,14 +168,14 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSharded) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); - PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::AAAA, QClass::IN, response, receivedOverUDP, 0, boost::none); + localCache.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::AAAA, QClass::IN, response, receivedOverUDP, 0, boost::none); - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); - if (found == true) { + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); + if (found) { BOOST_CHECK_EQUAL(dnsQuestion.getData().size(), response.size()); int match = memcmp(dnsQuestion.getData().data(), response.data(), dnsQuestion.getData().size()); BOOST_CHECK_EQUAL(match, 0); @@ -187,8 +186,8 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSharded) } } - BOOST_CHECK_EQUAL(skipped, PC.getInsertCollisions()); - BOOST_CHECK_EQUAL(PC.getSize(), counter - skipped); + BOOST_CHECK_EQUAL(skipped, localCache.getInsertCollisions()); + BOOST_CHECK_EQUAL(localCache.getSize(), counter - skipped); size_t matches = 0; for (counter = 0; counter < 100000; ++counter) { @@ -200,31 +199,31 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSharded) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - if (PC.get(dnsQuestion, pwQ.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP)) { + if (localCache.get(dnsQuestion, pwQ.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP)) { matches++; } } BOOST_CHECK_EQUAL(matches, counter - skipped); - auto remaining = PC.getSize(); + auto remaining = localCache.getSize(); /* no entry should have expired */ - auto expired = PC.purgeExpired(0, now); + auto expired = localCache.purgeExpired(0, now); BOOST_CHECK_EQUAL(expired, 0U); /* but after the TTL .. let's ask for at most 1k entries */ - auto removed = PC.purgeExpired(1000, now + 7200 + 3600); + auto removed = localCache.purgeExpired(1000, now + 7200 + 3600); BOOST_CHECK_EQUAL(removed, remaining - 1000U); - BOOST_CHECK_EQUAL(PC.getSize(), 1000U); + BOOST_CHECK_EQUAL(localCache.getSize(), 1000U); /* now remove everything */ - removed = PC.purgeExpired(0, now + 7200 + 3600); + removed = localCache.purgeExpired(0, now + 7200 + 3600); BOOST_CHECK_EQUAL(removed, 1000U); - BOOST_CHECK_EQUAL(PC.getSize(), 0U); + BOOST_CHECK_EQUAL(localCache.getSize(), 0U); /* nothing to remove */ - BOOST_CHECK_EQUAL(PC.purgeExpired(0, now), 0U); + BOOST_CHECK_EQUAL(localCache.purgeExpired(0, now), 0U); } catch (const PDNSException& e) { cerr << "Had error: " << e.reason << endl; @@ -235,7 +234,7 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheSharded) BOOST_AUTO_TEST_CASE(test_PacketCacheTCP) { const size_t maxEntries = 150000; - DNSDistPacketCache PC(maxEntries, 86400, 1); + DNSDistPacketCache localCache(maxEntries, 86400, 1); InternalQueryState ids; ids.qtype = QType::A; ids.qclass = QClass::IN; @@ -244,20 +243,19 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheTCP) ComboAddress remote; bool dnssecOK = false; try { - DNSName a("tcp"); - ids.qname = a; + ids.qname = DNSName("tcp"); PacketBuffer query; - GenericDNSPacketWriter pwQ(query, a, QType::AAAA, QClass::IN, 0); + GenericDNSPacketWriter pwQ(query, ids.qname, QType::AAAA, QClass::IN, 0); pwQ.getHeader()->rd = 1; PacketBuffer response; - GenericDNSPacketWriter pwR(response, a, QType::AAAA, QClass::IN, 0); + GenericDNSPacketWriter pwR(response, ids.qname, QType::AAAA, QClass::IN, 0); pwR.getHeader()->rd = 1; pwR.getHeader()->ra = 1; pwR.getHeader()->qr = 1; pwR.getHeader()->id = pwQ.getHeader()->id; - pwR.startRecord(a, QType::AAAA, 7200, QClass::IN, DNSResourceRecord::ANSWER); + pwR.startRecord(ids.qname, QType::AAAA, 7200, QClass::IN, DNSResourceRecord::ANSWER); ComboAddress v6addr("2001:db8::1"); pwR.xfrCAWithoutPort(6, v6addr); pwR.commit(); @@ -267,12 +265,12 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheTCP) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); - PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, a, QType::A, QClass::IN, response, receivedOverUDP, RCode::NoError, boost::none); - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); + localCache.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::A, QClass::IN, response, receivedOverUDP, RCode::NoError, boost::none); + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); BOOST_CHECK_EQUAL(found, true); BOOST_CHECK(!subnet); } @@ -283,12 +281,12 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheTCP) boost::optional subnet; ids.protocol = dnsdist::Protocol::DoTCP; DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, !receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, !receivedOverUDP); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); - PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, a, QType::A, QClass::IN, response, !receivedOverUDP, RCode::NoError, boost::none); - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, !receivedOverUDP, 0, true); + localCache.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::A, QClass::IN, response, !receivedOverUDP, RCode::NoError, boost::none); + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, !receivedOverUDP, 0, true); BOOST_CHECK_EQUAL(found, true); BOOST_CHECK(!subnet); } @@ -302,7 +300,7 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheTCP) BOOST_AUTO_TEST_CASE(test_PacketCacheServFailTTL) { const size_t maxEntries = 150000; - DNSDistPacketCache PC(maxEntries, 86400, 1); + DNSDistPacketCache localCache(maxEntries, 86400, 1); InternalQueryState ids; ids.qtype = QType::A; ids.qclass = QClass::IN; @@ -311,15 +309,14 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheServFailTTL) ComboAddress remote; bool dnssecOK = false; try { - DNSName a = DNSName("servfail"); - ids.qname = a; + ids.qname = DNSName("servfail"); PacketBuffer query; - GenericDNSPacketWriter pwQ(query, a, QType::A, QClass::IN, 0); + GenericDNSPacketWriter pwQ(query, ids.qname, QType::A, QClass::IN, 0); pwQ.getHeader()->rd = 1; PacketBuffer response; - GenericDNSPacketWriter pwR(response, a, QType::A, QClass::IN, 0); + GenericDNSPacketWriter pwR(response, ids.qname, QType::A, QClass::IN, 0); pwR.getHeader()->rd = 1; pwR.getHeader()->ra = 0; pwR.getHeader()->qr = 1; @@ -330,19 +327,19 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheServFailTTL) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); // Insert with failure-TTL of 0 (-> should not enter cache). - PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, a, QType::A, QClass::IN, response, receivedOverUDP, RCode::ServFail, boost::optional(0)); - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); + localCache.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::A, QClass::IN, response, receivedOverUDP, RCode::ServFail, boost::optional(0)); + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); // Insert with failure-TTL non-zero (-> should enter cache). - PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, a, QType::A, QClass::IN, response, receivedOverUDP, RCode::ServFail, boost::optional(300)); - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); + localCache.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::A, QClass::IN, response, receivedOverUDP, RCode::ServFail, boost::optional(300)); + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); BOOST_CHECK_EQUAL(found, true); BOOST_CHECK(!subnet); } @@ -355,7 +352,7 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheServFailTTL) BOOST_AUTO_TEST_CASE(test_PacketCacheNoDataTTL) { const size_t maxEntries = 150000; - DNSDistPacketCache PC(maxEntries, /* maxTTL */ 86400, /* minTTL */ 1, /* tempFailureTTL */ 60, /* maxNegativeTTL */ 1); + DNSDistPacketCache localCache(maxEntries, /* maxTTL */ 86400, /* minTTL */ 1, /* tempFailureTTL */ 60, /* maxNegativeTTL */ 1); ComboAddress remote; bool dnssecOK = false; @@ -387,18 +384,18 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheNoDataTTL) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); - PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, name, QType::A, QClass::IN, response, receivedOverUDP, RCode::NoError, boost::none); - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); + localCache.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, name, QType::A, QClass::IN, response, receivedOverUDP, RCode::NoError, boost::none); + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); BOOST_CHECK_EQUAL(found, true); BOOST_CHECK(!subnet); - sleep(2); + std::this_thread::sleep_for(std::chrono::seconds(2)); /* it should have expired by now */ - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); } @@ -411,7 +408,7 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheNoDataTTL) BOOST_AUTO_TEST_CASE(test_PacketCacheNXDomainTTL) { const size_t maxEntries = 150000; - DNSDistPacketCache PC(maxEntries, /* maxTTL */ 86400, /* minTTL */ 1, /* tempFailureTTL */ 60, /* maxNegativeTTL */ 1); + DNSDistPacketCache localCache(maxEntries, /* maxTTL */ 86400, /* minTTL */ 1, /* tempFailureTTL */ 60, /* maxNegativeTTL */ 1); InternalQueryState ids; ids.qtype = QType::A; @@ -443,18 +440,18 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheNXDomainTTL) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); - PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, name, QType::A, QClass::IN, response, receivedOverUDP, RCode::NXDomain, boost::none); - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); + localCache.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, name, QType::A, QClass::IN, response, receivedOverUDP, RCode::NXDomain, boost::none); + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); BOOST_CHECK_EQUAL(found, true); BOOST_CHECK(!subnet); - sleep(2); + std::this_thread::sleep_for(std::chrono::seconds(2)); /* it should have expired by now */ - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); } @@ -467,7 +464,7 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheNXDomainTTL) BOOST_AUTO_TEST_CASE(test_PacketCacheTruncated) { const size_t maxEntries = 150000; - DNSDistPacketCache PC(maxEntries, /* maxTTL */ 86400, /* minTTL */ 1, /* tempFailureTTL */ 60, /* maxNegativeTTL */ 1); + DNSDistPacketCache localCache(maxEntries, /* maxTTL */ 86400, /* minTTL */ 1, /* tempFailureTTL */ 60, /* maxNegativeTTL */ 1); InternalQueryState ids; ids.qtype = QType::A; @@ -498,19 +495,19 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheTruncated) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); - PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::A, QClass::IN, response, receivedOverUDP, RCode::NXDomain, boost::none); + localCache.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::A, QClass::IN, response, receivedOverUDP, RCode::NXDomain, boost::none); bool allowTruncated = true; - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true, allowTruncated); + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true, allowTruncated); BOOST_CHECK_EQUAL(found, true); BOOST_CHECK(!subnet); allowTruncated = false; - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true, allowTruncated); + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true, allowTruncated); BOOST_CHECK_EQUAL(found, false); } catch (const PDNSException& e) { @@ -669,7 +666,7 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheMaximumSize) } } -static DNSDistPacketCache g_PC(500000); +static DNSDistPacketCache s_localCache(500000); static void threadMangler(unsigned int offset) { @@ -700,9 +697,9 @@ static void threadMangler(unsigned int offset) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - g_PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); + s_localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); - g_PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); + s_localCache.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); } } catch (PDNSException& e) { @@ -732,7 +729,7 @@ static void threadReader(unsigned int offset) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - bool found = g_PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); + bool found = s_localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); if (!found) { g_missing++; } @@ -748,30 +745,31 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheThreaded) { try { std::vector threads; + threads.reserve(4); for (int i = 0; i < 4; ++i) { - threads.push_back(std::thread(threadMangler, i * 1000000UL)); + threads.emplace_back(threadMangler, i * 1000000UL); } - for (auto& t : threads) { - t.join(); + for (auto& thr : threads) { + thr.join(); } threads.clear(); - BOOST_CHECK_EQUAL(g_PC.getSize() + g_PC.getDeferredInserts() + g_PC.getInsertCollisions(), 400000U); - BOOST_CHECK_SMALL(1.0 * g_PC.getInsertCollisions(), 10000.0); + BOOST_CHECK_EQUAL(s_localCache.getSize() + s_localCache.getDeferredInserts() + s_localCache.getInsertCollisions(), 400000U); + BOOST_CHECK_SMALL(1.0 * s_localCache.getInsertCollisions(), 10000.0); for (int i = 0; i < 4; ++i) { - threads.push_back(std::thread(threadReader, i * 1000000UL)); + threads.emplace_back(threadReader, i * 1000000UL); } - for (auto& t : threads) { - t.join(); + for (auto& thr : threads) { + thr.join(); } - BOOST_CHECK((g_PC.getDeferredInserts() + g_PC.getDeferredLookups() + g_PC.getInsertCollisions()) >= g_missing); + BOOST_CHECK((s_localCache.getDeferredInserts() + s_localCache.getDeferredLookups() + s_localCache.getInsertCollisions()) >= g_missing); } - catch (PDNSException& e) { + catch (const PDNSException& e) { cerr << "Had error: " << e.reason << endl; throw; } @@ -780,8 +778,8 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheThreaded) BOOST_AUTO_TEST_CASE(test_PCCollision) { const size_t maxEntries = 150000; - DNSDistPacketCache PC(maxEntries, 86400, 1, 60, 3600, 60, false, 1, true, true); - BOOST_CHECK_EQUAL(PC.getSize(), 0U); + DNSDistPacketCache localCache(maxEntries, 86400, 1, 60, 3600, 60, false, 1, true, true); + BOOST_CHECK_EQUAL(localCache.getSize(), 0U); InternalQueryState ids; ids.qtype = QType::AAAA; @@ -789,8 +787,8 @@ BOOST_AUTO_TEST_CASE(test_PCCollision) ids.qname = DNSName("www.powerdns.com."); ids.protocol = dnsdist::Protocol::DoUDP; uint16_t qid = 0x42; - uint32_t key; - uint32_t secondKey; + uint32_t key{}; + uint32_t secondKey{}; boost::optional subnetOut; bool dnssecOK = false; @@ -811,7 +809,7 @@ BOOST_AUTO_TEST_CASE(test_PCCollision) ComboAddress remote("192.0.2.1"); ids.queryRealTime.start(); DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnetOut, dnssecOK, receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &key, subnetOut, dnssecOK, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); BOOST_REQUIRE(subnetOut); BOOST_CHECK_EQUAL(subnetOut->toString(), opt.source.toString()); @@ -827,10 +825,10 @@ BOOST_AUTO_TEST_CASE(test_PCCollision) pwR.addOpt(512, 0, 0, ednsOptions); pwR.commit(); - PC.insert(key, subnetOut, *(getFlagsFromDNSHeader(pwR.getHeader())), dnssecOK, ids.qname, ids.qtype, QClass::IN, response, receivedOverUDP, RCode::NoError, boost::none); - BOOST_CHECK_EQUAL(PC.getSize(), 1U); + localCache.insert(key, subnetOut, *(getFlagsFromDNSHeader(pwR.getHeader())), dnssecOK, ids.qname, ids.qtype, QClass::IN, response, receivedOverUDP, RCode::NoError, boost::none); + BOOST_CHECK_EQUAL(localCache.getSize(), 1U); - found = PC.get(dnsQuestion, 0, &key, subnetOut, dnssecOK, receivedOverUDP); + found = localCache.get(dnsQuestion, 0, &key, subnetOut, dnssecOK, receivedOverUDP); BOOST_CHECK_EQUAL(found, true); BOOST_REQUIRE(subnetOut); BOOST_CHECK_EQUAL(subnetOut->toString(), opt.source.toString()); @@ -853,12 +851,12 @@ BOOST_AUTO_TEST_CASE(test_PCCollision) ComboAddress remote("192.0.2.1"); ids.queryRealTime.start(); DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &secondKey, subnetOut, dnssecOK, receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &secondKey, subnetOut, dnssecOK, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK_EQUAL(secondKey, key); BOOST_REQUIRE(subnetOut); BOOST_CHECK_EQUAL(subnetOut->toString(), opt.source.toString()); - BOOST_CHECK_EQUAL(PC.getLookupCollisions(), 1U); + BOOST_CHECK_EQUAL(localCache.getLookupCollisions(), 1U); } #if 0 @@ -906,8 +904,8 @@ BOOST_AUTO_TEST_CASE(test_PCCollision) BOOST_AUTO_TEST_CASE(test_PCDNSSECCollision) { const size_t maxEntries = 150000; - DNSDistPacketCache PC(maxEntries, 86400, 1, 60, 3600, 60, false, 1, true, true); - BOOST_CHECK_EQUAL(PC.getSize(), 0U); + DNSDistPacketCache localCache(maxEntries, 86400, 1, 60, 3600, 60, false, 1, true, true); + BOOST_CHECK_EQUAL(localCache.getSize(), 0U); InternalQueryState ids; ids.qtype = QType::AAAA; @@ -915,7 +913,7 @@ BOOST_AUTO_TEST_CASE(test_PCDNSSECCollision) ids.qname = DNSName("www.powerdns.com."); ids.protocol = dnsdist::Protocol::DoUDP; uint16_t qid = 0x42; - uint32_t key; + uint32_t key{}; boost::optional subnetOut; /* lookup for a query with DNSSEC OK, @@ -933,7 +931,7 @@ BOOST_AUTO_TEST_CASE(test_PCDNSSECCollision) ids.queryRealTime.start(); ids.origRemote = remote; DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnetOut, true, receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &key, subnetOut, true, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); PacketBuffer response; @@ -947,13 +945,13 @@ BOOST_AUTO_TEST_CASE(test_PCDNSSECCollision) pwR.addOpt(512, 0, EDNS_HEADER_FLAG_DO); pwR.commit(); - PC.insert(key, subnetOut, *(getFlagsFromDNSHeader(pwR.getHeader())), /* DNSSEC OK is set */ true, ids.qname, ids.qtype, QClass::IN, response, receivedOverUDP, RCode::NoError, boost::none); - BOOST_CHECK_EQUAL(PC.getSize(), 1U); + localCache.insert(key, subnetOut, *(getFlagsFromDNSHeader(pwR.getHeader())), /* DNSSEC OK is set */ true, ids.qname, ids.qtype, QClass::IN, response, receivedOverUDP, RCode::NoError, boost::none); + BOOST_CHECK_EQUAL(localCache.getSize(), 1U); - found = PC.get(dnsQuestion, 0, &key, subnetOut, false, receivedOverUDP); + found = localCache.get(dnsQuestion, 0, &key, subnetOut, false, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); - found = PC.get(dnsQuestion, 0, &key, subnetOut, true, receivedOverUDP); + found = localCache.get(dnsQuestion, 0, &key, subnetOut, true, receivedOverUDP); BOOST_CHECK_EQUAL(found, true); } } @@ -961,8 +959,8 @@ BOOST_AUTO_TEST_CASE(test_PCDNSSECCollision) BOOST_AUTO_TEST_CASE(test_PacketCacheInspection) { const size_t maxEntries = 100; - DNSDistPacketCache PC(maxEntries, 86400, 1); - BOOST_CHECK_EQUAL(PC.getSize(), 0U); + DNSDistPacketCache localCache(maxEntries, 86400, 1); + BOOST_CHECK_EQUAL(localCache.getSize(), 0U); ComboAddress remote; bool dnssecOK = false; @@ -995,8 +993,8 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheInspection) pwR.commit(); } - PC.insert(key++, boost::none, *getFlagsFromDNSHeader(pwQ.getHeader()), dnssecOK, qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); - BOOST_CHECK_EQUAL(PC.getSize(), key); + localCache.insert(key++, boost::none, *getFlagsFromDNSHeader(pwQ.getHeader()), dnssecOK, qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); + BOOST_CHECK_EQUAL(localCache.getSize(), key); } /* insert powerdns1.com A 192.0.2.3, 192.0.2.4, AAAA 2001:db8::3, 2001:db8::4 */ @@ -1037,8 +1035,8 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheInspection) pwR.commit(); } - PC.insert(key++, boost::none, *getFlagsFromDNSHeader(pwQ.getHeader()), dnssecOK, qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); - BOOST_CHECK_EQUAL(PC.getSize(), key); + localCache.insert(key++, boost::none, *getFlagsFromDNSHeader(pwQ.getHeader()), dnssecOK, qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); + BOOST_CHECK_EQUAL(localCache.getSize(), key); } /* insert powerdns2.com NODATA */ @@ -1060,8 +1058,8 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheInspection) pwR.addOpt(4096, 0, 0); pwR.commit(); - PC.insert(key++, boost::none, *getFlagsFromDNSHeader(pwQ.getHeader()), dnssecOK, qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); - BOOST_CHECK_EQUAL(PC.getSize(), key); + localCache.insert(key++, boost::none, *getFlagsFromDNSHeader(pwQ.getHeader()), dnssecOK, qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); + BOOST_CHECK_EQUAL(localCache.getSize(), key); } /* insert powerdns3.com AAAA 2001:db8::4, 2001:db8::5 */ @@ -1090,8 +1088,8 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheInspection) pwR.commit(); } - PC.insert(key++, boost::none, *getFlagsFromDNSHeader(pwQ.getHeader()), dnssecOK, qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); - BOOST_CHECK_EQUAL(PC.getSize(), key); + localCache.insert(key++, boost::none, *getFlagsFromDNSHeader(pwQ.getHeader()), dnssecOK, qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); + BOOST_CHECK_EQUAL(localCache.getSize(), key); } /* insert powerdns4.com A 192.0.2.1 */ @@ -1114,61 +1112,61 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheInspection) pwR.commit(); } - PC.insert(key++, boost::none, *getFlagsFromDNSHeader(pwQ.getHeader()), dnssecOK, qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); - BOOST_CHECK_EQUAL(PC.getSize(), key); + localCache.insert(key++, boost::none, *getFlagsFromDNSHeader(pwQ.getHeader()), dnssecOK, qname, QType::A, QClass::IN, response, receivedOverUDP, 0, boost::none); + BOOST_CHECK_EQUAL(localCache.getSize(), key); } { - auto domains = PC.getDomainsContainingRecords(ComboAddress("192.0.2.1")); + auto domains = localCache.getDomainsContainingRecords(ComboAddress("192.0.2.1")); BOOST_CHECK_EQUAL(domains.size(), 2U); BOOST_CHECK_EQUAL(domains.count(DNSName("powerdns.com")), 1U); BOOST_CHECK_EQUAL(domains.count(DNSName("powerdns4.com")), 1U); } { - auto domains = PC.getDomainsContainingRecords(ComboAddress("192.0.2.2")); + auto domains = localCache.getDomainsContainingRecords(ComboAddress("192.0.2.2")); BOOST_CHECK_EQUAL(domains.size(), 1U); BOOST_CHECK_EQUAL(domains.count(DNSName("powerdns.com")), 1U); } { - auto domains = PC.getDomainsContainingRecords(ComboAddress("192.0.2.3")); + auto domains = localCache.getDomainsContainingRecords(ComboAddress("192.0.2.3")); BOOST_CHECK_EQUAL(domains.size(), 1U); BOOST_CHECK_EQUAL(domains.count(DNSName("powerdns1.com")), 1U); } { - auto domains = PC.getDomainsContainingRecords(ComboAddress("192.0.2.4")); + auto domains = localCache.getDomainsContainingRecords(ComboAddress("192.0.2.4")); BOOST_CHECK_EQUAL(domains.size(), 1U); BOOST_CHECK_EQUAL(domains.count(DNSName("powerdns1.com")), 1U); } { - auto domains = PC.getDomainsContainingRecords(ComboAddress("192.0.2.5")); + auto domains = localCache.getDomainsContainingRecords(ComboAddress("192.0.2.5")); BOOST_CHECK_EQUAL(domains.size(), 0U); } { - auto domains = PC.getDomainsContainingRecords(ComboAddress("2001:db8::3")); + auto domains = localCache.getDomainsContainingRecords(ComboAddress("2001:db8::3")); BOOST_CHECK_EQUAL(domains.size(), 1U); BOOST_CHECK_EQUAL(domains.count(DNSName("powerdns1.com")), 1U); } { - auto domains = PC.getDomainsContainingRecords(ComboAddress("2001:db8::4")); + auto domains = localCache.getDomainsContainingRecords(ComboAddress("2001:db8::4")); BOOST_CHECK_EQUAL(domains.size(), 2U); BOOST_CHECK_EQUAL(domains.count(DNSName("powerdns1.com")), 1U); BOOST_CHECK_EQUAL(domains.count(DNSName("powerdns3.com")), 1U); } { - auto domains = PC.getDomainsContainingRecords(ComboAddress("2001:db8::5")); + auto domains = localCache.getDomainsContainingRecords(ComboAddress("2001:db8::5")); BOOST_CHECK_EQUAL(domains.size(), 1U); BOOST_CHECK_EQUAL(domains.count(DNSName("powerdns3.com")), 1U); } { - auto records = PC.getRecordsForDomain(DNSName("powerdns.com")); + auto records = localCache.getRecordsForDomain(DNSName("powerdns.com")); BOOST_CHECK_EQUAL(records.size(), 2U); BOOST_CHECK_EQUAL(records.count(ComboAddress("192.0.2.1")), 1U); BOOST_CHECK_EQUAL(records.count(ComboAddress("192.0.2.2")), 1U); } { - auto records = PC.getRecordsForDomain(DNSName("powerdns1.com")); + auto records = localCache.getRecordsForDomain(DNSName("powerdns1.com")); BOOST_CHECK_EQUAL(records.size(), 4U); BOOST_CHECK_EQUAL(records.count(ComboAddress("192.0.2.3")), 1U); BOOST_CHECK_EQUAL(records.count(ComboAddress("192.0.2.4")), 1U); @@ -1177,25 +1175,25 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheInspection) } { - auto records = PC.getRecordsForDomain(DNSName("powerdns2.com")); + auto records = localCache.getRecordsForDomain(DNSName("powerdns2.com")); BOOST_CHECK_EQUAL(records.size(), 0U); } { - auto records = PC.getRecordsForDomain(DNSName("powerdns3.com")); + auto records = localCache.getRecordsForDomain(DNSName("powerdns3.com")); BOOST_CHECK_EQUAL(records.size(), 2U); BOOST_CHECK_EQUAL(records.count(ComboAddress("2001:db8::4")), 1U); BOOST_CHECK_EQUAL(records.count(ComboAddress("2001:db8::4")), 1U); } { - auto records = PC.getRecordsForDomain(DNSName("powerdns4.com")); + auto records = localCache.getRecordsForDomain(DNSName("powerdns4.com")); BOOST_CHECK_EQUAL(records.size(), 1U); BOOST_CHECK_EQUAL(records.count(ComboAddress("192.0.2.1")), 1U); } { - auto records = PC.getRecordsForDomain(DNSName("powerdns5.com")); + auto records = localCache.getRecordsForDomain(DNSName("powerdns5.com")); BOOST_CHECK_EQUAL(records.size(), 0U); } } @@ -1203,8 +1201,8 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheInspection) BOOST_AUTO_TEST_CASE(test_PacketCacheXFR) { const size_t maxEntries = 150000; - DNSDistPacketCache PC(maxEntries, 86400, 1); - BOOST_CHECK_EQUAL(PC.getSize(), 0U); + DNSDistPacketCache localCache(maxEntries, 86400, 1); + BOOST_CHECK_EQUAL(localCache.getSize(), 0U); const std::set xfrTypes = {QType::AXFR, QType::IXFR}; for (const auto& type : xfrTypes) { @@ -1232,12 +1230,12 @@ BOOST_AUTO_TEST_CASE(test_PacketCacheXFR) uint32_t key = 0; boost::optional subnet; DNSQuestion dnsQuestion(ids, query); - bool found = PC.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); + bool found = localCache.get(dnsQuestion, 0, &key, subnet, dnssecOK, receivedOverUDP); BOOST_CHECK_EQUAL(found, false); BOOST_CHECK(!subnet); - PC.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, ids.qtype, ids.qclass, response, receivedOverUDP, 0, boost::none); - found = PC.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); + localCache.insert(key, subnet, *(getFlagsFromDNSHeader(dnsQuestion.getHeader().get())), dnssecOK, ids.qname, ids.qtype, ids.qclass, response, receivedOverUDP, 0, boost::none); + found = localCache.get(dnsQuestion, pwR.getHeader()->id, &key, subnet, dnssecOK, receivedOverUDP, 0, true); BOOST_CHECK_EQUAL(found, false); } } From e396e3b12645f84d3ab716dfa6f34db6dc2e2424 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 12:26:39 +0100 Subject: [PATCH 07/25] dnsdist: Delint dnsdist-dnscrypt.cc --- pdns/dnsdistdist/dnsdist-dnscrypt.cc | 6 +++--- pdns/dnsdistdist/dnsdist.hh | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-dnscrypt.cc b/pdns/dnsdistdist/dnsdist-dnscrypt.cc index 8f02910aaa8a..a7a776cba7fe 100644 --- a/pdns/dnsdistdist/dnsdist-dnscrypt.cc +++ b/pdns/dnsdistdist/dnsdist-dnscrypt.cc @@ -25,16 +25,16 @@ #include "dnscrypt.hh" #ifdef HAVE_DNSCRYPT -int handleDNSCryptQuery(PacketBuffer& packet, DNSCryptQuery& query, bool tcp, time_t now, PacketBuffer& response) +bool handleDNSCryptQuery(PacketBuffer& packet, DNSCryptQuery& query, bool tcp, time_t now, PacketBuffer& response) { query.parsePacket(packet, tcp, now); - if (query.isValid() == false) { + if (!query.isValid()) { vinfolog("Dropping DNSCrypt invalid query"); return false; } - if (query.isEncrypted() == false) { + if (!query.isEncrypted()) { query.getCertificateResponse(now, response); return false; diff --git a/pdns/dnsdistdist/dnsdist.hh b/pdns/dnsdistdist/dnsdist.hh index 9db31de62fd8..e345614be5d7 100644 --- a/pdns/dnsdistdist/dnsdist.hh +++ b/pdns/dnsdistdist/dnsdist.hh @@ -1241,7 +1241,7 @@ bool responseContentMatches(const PacketBuffer& response, const DNSName& qname, bool checkQueryHeaders(const struct dnsheader& dnsHeader, ClientState& clientState); extern std::vector> g_dnsCryptLocals; -int handleDNSCryptQuery(PacketBuffer& packet, DNSCryptQuery& query, bool tcp, time_t now, PacketBuffer& response); +bool handleDNSCryptQuery(PacketBuffer& packet, DNSCryptQuery& query, bool tcp, time_t now, PacketBuffer& response); bool checkDNSCryptQuery(const ClientState& cs, PacketBuffer& query, std::unique_ptr& dnsCryptQuery, time_t now, bool tcp); #include "dnsdist-snmp.hh" From 9269c14346ddda5d8cc2aa0bca3fa17c27efae1a Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 12:30:03 +0100 Subject: [PATCH 08/25] dnsdist: Delint test-dnsdist_cc.cc --- pdns/dnsdistdist/dnsdist-internal-queries.cc | 18 +- pdns/dnsdistdist/dnsdist-internal-queries.hh | 2 +- pdns/dnsdistdist/dnsdist.cc | 170 ++-- pdns/dnsdistdist/dnsdist.hh | 10 +- pdns/dnsdistdist/test-dnsdist_cc.cc | 964 ++++++++++--------- 5 files changed, 618 insertions(+), 546 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-internal-queries.cc b/pdns/dnsdistdist/dnsdist-internal-queries.cc index b707fefb9b5d..535062227df4 100644 --- a/pdns/dnsdistdist/dnsdist-internal-queries.cc +++ b/pdns/dnsdistdist/dnsdist-internal-queries.cc @@ -29,34 +29,34 @@ std::unique_ptr getUDPCrossProtocolQueryFromDQ(DNSQuestion& namespace dnsdist { -std::unique_ptr getInternalQueryFromDQ(DNSQuestion& dq, bool isResponse) +std::unique_ptr getInternalQueryFromDQ(DNSQuestion& dnsQuestion, bool isResponse) { - auto protocol = dq.getProtocol(); + auto protocol = dnsQuestion.getProtocol(); if (protocol == dnsdist::Protocol::DoUDP || protocol == dnsdist::Protocol::DNSCryptUDP) { - return getUDPCrossProtocolQueryFromDQ(dq); + return getUDPCrossProtocolQueryFromDQ(dnsQuestion); } #ifdef HAVE_DNS_OVER_HTTPS else if (protocol == dnsdist::Protocol::DoH) { #ifdef HAVE_LIBH2OEVLOOP - if (dq.ids.cs->dohFrontend->d_library == "h2o") { - return getDoHCrossProtocolQueryFromDQ(dq, isResponse); + if (dnsQuestion.ids.cs->dohFrontend->d_library == "h2o") { + return getDoHCrossProtocolQueryFromDQ(dnsQuestion, isResponse); } #endif /* HAVE_LIBH2OEVLOOP */ - return getTCPCrossProtocolQueryFromDQ(dq); + return getTCPCrossProtocolQueryFromDQ(dnsQuestion); } #endif #ifdef HAVE_DNS_OVER_QUIC else if (protocol == dnsdist::Protocol::DoQ) { - return getDOQCrossProtocolQueryFromDQ(dq, isResponse); + return getDOQCrossProtocolQueryFromDQ(dnsQuestion, isResponse); } #endif #ifdef HAVE_DNS_OVER_HTTP3 else if (protocol == dnsdist::Protocol::DoH3) { - return getDOH3CrossProtocolQueryFromDQ(dq, isResponse); + return getDOH3CrossProtocolQueryFromDQ(dnsQuestion, isResponse); } #endif else { - return getTCPCrossProtocolQueryFromDQ(dq); + return getTCPCrossProtocolQueryFromDQ(dnsQuestion); } } } diff --git a/pdns/dnsdistdist/dnsdist-internal-queries.hh b/pdns/dnsdistdist/dnsdist-internal-queries.hh index 46634aa11a8b..331f44d1a78b 100644 --- a/pdns/dnsdistdist/dnsdist-internal-queries.hh +++ b/pdns/dnsdistdist/dnsdist-internal-queries.hh @@ -26,5 +26,5 @@ namespace dnsdist { -std::unique_ptr getInternalQueryFromDQ(DNSQuestion& dq, bool isResponse); +std::unique_ptr getInternalQueryFromDQ(DNSQuestion& dnsQuestion, bool isResponse); } diff --git a/pdns/dnsdistdist/dnsdist.cc b/pdns/dnsdistdist/dnsdist.cc index 97f834ffd980..089f7ef00751 100644 --- a/pdns/dnsdistdist/dnsdist.cc +++ b/pdns/dnsdistdist/dnsdist.cc @@ -567,15 +567,15 @@ static bool applyRulesToResponse(const std::vector& r return true; } -bool processResponseAfterRules(PacketBuffer& response, const std::vector& cacheInsertedRespRuleActions, DNSResponse& dr, bool muted) +bool processResponseAfterRules(PacketBuffer& response, const std::vector& cacheInsertedRespRuleActions, DNSResponse& dnsResponse, bool muted) { bool zeroScope = false; - if (!fixUpResponse(response, dr.ids.qname, dr.ids.origFlags, dr.ids.ednsAdded, dr.ids.ecsAdded, dr.ids.useZeroScope ? &zeroScope : nullptr)) { + if (!fixUpResponse(response, dnsResponse.ids.qname, dnsResponse.ids.origFlags, dnsResponse.ids.ednsAdded, dnsResponse.ids.ecsAdded, dnsResponse.ids.useZeroScope ? &zeroScope : nullptr)) { return false; } - if (dr.ids.packetCache && !dr.ids.selfGenerated && !dr.ids.skipCache && (!dr.ids.forwardedOverUDP || response.size() <= s_maxUDPResponsePacketSize)) { - if (!dr.ids.useZeroScope) { + if (dnsResponse.ids.packetCache && !dnsResponse.ids.selfGenerated && !dnsResponse.ids.skipCache && (!dnsResponse.ids.forwardedOverUDP || response.size() <= s_maxUDPResponsePacketSize)) { + if (!dnsResponse.ids.useZeroScope) { /* if the query was not suitable for zero-scope, for example because it had an existing ECS entry so the hash is not really 'no ECS', so just insert it for the existing subnet @@ -586,35 +586,35 @@ bool processResponseAfterRules(PacketBuffer& response, const std::vectorinsert(cacheKey, zeroScope ? boost::none : dr.ids.subnet, dr.ids.cacheFlags, dr.ids.dnssecOK, dr.ids.qname, dr.ids.qtype, dr.ids.qclass, response, dr.ids.forwardedOverUDP, dr.getHeader()->rcode, dr.ids.tempFailureTTL); + dnsResponse.ids.packetCache->insert(cacheKey, zeroScope ? boost::none : dnsResponse.ids.subnet, dnsResponse.ids.cacheFlags, dnsResponse.ids.dnssecOK, dnsResponse.ids.qname, dnsResponse.ids.qtype, dnsResponse.ids.qclass, response, dnsResponse.ids.forwardedOverUDP, dnsResponse.getHeader()->rcode, dnsResponse.ids.tempFailureTTL); - if (!applyRulesToResponse(cacheInsertedRespRuleActions, dr)) { + if (!applyRulesToResponse(cacheInsertedRespRuleActions, dnsResponse)) { return false; } } - if (dr.ids.ttlCap > 0) { + if (dnsResponse.ids.ttlCap > 0) { std::string result; - LimitTTLResponseAction ac(0, dr.ids.ttlCap, {}); - ac(&dr, &result); + LimitTTLResponseAction ac(0, dnsResponse.ids.ttlCap, {}); + ac(&dnsResponse, &result); } - if (dr.ids.d_extendedError) { - dnsdist::edns::addExtendedDNSError(dr.getMutableData(), dr.getMaximumSize(), dr.ids.d_extendedError->infoCode, dr.ids.d_extendedError->extraText); + if (dnsResponse.ids.d_extendedError) { + dnsdist::edns::addExtendedDNSError(dnsResponse.getMutableData(), dnsResponse.getMaximumSize(), dnsResponse.ids.d_extendedError->infoCode, dnsResponse.ids.d_extendedError->extraText); } #ifdef HAVE_DNSCRYPT if (!muted) { - if (!encryptResponse(response, dr.getMaximumSize(), dr.overTCP(), dr.ids.dnsCryptQuery)) { + if (!encryptResponse(response, dnsResponse.getMaximumSize(), dnsResponse.overTCP(), dnsResponse.ids.dnsCryptQuery)) { return false; } } @@ -623,17 +623,17 @@ bool processResponseAfterRules(PacketBuffer& response, const std::vector& respRuleActions, const std::vector& cacheInsertedRespRuleActions, DNSResponse& dr, bool muted) +bool processResponse(PacketBuffer& response, const std::vector& respRuleActions, const std::vector& cacheInsertedRespRuleActions, DNSResponse& dnsResponse, bool muted) { - if (!applyRulesToResponse(respRuleActions, dr)) { + if (!applyRulesToResponse(respRuleActions, dnsResponse)) { return false; } - if (dr.isAsynchronous()) { + if (dnsResponse.isAsynchronous()) { return true; } - return processResponseAfterRules(response, cacheInsertedRespRuleActions, dr, muted); + return processResponseAfterRules(response, cacheInsertedRespRuleActions, dnsResponse, muted); } static size_t getInitialUDPPacketBufferSize(bool expectProxyProtocol) @@ -961,14 +961,14 @@ static void spoofPacketFromString(DNSQuestion& dq, const string& spoofContent) tempSpoofAction(&dq, &result); } -bool processRulesResult(const DNSAction::Action& action, DNSQuestion& dq, std::string& ruleresult, bool& drop) +bool processRulesResult(const DNSAction::Action& action, DNSQuestion& dnsQuestion, std::string& ruleresult, bool& drop) { - if (dq.isAsynchronous()) { + if (dnsQuestion.isAsynchronous()) { return false; } - auto setRCode = [&dq](uint8_t rcode) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [rcode](dnsheader& header) { + auto setRCode = [&dnsQuestion](uint8_t rcode) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [rcode](dnsheader& header) { header.rcode = rcode; header.qr = true; return true; @@ -997,20 +997,20 @@ bool processRulesResult(const DNSAction::Action& action, DNSQuestion& dq, std::s return true; break; case DNSAction::Action::Spoof: - spoofResponseFromString(dq, ruleresult, false); + spoofResponseFromString(dnsQuestion, ruleresult, false); return true; break; case DNSAction::Action::SpoofPacket: - spoofPacketFromString(dq, ruleresult); + spoofPacketFromString(dnsQuestion, ruleresult); return true; break; case DNSAction::Action::SpoofRaw: - spoofResponseFromString(dq, ruleresult, true); + spoofResponseFromString(dnsQuestion, ruleresult, true); return true; break; case DNSAction::Action::Truncate: - if (!dq.overTCP()) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [](dnsheader& header) { + if (!dnsQuestion.overTCP()) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [](dnsheader& header) { header.tc = true; header.qr = true; header.ra = header.rd; @@ -1028,11 +1028,11 @@ bool processRulesResult(const DNSAction::Action& action, DNSQuestion& dq, std::s case DNSAction::Action::Pool: /* we need to keep this because a custom Lua action can return DNSAction.Spoof, 'poolname' */ - dq.ids.poolName = ruleresult; + dnsQuestion.ids.poolName = ruleresult; return true; break; case DNSAction::Action::NoRecurse: - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [](dnsheader& header) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [](dnsheader& header) { header.rd = false; return true; }); @@ -1040,7 +1040,7 @@ bool processRulesResult(const DNSAction::Action& action, DNSQuestion& dq, std::s break; /* non-terminal actions follow */ case DNSAction::Action::Delay: - pdns::checked_stoi_into(dq.ids.delayMsec, ruleresult); // sorry + pdns::checked_stoi_into(dnsQuestion.ids.delayMsec, ruleresult); // sorry break; case DNSAction::Action::None: /* fall-through */ @@ -1416,19 +1416,19 @@ static bool prepareOutgoingResponse(LocalHolders& holders, const ClientState& cs return true; } -ProcessQueryResult processQueryAfterRules(DNSQuestion& dq, LocalHolders& holders, std::shared_ptr& selectedBackend) +ProcessQueryResult processQueryAfterRules(DNSQuestion& dnsQuestion, LocalHolders& holders, std::shared_ptr& selectedBackend) { - const uint16_t queryId = ntohs(dq.getHeader()->id); + const uint16_t queryId = ntohs(dnsQuestion.getHeader()->id); try { - if (dq.getHeader()->qr) { // something turned it into a response - fixUpQueryTurnedResponse(dq, dq.ids.origFlags); + if (dnsQuestion.getHeader()->qr) { // something turned it into a response + fixUpQueryTurnedResponse(dnsQuestion, dnsQuestion.ids.origFlags); - if (!prepareOutgoingResponse(holders, *dq.ids.cs, dq, false)) { + if (!prepareOutgoingResponse(holders, *dnsQuestion.ids.cs, dnsQuestion, false)) { return ProcessQueryResult::Drop; } - const auto rcode = dq.getHeader()->rcode; + const auto rcode = dnsQuestion.getHeader()->rcode; if (rcode == RCode::NXDomain) { ++dnsdist::metrics::g_stats.ruleNXDomain; } @@ -1440,91 +1440,91 @@ ProcessQueryResult processQueryAfterRules(DNSQuestion& dq, LocalHolders& holders } ++dnsdist::metrics::g_stats.selfAnswered; - ++dq.ids.cs->responses; + ++dnsQuestion.ids.cs->responses; return ProcessQueryResult::SendAnswer; } - std::shared_ptr serverPool = getPool(*holders.pools, dq.ids.poolName); + std::shared_ptr serverPool = getPool(*holders.pools, dnsQuestion.ids.poolName); std::shared_ptr poolPolicy = serverPool->policy; - dq.ids.packetCache = serverPool->packetCache; + dnsQuestion.ids.packetCache = serverPool->packetCache; const auto& policy = poolPolicy != nullptr ? *poolPolicy : *(holders.policy); const auto servers = serverPool->getServers(); - selectedBackend = policy.getSelectedBackend(*servers, dq); + selectedBackend = policy.getSelectedBackend(*servers, dnsQuestion); uint32_t allowExpired = selectedBackend ? 0 : g_staleCacheEntriesTTL; - if (dq.ids.packetCache && !dq.ids.skipCache) { - dq.ids.dnssecOK = (getEDNSZ(dq) & EDNS_HEADER_FLAG_DO); + if (dnsQuestion.ids.packetCache && !dnsQuestion.ids.skipCache) { + dnsQuestion.ids.dnssecOK = (getEDNSZ(dnsQuestion) & EDNS_HEADER_FLAG_DO); } - if (dq.useECS && ((selectedBackend && selectedBackend->d_config.useECS) || (!selectedBackend && serverPool->getECS()))) { + if (dnsQuestion.useECS && ((selectedBackend && selectedBackend->d_config.useECS) || (!selectedBackend && serverPool->getECS()))) { // we special case our cache in case a downstream explicitly gave us a universally valid response with a 0 scope // we need ECS parsing (parseECS) to be true so we can be sure that the initial incoming query did not have an existing // ECS option, which would make it unsuitable for the zero-scope feature. - if (dq.ids.packetCache && !dq.ids.skipCache && (!selectedBackend || !selectedBackend->d_config.disableZeroScope) && dq.ids.packetCache->isECSParsingEnabled()) { - if (dq.ids.packetCache->get(dq, dq.getHeader()->id, &dq.ids.cacheKeyNoECS, dq.ids.subnet, dq.ids.dnssecOK, !dq.overTCP(), allowExpired, false, true, false)) { + if (dnsQuestion.ids.packetCache && !dnsQuestion.ids.skipCache && (!selectedBackend || !selectedBackend->d_config.disableZeroScope) && dnsQuestion.ids.packetCache->isECSParsingEnabled()) { + if (dnsQuestion.ids.packetCache->get(dnsQuestion, dnsQuestion.getHeader()->id, &dnsQuestion.ids.cacheKeyNoECS, dnsQuestion.ids.subnet, dnsQuestion.ids.dnssecOK, !dnsQuestion.overTCP(), allowExpired, false, true, false)) { - vinfolog("Packet cache hit for query for %s|%s from %s (%s, %d bytes)", dq.ids.qname.toLogString(), QType(dq.ids.qtype).toString(), dq.ids.origRemote.toStringWithPort(), dq.ids.protocol.toString(), dq.getData().size()); + vinfolog("Packet cache hit for query for %s|%s from %s (%s, %d bytes)", dnsQuestion.ids.qname.toLogString(), QType(dnsQuestion.ids.qtype).toString(), dnsQuestion.ids.origRemote.toStringWithPort(), dnsQuestion.ids.protocol.toString(), dnsQuestion.getData().size()); - if (!prepareOutgoingResponse(holders, *dq.ids.cs, dq, true)) { + if (!prepareOutgoingResponse(holders, *dnsQuestion.ids.cs, dnsQuestion, true)) { return ProcessQueryResult::Drop; } ++dnsdist::metrics::g_stats.responses; - ++dq.ids.cs->responses; + ++dnsQuestion.ids.cs->responses; return ProcessQueryResult::SendAnswer; } - if (!dq.ids.subnet) { + if (!dnsQuestion.ids.subnet) { /* there was no existing ECS on the query, enable the zero-scope feature */ - dq.ids.useZeroScope = true; + dnsQuestion.ids.useZeroScope = true; } } - if (!handleEDNSClientSubnet(dq, dq.ids.ednsAdded, dq.ids.ecsAdded)) { - vinfolog("Dropping query from %s because we couldn't insert the ECS value", dq.ids.origRemote.toStringWithPort()); + if (!handleEDNSClientSubnet(dnsQuestion, dnsQuestion.ids.ednsAdded, dnsQuestion.ids.ecsAdded)) { + vinfolog("Dropping query from %s because we couldn't insert the ECS value", dnsQuestion.ids.origRemote.toStringWithPort()); return ProcessQueryResult::Drop; } } - if (dq.ids.packetCache && !dq.ids.skipCache) { - bool forwardedOverUDP = !dq.overTCP(); + if (dnsQuestion.ids.packetCache && !dnsQuestion.ids.skipCache) { + bool forwardedOverUDP = !dnsQuestion.overTCP(); if (selectedBackend && selectedBackend->isTCPOnly()) { forwardedOverUDP = false; } /* we do not record a miss for queries received over DoH and forwarded over TCP yet, as we will do a second-lookup */ - if (dq.ids.packetCache->get(dq, dq.getHeader()->id, &dq.ids.cacheKey, dq.ids.subnet, dq.ids.dnssecOK, forwardedOverUDP, allowExpired, false, true, dq.ids.protocol != dnsdist::Protocol::DoH || forwardedOverUDP)) { + if (dnsQuestion.ids.packetCache->get(dnsQuestion, dnsQuestion.getHeader()->id, &dnsQuestion.ids.cacheKey, dnsQuestion.ids.subnet, dnsQuestion.ids.dnssecOK, forwardedOverUDP, allowExpired, false, true, dnsQuestion.ids.protocol != dnsdist::Protocol::DoH || forwardedOverUDP)) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [flags = dq.ids.origFlags](dnsheader& header) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [flags = dnsQuestion.ids.origFlags](dnsheader& header) { restoreFlags(&header, flags); return true; }); - vinfolog("Packet cache hit for query for %s|%s from %s (%s, %d bytes)", dq.ids.qname.toLogString(), QType(dq.ids.qtype).toString(), dq.ids.origRemote.toStringWithPort(), dq.ids.protocol.toString(), dq.getData().size()); + vinfolog("Packet cache hit for query for %s|%s from %s (%s, %d bytes)", dnsQuestion.ids.qname.toLogString(), QType(dnsQuestion.ids.qtype).toString(), dnsQuestion.ids.origRemote.toStringWithPort(), dnsQuestion.ids.protocol.toString(), dnsQuestion.getData().size()); - if (!prepareOutgoingResponse(holders, *dq.ids.cs, dq, true)) { + if (!prepareOutgoingResponse(holders, *dnsQuestion.ids.cs, dnsQuestion, true)) { return ProcessQueryResult::Drop; } ++dnsdist::metrics::g_stats.responses; - ++dq.ids.cs->responses; + ++dnsQuestion.ids.cs->responses; return ProcessQueryResult::SendAnswer; } - else if (dq.ids.protocol == dnsdist::Protocol::DoH && !forwardedOverUDP) { + else if (dnsQuestion.ids.protocol == dnsdist::Protocol::DoH && !forwardedOverUDP) { /* do a second-lookup for UDP responses, but we do not want TC=1 answers */ - if (dq.ids.packetCache->get(dq, dq.getHeader()->id, &dq.ids.cacheKeyUDP, dq.ids.subnet, dq.ids.dnssecOK, true, allowExpired, false, false, true)) { - if (!prepareOutgoingResponse(holders, *dq.ids.cs, dq, true)) { + if (dnsQuestion.ids.packetCache->get(dnsQuestion, dnsQuestion.getHeader()->id, &dnsQuestion.ids.cacheKeyUDP, dnsQuestion.ids.subnet, dnsQuestion.ids.dnssecOK, true, allowExpired, false, false, true)) { + if (!prepareOutgoingResponse(holders, *dnsQuestion.ids.cs, dnsQuestion, true)) { return ProcessQueryResult::Drop; } ++dnsdist::metrics::g_stats.responses; - ++dq.ids.cs->responses; + ++dnsQuestion.ids.cs->responses; return ProcessQueryResult::SendAnswer; } } - vinfolog("Packet cache miss for query for %s|%s from %s (%s, %d bytes)", dq.ids.qname.toLogString(), QType(dq.ids.qtype).toString(), dq.ids.origRemote.toStringWithPort(), dq.ids.protocol.toString(), dq.getData().size()); + vinfolog("Packet cache miss for query for %s|%s from %s (%s, %d bytes)", dnsQuestion.ids.qname.toLogString(), QType(dnsQuestion.ids.qtype).toString(), dnsQuestion.ids.origRemote.toStringWithPort(), dnsQuestion.ids.protocol.toString(), dnsQuestion.getData().size()); ++dnsdist::metrics::g_stats.cacheMisses; } @@ -1532,21 +1532,21 @@ ProcessQueryResult processQueryAfterRules(DNSQuestion& dq, LocalHolders& holders if (!selectedBackend) { ++dnsdist::metrics::g_stats.noPolicy; - vinfolog("%s query for %s|%s from %s, no downstream server available", g_servFailOnNoPolicy ? "ServFailed" : "Dropped", dq.ids.qname.toLogString(), QType(dq.ids.qtype).toString(), dq.ids.origRemote.toStringWithPort()); + vinfolog("%s query for %s|%s from %s, no downstream server available", g_servFailOnNoPolicy ? "ServFailed" : "Dropped", dnsQuestion.ids.qname.toLogString(), QType(dnsQuestion.ids.qtype).toString(), dnsQuestion.ids.origRemote.toStringWithPort()); if (g_servFailOnNoPolicy) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [](dnsheader& header) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [](dnsheader& header) { header.rcode = RCode::ServFail; header.qr = true; return true; }); - fixUpQueryTurnedResponse(dq, dq.ids.origFlags); + fixUpQueryTurnedResponse(dnsQuestion, dnsQuestion.ids.origFlags); - if (!prepareOutgoingResponse(holders, *dq.ids.cs, dq, false)) { + if (!prepareOutgoingResponse(holders, *dnsQuestion.ids.cs, dnsQuestion, false)) { return ProcessQueryResult::Drop; } ++dnsdist::metrics::g_stats.responses; - ++dq.ids.cs->responses; + ++dnsQuestion.ids.cs->responses; // no response-only statistics counter to update. return ProcessQueryResult::SendAnswer; } @@ -1555,24 +1555,24 @@ ProcessQueryResult processQueryAfterRules(DNSQuestion& dq, LocalHolders& holders } /* save the DNS flags as sent to the backend so we can cache the answer with the right flags later */ - dq.ids.cacheFlags = *getFlagsFromDNSHeader(dq.getHeader().get()); + dnsQuestion.ids.cacheFlags = *getFlagsFromDNSHeader(dnsQuestion.getHeader().get()); - if (dq.addXPF && selectedBackend->d_config.xpfRRCode != 0) { - addXPF(dq, selectedBackend->d_config.xpfRRCode); + if (dnsQuestion.addXPF && selectedBackend->d_config.xpfRRCode != 0) { + addXPF(dnsQuestion, selectedBackend->d_config.xpfRRCode); } - if (selectedBackend->d_config.useProxyProtocol && dq.getProtocol().isEncrypted() && selectedBackend->d_config.d_proxyProtocolAdvertiseTLS) { - if (!dq.proxyProtocolValues) { - dq.proxyProtocolValues = std::make_unique>(); + if (selectedBackend->d_config.useProxyProtocol && dnsQuestion.getProtocol().isEncrypted() && selectedBackend->d_config.d_proxyProtocolAdvertiseTLS) { + if (!dnsQuestion.proxyProtocolValues) { + dnsQuestion.proxyProtocolValues = std::make_unique>(); } - dq.proxyProtocolValues->push_back(ProxyProtocolValue{"", static_cast(ProxyProtocolValue::Types::PP_TLV_SSL)}); + dnsQuestion.proxyProtocolValues->push_back(ProxyProtocolValue{"", static_cast(ProxyProtocolValue::Types::PP_TLV_SSL)}); } selectedBackend->incQueriesCount(); return ProcessQueryResult::PassToBackend; } catch (const std::exception& e) { - vinfolog("Got an error while parsing a %s query (after applying rules) from %s, id %d: %s", (dq.overTCP() ? "TCP" : "UDP"), dq.ids.origRemote.toStringWithPort(), queryId, e.what()); + vinfolog("Got an error while parsing a %s query (after applying rules) from %s, id %d: %s", (dnsQuestion.overTCP() ? "TCP" : "UDP"), dnsQuestion.ids.origRemote.toStringWithPort(), queryId, e.what()); } return ProcessQueryResult::Drop; } @@ -1658,9 +1658,9 @@ std::unique_ptr getUDPCrossProtocolQueryFromDQ(DNSQuestion& return std::make_unique(std::move(dq.getMutableData()), std::move(dq.ids), nullptr); } -ProcessQueryResult processQuery(DNSQuestion& dq, LocalHolders& holders, std::shared_ptr& selectedBackend) +ProcessQueryResult processQuery(DNSQuestion& dnsQuestion, LocalHolders& holders, std::shared_ptr& selectedBackend) { - const uint16_t queryId = ntohs(dq.getHeader()->id); + const uint16_t queryId = ntohs(dnsQuestion.getHeader()->id); try { /* we need an accurate ("real") value for the response and @@ -1669,18 +1669,18 @@ ProcessQueryResult processQuery(DNSQuestion& dq, LocalHolders& holders, std::sha struct timespec now; gettime(&now); - if (!applyRulesToQuery(holders, dq, now)) { + if (!applyRulesToQuery(holders, dnsQuestion, now)) { return ProcessQueryResult::Drop; } - if (dq.isAsynchronous()) { + if (dnsQuestion.isAsynchronous()) { return ProcessQueryResult::Asynchronous; } - return processQueryAfterRules(dq, holders, selectedBackend); + return processQueryAfterRules(dnsQuestion, holders, selectedBackend); } catch (const std::exception& e) { - vinfolog("Got an error while parsing a %s query from %s, id %d: %s", (dq.overTCP() ? "TCP" : "UDP"), dq.ids.origRemote.toStringWithPort(), queryId, e.what()); + vinfolog("Got an error while parsing a %s query from %s, id %d: %s", (dnsQuestion.overTCP() ? "TCP" : "UDP"), dnsQuestion.ids.origRemote.toStringWithPort(), queryId, e.what()); } return ProcessQueryResult::Drop; } diff --git a/pdns/dnsdistdist/dnsdist.hh b/pdns/dnsdistdist/dnsdist.hh index e345614be5d7..064e0e867881 100644 --- a/pdns/dnsdistdist/dnsdist.hh +++ b/pdns/dnsdistdist/dnsdist.hh @@ -1261,11 +1261,11 @@ enum class ProcessQueryResult : uint8_t PassToBackend, Asynchronous }; -ProcessQueryResult processQuery(DNSQuestion& dq, LocalHolders& holders, std::shared_ptr& selectedBackend); -ProcessQueryResult processQueryAfterRules(DNSQuestion& dq, LocalHolders& holders, std::shared_ptr& selectedBackend); -bool processResponse(PacketBuffer& response, const std::vector& respRuleActions, const std::vector& insertedRespRuleActions, DNSResponse& dr, bool muted); -bool processRulesResult(const DNSAction::Action& action, DNSQuestion& dq, std::string& ruleresult, bool& drop); -bool processResponseAfterRules(PacketBuffer& response, const std::vector& cacheInsertedRespRuleActions, DNSResponse& dr, bool muted); +ProcessQueryResult processQuery(DNSQuestion& dnsQuestion, LocalHolders& holders, std::shared_ptr& selectedBackend); +ProcessQueryResult processQueryAfterRules(DNSQuestion& dnsQuestion, LocalHolders& holders, std::shared_ptr& selectedBackend); +bool processResponse(PacketBuffer& response, const std::vector& respRuleActions, const std::vector& insertedRespRuleActions, DNSResponse& dnsResponse, bool muted); +bool processRulesResult(const DNSAction::Action& action, DNSQuestion& dnsQuestion, std::string& ruleresult, bool& drop); +bool processResponseAfterRules(PacketBuffer& response, const std::vector& cacheInsertedRespRuleActions, DNSResponse& dnsResponse, bool muted); bool processResponderPacket(std::shared_ptr& dss, PacketBuffer& response, const std::vector& localRespRuleActions, const std::vector& cacheInsertedRespRuleActions, InternalQueryState&& ids); bool assignOutgoingUDPQueryToBackend(std::shared_ptr& downstream, uint16_t queryID, DNSQuestion& dnsQuestion, PacketBuffer& query, bool actuallySend = true); diff --git a/pdns/dnsdistdist/test-dnsdist_cc.cc b/pdns/dnsdistdist/test-dnsdist_cc.cc index 1254c7e35708..79fcd5e8fc6e 100644 --- a/pdns/dnsdistdist/test-dnsdist_cc.cc +++ b/pdns/dnsdistdist/test-dnsdist_cc.cc @@ -43,12 +43,12 @@ #include "ednscookies.hh" #include "ednssubnet.hh" -ProcessQueryResult processQueryAfterRules(DNSQuestion& dq, LocalHolders& holders, std::shared_ptr& selectedBackend) +ProcessQueryResult processQueryAfterRules(DNSQuestion& dnsQuestion, LocalHolders& holders, std::shared_ptr& selectedBackend) { return ProcessQueryResult::Drop; } -bool processResponseAfterRules(PacketBuffer& response, const std::vector& cacheInsertedRespRuleActions, DNSResponse& dr, bool muted) +bool processResponseAfterRules(PacketBuffer& response, const std::vector& cacheInsertedRespRuleActions, DNSResponse& dnsResponse, bool muted) { return false; } @@ -65,13 +65,14 @@ bool assignOutgoingUDPQueryToBackend(std::shared_ptr& downstrea namespace dnsdist { -std::unique_ptr getInternalQueryFromDQ(DNSQuestion& dq, bool isResponse) +std::unique_ptr getInternalQueryFromDQ(DNSQuestion& dnsQuestion, bool isResponse) { return nullptr; } } -bool DNSDistSNMPAgent::sendBackendStatusChangeTrap(DownstreamState const&) +// NOLINTNEXTLINE(readability-convert-member-functions-to-static): only a stub +bool DNSDistSNMPAgent::sendBackendStatusChangeTrap([[maybe_unused]] DownstreamState const& backend) { return false; } @@ -95,6 +96,7 @@ static const uint16_t ECSSourcePrefixV6 = 56; static void validateQuery(const PacketBuffer& packet, bool hasEdns = true, bool hasXPF = false, uint16_t additionals = 0, uint16_t answers = 0, uint16_t authorities = 0) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); BOOST_CHECK_EQUAL(mdp.d_qname.toString(), "www.powerdns.com."); @@ -111,13 +113,15 @@ static void validateECS(const PacketBuffer& packet, const ComboAddress& expected InternalQueryState ids; ids.protocol = dnsdist::Protocol::DoUDP; ids.origRemote = ComboAddress("::1"); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); - DNSQuestion dq(ids, const_cast(packet)); - BOOST_CHECK(parseEDNSOptions(dq)); - BOOST_REQUIRE(dq.ednsOptions != nullptr); - BOOST_CHECK_EQUAL(dq.ednsOptions->size(), 1U); - const auto& ecsOption = dq.ednsOptions->find(EDNSOptionCode::ECS); - BOOST_REQUIRE(ecsOption != dq.ednsOptions->cend()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + DNSQuestion dnsQuestion(ids, const_cast(packet)); + BOOST_CHECK(parseEDNSOptions(dnsQuestion)); + BOOST_REQUIRE(dnsQuestion.ednsOptions != nullptr); + BOOST_CHECK_EQUAL(dnsQuestion.ednsOptions->size(), 1U); + const auto& ecsOption = dnsQuestion.ednsOptions->find(EDNSOptionCode::ECS); + BOOST_REQUIRE(ecsOption != dnsQuestion.ednsOptions->cend()); string expectedOption; generateECSOption(expected, expectedOption, expected.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); @@ -128,6 +132,7 @@ static void validateECS(const PacketBuffer& packet, const ComboAddress& expected static void validateResponse(const PacketBuffer& packet, bool hasEdns, uint8_t additionalCount = 0) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) MOADNSParser mdp(false, reinterpret_cast(packet.data()), packet.size()); BOOST_CHECK_EQUAL(mdp.d_qname.toString(), "www.powerdns.com."); @@ -150,20 +155,22 @@ BOOST_AUTO_TEST_CASE(test_addXPF) ids.origDest = ComboAddress("::1"); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; PacketBuffer queryWithXPF; { PacketBuffer packet = query; /* large enough packet */ + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); - DNSQuestion dq(ids, const_cast(packet)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + DNSQuestion dnsQuestion(ids, const_cast(packet)); BOOST_CHECK_EQUAL(ids.qname, name); BOOST_CHECK(ids.qtype == QType::A); - BOOST_CHECK(addXPF(dq, xpfOptionCode)); + BOOST_CHECK(addXPF(dnsQuestion, xpfOptionCode)); BOOST_CHECK(packet.size() > query.size()); validateQuery(packet, false, true); queryWithXPF = packet; @@ -174,12 +181,14 @@ BOOST_AUTO_TEST_CASE(test_addXPF) /* packet is already too large for the 4096 limit over UDP */ packet.resize(4096); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); - DNSQuestion dq(ids, const_cast(packet)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + DNSQuestion dnsQuestion(ids, const_cast(packet)); BOOST_CHECK_EQUAL(ids.qname, name); BOOST_CHECK(ids.qtype == QType::A); - BOOST_REQUIRE(!addXPF(dq, xpfOptionCode)); + BOOST_REQUIRE(!addXPF(dnsQuestion, xpfOptionCode)); BOOST_CHECK_EQUAL(packet.size(), 4096U); packet.resize(query.size()); validateQuery(packet, false, false); @@ -189,8 +198,10 @@ BOOST_AUTO_TEST_CASE(test_addXPF) PacketBuffer packet = query; /* packet with trailing data (overriding it) */ + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); - DNSQuestion dq(ids, const_cast(packet)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + DNSQuestion dnsQuestion(ids, const_cast(packet)); BOOST_CHECK_EQUAL(ids.qname, name); BOOST_CHECK(ids.qtype == QType::A); @@ -202,7 +213,7 @@ BOOST_AUTO_TEST_CASE(test_addXPF) packet.push_back('A'); } - BOOST_CHECK(addXPF(dq, xpfOptionCode)); + BOOST_CHECK(addXPF(dnsQuestion, xpfOptionCode)); BOOST_CHECK_EQUAL(packet.size(), queryWithXPF.size()); BOOST_CHECK_EQUAL(memcmp(queryWithXPF.data(), packet.data(), queryWithXPF.size()), 0); validateQuery(packet, false, true); @@ -219,15 +230,16 @@ BOOST_AUTO_TEST_CASE(addECSWithoutEDNS) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; uint16_t len = query.size(); /* large enough packet */ PacketBuffer packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -246,6 +258,7 @@ BOOST_AUTO_TEST_CASE(addECSWithoutEDNS) ednsAdded = false; ecsAdded = false; consumed = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -261,6 +274,7 @@ BOOST_AUTO_TEST_CASE(addECSWithoutEDNS) ednsAdded = false; ecsAdded = false; consumed = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -294,18 +308,19 @@ BOOST_AUTO_TEST_CASE(addECSWithoutEDNSButWithAnswer) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; - pw.startRecord(name, QType::A, 60, QClass::IN, DNSResourceRecord::ANSWER, false); - pw.xfrIP(remote.sin4.sin_addr.s_addr); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; + packetWriter.startRecord(name, QType::A, 60, QClass::IN, DNSResourceRecord::ANSWER, false); + packetWriter.xfrIP(remote.sin4.sin_addr.s_addr); + packetWriter.commit(); uint16_t len = query.size(); /* large enough packet */ PacketBuffer packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -324,6 +339,7 @@ BOOST_AUTO_TEST_CASE(addECSWithoutEDNSButWithAnswer) ednsAdded = false; ecsAdded = false; consumed = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -339,6 +355,7 @@ BOOST_AUTO_TEST_CASE(addECSWithoutEDNSButWithAnswer) ednsAdded = false; ecsAdded = false; consumed = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -368,22 +385,22 @@ BOOST_AUTO_TEST_CASE(addECSWithoutEDNSAlreadyParsed) DNSName name("www.powerdns.com."); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; auto packet = query; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); BOOST_CHECK_EQUAL(ids.qname, name); BOOST_CHECK(ids.qtype == QType::A); BOOST_CHECK(ids.qclass == QClass::IN); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); /* Parse the options before handling ECS, simulating a Lua rule asking for EDNS Options */ - BOOST_CHECK(!parseEDNSOptions(dq)); + BOOST_CHECK(!parseEDNSOptions(dnsQuestion)); /* And now we add our own ECS */ - BOOST_CHECK(handleEDNSClientSubnet(dq, ednsAdded, ecsAdded)); + BOOST_CHECK(handleEDNSClientSubnet(dnsQuestion, ednsAdded, ecsAdded)); BOOST_CHECK_GT(packet.size(), query.size()); BOOST_CHECK_EQUAL(ednsAdded, true); BOOST_CHECK_EQUAL(ecsAdded, true); @@ -396,14 +413,14 @@ BOOST_AUTO_TEST_CASE(addECSWithoutEDNSAlreadyParsed) ednsAdded = false; ecsAdded = false; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); BOOST_CHECK_EQUAL(ids.qname, name); BOOST_CHECK(ids.qtype == QType::A); BOOST_CHECK(ids.qclass == QClass::IN); - DNSQuestion dq2(ids, packet); + DNSQuestion dnsQuestion2(ids, packet); - BOOST_CHECK(handleEDNSClientSubnet(dq2, ednsAdded, ecsAdded)); + BOOST_CHECK(handleEDNSClientSubnet(dnsQuestion2, ednsAdded, ecsAdded)); BOOST_CHECK_GT(packet.size(), query.size()); BOOST_CHECK_LT(packet.size(), 2048U); BOOST_CHECK_EQUAL(ednsAdded, true); @@ -422,15 +439,16 @@ BOOST_AUTO_TEST_CASE(addECSWithEDNSNoECS) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; - pw.addOpt(512, 0, 0); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; + packetWriter.addOpt(512, 0, 0); + packetWriter.commit(); auto packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -447,7 +465,7 @@ BOOST_AUTO_TEST_CASE(addECSWithEDNSNoECS) ednsAdded = false; ecsAdded = false; packet = query; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -469,24 +487,24 @@ BOOST_AUTO_TEST_CASE(addECSWithEDNSNoECSAlreadyParsed) DNSName name("www.powerdns.com."); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; - pw.addOpt(512, 0, 0); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; + packetWriter.addOpt(512, 0, 0); + packetWriter.commit(); auto packet = query; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); BOOST_CHECK_EQUAL(ids.qname, name); BOOST_CHECK(ids.qtype == QType::A); BOOST_CHECK(ids.qclass == QClass::IN); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); /* Parse the options before handling ECS, simulating a Lua rule asking for EDNS Options */ - BOOST_CHECK(parseEDNSOptions(dq)); + BOOST_CHECK(parseEDNSOptions(dnsQuestion)); /* And now we add our own ECS */ - BOOST_CHECK(handleEDNSClientSubnet(dq, ednsAdded, ecsAdded)); + BOOST_CHECK(handleEDNSClientSubnet(dnsQuestion, ednsAdded, ecsAdded)); BOOST_CHECK_GT(packet.size(), query.size()); BOOST_CHECK_EQUAL(ednsAdded, false); BOOST_CHECK_EQUAL(ecsAdded, true); @@ -498,13 +516,14 @@ BOOST_AUTO_TEST_CASE(addECSWithEDNSNoECSAlreadyParsed) packet.resize(2048); ednsAdded = false; ecsAdded = false; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); BOOST_CHECK_EQUAL(ids.qname, name); BOOST_CHECK(ids.qtype == QType::A); BOOST_CHECK(ids.qclass == QClass::IN); - DNSQuestion dq2(ids, packet); + DNSQuestion dnsQuestion2(ids, packet); - BOOST_CHECK(handleEDNSClientSubnet(dq2, ednsAdded, ecsAdded)); + BOOST_CHECK(handleEDNSClientSubnet(dnsQuestion2, ednsAdded, ecsAdded)); BOOST_CHECK_GT(packet.size(), query.size()); BOOST_CHECK_LT(packet.size(), 2048U); BOOST_CHECK_EQUAL(ednsAdded, false); @@ -524,21 +543,22 @@ BOOST_AUTO_TEST_CASE(replaceECSWithSameSize) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, ECSSourcePrefixV4); string origECSOption = makeEDNSSubnetOptsString(ecsOpts); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOption); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); /* large enough packet */ auto packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -563,34 +583,35 @@ BOOST_AUTO_TEST_CASE(replaceECSWithSameSizeAlreadyParsed) ids.qname = DNSName("www.powerdns.com."); PacketBuffer query; - GenericDNSPacketWriter pw(query, ids.qname, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; + GenericDNSPacketWriter packetWriter(query, ids.qname, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, ECSSourcePrefixV4); string origECSOption = makeEDNSSubnetOptsString(ecsOpts); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOption); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); auto packet = query; unsigned int consumed = 0; - uint16_t qtype; - uint16_t qclass; + uint16_t qtype = 0; + uint16_t qclass = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, &qclass, &consumed); BOOST_CHECK_EQUAL(qname, ids.qname); BOOST_CHECK(qtype == QType::A); BOOST_CHECK(qclass == QClass::IN); - DNSQuestion dq(ids, packet); - dq.ecsOverride = true; + DNSQuestion dnsQuestion(ids, packet); + dnsQuestion.ecsOverride = true; /* Parse the options before handling ECS, simulating a Lua rule asking for EDNS Options */ - BOOST_CHECK(parseEDNSOptions(dq)); + BOOST_CHECK(parseEDNSOptions(dnsQuestion)); /* And now we add our own ECS */ - BOOST_CHECK(handleEDNSClientSubnet(dq, ednsAdded, ecsAdded)); + BOOST_CHECK(handleEDNSClientSubnet(dnsQuestion, ednsAdded, ecsAdded)); BOOST_CHECK_EQUAL(packet.size(), query.size()); BOOST_CHECK_EQUAL(ednsAdded, false); BOOST_CHECK_EQUAL(ecsAdded, false); @@ -609,20 +630,21 @@ BOOST_AUTO_TEST_CASE(replaceECSWithSmaller) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, 32); string origECSOption = makeEDNSSubnetOptsString(ecsOpts); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOption); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); auto packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -646,8 +668,8 @@ BOOST_AUTO_TEST_CASE(replaceECSWithLarger) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; EDNSSubnetOpts ecsOpts; // smaller (less specific so less bits) option static_assert(8 < ECSSourcePrefixV4, "The ECS scope should be smaller"); @@ -655,14 +677,15 @@ BOOST_AUTO_TEST_CASE(replaceECSWithLarger) string origECSOption = makeEDNSSubnetOptsString(ecsOpts); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOption); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); /* large enough packet */ auto packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -680,6 +703,7 @@ BOOST_AUTO_TEST_CASE(replaceECSWithLarger) ednsAdded = false; ecsAdded = false; consumed = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -702,22 +726,23 @@ BOOST_AUTO_TEST_CASE(replaceECSFollowedByTSIG) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, 8); string origECSOption = makeEDNSSubnetOptsString(ecsOpts); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOption); - pw.addOpt(512, 0, 0, opts); - pw.startRecord(DNSName("tsigname."), QType::TSIG, 0, QClass::ANY, DNSResourceRecord::ADDITIONAL, false); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.startRecord(DNSName("tsigname."), QType::TSIG, 0, QClass::ANY, DNSResourceRecord::ADDITIONAL, false); + packetWriter.commit(); /* large enough packet */ auto packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -735,6 +760,7 @@ BOOST_AUTO_TEST_CASE(replaceECSFollowedByTSIG) ednsAdded = false; ecsAdded = false; consumed = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -757,23 +783,24 @@ BOOST_AUTO_TEST_CASE(replaceECSAfterAN) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; - pw.startRecord(DNSName("powerdns.com."), QType::A, 0, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; + packetWriter.startRecord(DNSName("powerdns.com."), QType::A, 0, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.commit(); EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, 8); string origECSOption = makeEDNSSubnetOptsString(ecsOpts); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOption); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); /* large enough packet */ auto packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -791,6 +818,7 @@ BOOST_AUTO_TEST_CASE(replaceECSAfterAN) ednsAdded = false; ecsAdded = false; consumed = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -813,23 +841,24 @@ BOOST_AUTO_TEST_CASE(replaceECSAfterAuth) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; - pw.startRecord(DNSName("powerdns.com."), QType::A, 0, QClass::IN, DNSResourceRecord::AUTHORITY, true); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; + packetWriter.startRecord(DNSName("powerdns.com."), QType::A, 0, QClass::IN, DNSResourceRecord::AUTHORITY, true); + packetWriter.commit(); EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, 8); string origECSOption = makeEDNSSubnetOptsString(ecsOpts); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOption); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); /* large enough packet */ auto packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -847,6 +876,7 @@ BOOST_AUTO_TEST_CASE(replaceECSAfterAuth) ednsAdded = false; ecsAdded = false; consumed = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -869,24 +899,25 @@ BOOST_AUTO_TEST_CASE(replaceECSBetweenTwoRecords) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, 8); string origECSOption = makeEDNSSubnetOptsString(ecsOpts); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOption); - pw.startRecord(DNSName("additional"), QType::A, 0, QClass::IN, DNSResourceRecord::ADDITIONAL, false); - pw.xfr32BitInt(0x01020304); - pw.addOpt(512, 0, 0, opts); - pw.startRecord(DNSName("tsigname."), QType::TSIG, 0, QClass::ANY, DNSResourceRecord::ADDITIONAL, false); - pw.commit(); + packetWriter.startRecord(DNSName("additional"), QType::A, 0, QClass::IN, DNSResourceRecord::ADDITIONAL, false); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.startRecord(DNSName("tsigname."), QType::TSIG, 0, QClass::ANY, DNSResourceRecord::ADDITIONAL, false); + packetWriter.commit(); /* large enough packet */ auto packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -904,6 +935,7 @@ BOOST_AUTO_TEST_CASE(replaceECSBetweenTwoRecords) ednsAdded = false; ecsAdded = false; consumed = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -926,19 +958,20 @@ BOOST_AUTO_TEST_CASE(insertECSInEDNSBetweenTwoRecords) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; - pw.startRecord(DNSName("additional"), QType::A, 0, QClass::IN, DNSResourceRecord::ADDITIONAL, false); - pw.xfr32BitInt(0x01020304); - pw.addOpt(512, 0, 0); - pw.startRecord(DNSName("tsigname."), QType::TSIG, 0, QClass::ANY, DNSResourceRecord::ADDITIONAL, false); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; + packetWriter.startRecord(DNSName("additional"), QType::A, 0, QClass::IN, DNSResourceRecord::ADDITIONAL, false); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.addOpt(512, 0, 0); + packetWriter.startRecord(DNSName("tsigname."), QType::TSIG, 0, QClass::ANY, DNSResourceRecord::ADDITIONAL, false); + packetWriter.commit(); /* large enough packet */ auto packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -956,6 +989,7 @@ BOOST_AUTO_TEST_CASE(insertECSInEDNSBetweenTwoRecords) ednsAdded = false; ecsAdded = false; consumed = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -978,16 +1012,17 @@ BOOST_AUTO_TEST_CASE(insertECSAfterTSIG) generateECSOption(remote, newECSOption, remote.sin4.sin_family == AF_INET ? ECSSourcePrefixV4 : ECSSourcePrefixV6); PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; - pw.startRecord(DNSName("tsigname."), QType::TSIG, 0, QClass::ANY, DNSResourceRecord::ADDITIONAL, false); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; + packetWriter.startRecord(DNSName("tsigname."), QType::TSIG, 0, QClass::ANY, DNSResourceRecord::ADDITIONAL, false); + packetWriter.commit(); /* large enough packet */ auto packet = query; unsigned int consumed = 0; - uint16_t qtype; + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -1006,6 +1041,7 @@ BOOST_AUTO_TEST_CASE(insertECSAfterTSIG) ednsAdded = false; ecsAdded = false; consumed = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -1022,23 +1058,24 @@ BOOST_AUTO_TEST_CASE(removeEDNSWhenFirst) DNSName name("www.powerdns.com."); PacketBuffer response; - GenericDNSPacketWriter pw(response, name, QType::A, QClass::IN, 0); - pw.getHeader()->qr = 1; - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.xfr32BitInt(0x01020304); - pw.addOpt(512, 0, 0); - pw.commit(); - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); + GenericDNSPacketWriter packetWriter(response, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.addOpt(512, 0, 0); + packetWriter.commit(); + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); PacketBuffer newResponse; int res = rewriteResponseWithoutEDNS(response, newResponse); BOOST_CHECK_EQUAL(res, 0); unsigned int consumed = 0; - uint16_t qtype; - DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + DNSName qname(reinterpret_cast(newResponse.data()), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); size_t const ednsOptRRSize = sizeof(struct dnsrecordheader) + 1 /* root in OPT RR */; @@ -1052,26 +1089,27 @@ BOOST_AUTO_TEST_CASE(removeEDNSWhenIntermediary) DNSName name("www.powerdns.com."); PacketBuffer response; - GenericDNSPacketWriter pw(response, name, QType::A, QClass::IN, 0); - pw.getHeader()->qr = 1; - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.xfr32BitInt(0x01020304); - pw.startRecord(DNSName("other.powerdns.com."), QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); - pw.addOpt(512, 0, 0); - pw.commit(); - pw.startRecord(DNSName("yetanother.powerdns.com."), QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); + GenericDNSPacketWriter packetWriter(response, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.startRecord(DNSName("other.powerdns.com."), QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); + packetWriter.addOpt(512, 0, 0); + packetWriter.commit(); + packetWriter.startRecord(DNSName("yetanother.powerdns.com."), QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); PacketBuffer newResponse; int res = rewriteResponseWithoutEDNS(response, newResponse); BOOST_CHECK_EQUAL(res, 0); unsigned int consumed = 0; - uint16_t qtype; - DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + DNSName qname(reinterpret_cast(newResponse.data()), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); size_t const ednsOptRRSize = sizeof(struct dnsrecordheader) + 1 /* root in OPT RR */; @@ -1085,16 +1123,16 @@ BOOST_AUTO_TEST_CASE(removeEDNSWhenLast) DNSName name("www.powerdns.com."); PacketBuffer response; - GenericDNSPacketWriter pw(response, name, QType::A, QClass::IN, 0); - pw.getHeader()->qr = 1; - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); - pw.startRecord(DNSName("other.powerdns.com."), QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); - pw.addOpt(512, 0, 0); - pw.commit(); + GenericDNSPacketWriter packetWriter(response, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); + packetWriter.startRecord(DNSName("other.powerdns.com."), QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); + packetWriter.addOpt(512, 0, 0); + packetWriter.commit(); PacketBuffer newResponse; int res = rewriteResponseWithoutEDNS(response, newResponse); @@ -1102,8 +1140,9 @@ BOOST_AUTO_TEST_CASE(removeEDNSWhenLast) BOOST_CHECK_EQUAL(res, 0); unsigned int consumed = 0; - uint16_t qtype; - DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + DNSName qname(reinterpret_cast(newResponse.data()), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); size_t const ednsOptRRSize = sizeof(struct dnsrecordheader) + 1 /* root in OPT RR */; @@ -1118,24 +1157,24 @@ BOOST_AUTO_TEST_CASE(removeECSWhenOnlyOption) ComboAddress origRemote("127.0.0.1"); PacketBuffer response; - GenericDNSPacketWriter pw(response, name, QType::A, QClass::IN, 0); - pw.getHeader()->qr = 1; - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.xfr32BitInt(0x01020304); + GenericDNSPacketWriter packetWriter(response, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.xfr32BitInt(0x01020304); - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, ECSSourcePrefixV4); string origECSOptionStr = makeEDNSSubnetOptsString(ecsOpts); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOptionStr); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); - uint16_t optStart; + uint16_t optStart = 0; size_t optLen = 0; bool last = false; @@ -1146,14 +1185,16 @@ BOOST_AUTO_TEST_CASE(removeECSWhenOnlyOption) size_t responseLen = response.size(); size_t existingOptLen = optLen; BOOST_CHECK(existingOptLen < responseLen); - res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + res = removeEDNSOptionFromOPT(reinterpret_cast(&response.at(optStart)), &optLen, EDNSOptionCode::ECS); BOOST_CHECK_EQUAL(res, 0); BOOST_CHECK_EQUAL(optLen, existingOptLen - (origECSOptionStr.size() + 4)); responseLen -= (existingOptLen - optLen); unsigned int consumed = 0; - uint16_t qtype; - DNSName qname((const char*)response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + DNSName qname(reinterpret_cast(response.data()), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -1166,14 +1207,14 @@ BOOST_AUTO_TEST_CASE(removeECSWhenFirstOption) ComboAddress origRemote("127.0.0.1"); PacketBuffer response; - GenericDNSPacketWriter pw(response, name, QType::A, QClass::IN, 0); - pw.getHeader()->qr = 1; - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.xfr32BitInt(0x01020304); + GenericDNSPacketWriter packetWriter(response, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.xfr32BitInt(0x01020304); - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, ECSSourcePrefixV6); @@ -1183,10 +1224,10 @@ BOOST_AUTO_TEST_CASE(removeECSWhenFirstOption) GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOptionStr); opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); - uint16_t optStart; + uint16_t optStart = 0; size_t optLen = 0; bool last = false; @@ -1197,14 +1238,16 @@ BOOST_AUTO_TEST_CASE(removeECSWhenFirstOption) size_t responseLen = response.size(); size_t existingOptLen = optLen; BOOST_CHECK(existingOptLen < responseLen); - res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + res = removeEDNSOptionFromOPT(reinterpret_cast(&response.at(optStart)), &optLen, EDNSOptionCode::ECS); BOOST_CHECK_EQUAL(res, 0); BOOST_CHECK_EQUAL(optLen, existingOptLen - (origECSOptionStr.size() + 4)); responseLen -= (existingOptLen - optLen); unsigned int consumed = 0; - uint16_t qtype; - DNSName qname((const char*)response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + DNSName qname(reinterpret_cast(response.data()), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -1217,14 +1260,14 @@ BOOST_AUTO_TEST_CASE(removeECSWhenIntermediaryOption) ComboAddress origRemote("127.0.0.1"); PacketBuffer response; - GenericDNSPacketWriter pw(response, name, QType::A, QClass::IN, 0); - pw.getHeader()->qr = 1; - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.xfr32BitInt(0x01020304); + GenericDNSPacketWriter packetWriter(response, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.xfr32BitInt(0x01020304); - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, ECSSourcePrefixV4); @@ -1238,10 +1281,10 @@ BOOST_AUTO_TEST_CASE(removeECSWhenIntermediaryOption) opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr1); opts.emplace_back(EDNSOptionCode::ECS, origECSOptionStr); opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr2); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); - uint16_t optStart; + uint16_t optStart = 0; size_t optLen = 0; bool last = false; @@ -1252,14 +1295,16 @@ BOOST_AUTO_TEST_CASE(removeECSWhenIntermediaryOption) size_t responseLen = response.size(); size_t existingOptLen = optLen; BOOST_CHECK(existingOptLen < responseLen); - res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + res = removeEDNSOptionFromOPT(reinterpret_cast(&response.at(optStart)), &optLen, EDNSOptionCode::ECS); BOOST_CHECK_EQUAL(res, 0); BOOST_CHECK_EQUAL(optLen, existingOptLen - (origECSOptionStr.size() + 4)); responseLen -= (existingOptLen - optLen); unsigned int consumed = 0; - uint16_t qtype; - DNSName qname((const char*)response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + DNSName qname(reinterpret_cast(response.data()), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -1272,14 +1317,14 @@ BOOST_AUTO_TEST_CASE(removeECSWhenLastOption) ComboAddress origRemote("127.0.0.1"); PacketBuffer response; - GenericDNSPacketWriter pw(response, name, QType::A, QClass::IN, 0); - pw.getHeader()->qr = 1; - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.xfr32BitInt(0x01020304); + GenericDNSPacketWriter packetWriter(response, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.xfr32BitInt(0x01020304); - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); EDNSCookiesOpt cookiesOpt("deadbeefdeadbeef"); string cookiesOptionStr = cookiesOpt.makeOptString(); @@ -1289,10 +1334,10 @@ BOOST_AUTO_TEST_CASE(removeECSWhenLastOption) GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr); opts.emplace_back(EDNSOptionCode::ECS, origECSOptionStr); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); - uint16_t optStart; + uint16_t optStart = 0; size_t optLen = 0; bool last = false; @@ -1303,14 +1348,16 @@ BOOST_AUTO_TEST_CASE(removeECSWhenLastOption) size_t responseLen = response.size(); size_t existingOptLen = optLen; BOOST_CHECK(existingOptLen < responseLen); - res = removeEDNSOptionFromOPT(reinterpret_cast(response.data()) + optStart, &optLen, EDNSOptionCode::ECS); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + res = removeEDNSOptionFromOPT(reinterpret_cast(&response.at(optStart)), &optLen, EDNSOptionCode::ECS); BOOST_CHECK_EQUAL(res, 0); BOOST_CHECK_EQUAL(optLen, existingOptLen - (origECSOptionStr.size() + 4)); responseLen -= (existingOptLen - optLen); unsigned int consumed = 0; - uint16_t qtype; - DNSName qname((const char*)response.data(), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + DNSName qname(reinterpret_cast(response.data()), responseLen, sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -1323,22 +1370,22 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenOnlyOption) ComboAddress origRemote("127.0.0.1"); PacketBuffer response; - GenericDNSPacketWriter pw(response, name, QType::A, QClass::IN, 0); - pw.getHeader()->qr = 1; - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.xfr32BitInt(0x01020304); + GenericDNSPacketWriter packetWriter(response, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.xfr32BitInt(0x01020304); EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, ECSSourcePrefixV4); string origECSOptionStr = makeEDNSSubnetOptsString(ecsOpts); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOptionStr); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); PacketBuffer newResponse; int res = rewriteResponseWithoutEDNSOption(response, EDNSOptionCode::ECS, newResponse); @@ -1347,8 +1394,9 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenOnlyOption) BOOST_CHECK_EQUAL(newResponse.size(), response.size() - (origECSOptionStr.size() + 4)); unsigned int consumed = 0; - uint16_t qtype; - DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + DNSName qname(reinterpret_cast(newResponse.data()), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -1361,10 +1409,10 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenFirstOption) ComboAddress origRemote("127.0.0.1"); PacketBuffer response; - GenericDNSPacketWriter pw(response, name, QType::A, QClass::IN, 0); - pw.getHeader()->qr = 1; - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.xfr32BitInt(0x01020304); + GenericDNSPacketWriter packetWriter(response, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.xfr32BitInt(0x01020304); EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, ECSSourcePrefixV4); @@ -1374,12 +1422,12 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenFirstOption) GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, origECSOptionStr); opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); PacketBuffer newResponse; int res = rewriteResponseWithoutEDNSOption(response, EDNSOptionCode::ECS, newResponse); @@ -1388,8 +1436,9 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenFirstOption) BOOST_CHECK_EQUAL(newResponse.size(), response.size() - (origECSOptionStr.size() + 4)); unsigned int consumed = 0; - uint16_t qtype; - DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + DNSName qname(reinterpret_cast(newResponse.data()), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -1402,10 +1451,10 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenIntermediaryOption) ComboAddress origRemote("127.0.0.1"); PacketBuffer response; - GenericDNSPacketWriter pw(response, name, QType::A, QClass::IN, 0); - pw.getHeader()->qr = 1; - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.xfr32BitInt(0x01020304); + GenericDNSPacketWriter packetWriter(response, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.xfr32BitInt(0x01020304); EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, ECSSourcePrefixV4); @@ -1417,12 +1466,12 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenIntermediaryOption) opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr1); opts.emplace_back(EDNSOptionCode::ECS, origECSOptionStr); opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr2); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); PacketBuffer newResponse; int res = rewriteResponseWithoutEDNSOption(response, EDNSOptionCode::ECS, newResponse); @@ -1431,8 +1480,9 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenIntermediaryOption) BOOST_CHECK_EQUAL(newResponse.size(), response.size() - (origECSOptionStr.size() + 4)); unsigned int consumed = 0; - uint16_t qtype; - DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + DNSName qname(reinterpret_cast(newResponse.data()), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -1445,10 +1495,10 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenLastOption) ComboAddress origRemote("127.0.0.1"); PacketBuffer response; - GenericDNSPacketWriter pw(response, name, QType::A, QClass::IN, 0); - pw.getHeader()->qr = 1; - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); - pw.xfr32BitInt(0x01020304); + GenericDNSPacketWriter packetWriter(response, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ANSWER, true); + packetWriter.xfr32BitInt(0x01020304); EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(origRemote, ECSSourcePrefixV4); @@ -1458,12 +1508,12 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenLastOption) GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr); opts.emplace_back(EDNSOptionCode::ECS, origECSOptionStr); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); - pw.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); - pw.xfr32BitInt(0x01020304); - pw.commit(); + packetWriter.startRecord(name, QType::A, 3600, QClass::IN, DNSResourceRecord::ADDITIONAL, true); + packetWriter.xfr32BitInt(0x01020304); + packetWriter.commit(); PacketBuffer newResponse; int res = rewriteResponseWithoutEDNSOption(response, EDNSOptionCode::ECS, newResponse); @@ -1472,8 +1522,9 @@ BOOST_AUTO_TEST_CASE(rewritingWithoutECSWhenLastOption) BOOST_CHECK_EQUAL(newResponse.size(), response.size() - (origECSOptionStr.size() + 4)); unsigned int consumed = 0; - uint16_t qtype; - DNSName qname((const char*)newResponse.data(), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); + uint16_t qtype = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + DNSName qname(reinterpret_cast(newResponse.data()), newResponse.size(), sizeof(dnsheader), false, &qtype, nullptr, &consumed); BOOST_CHECK_EQUAL(qname, name); BOOST_CHECK(qtype == QType::A); @@ -1486,11 +1537,11 @@ static DNSQuestion turnIntoResponse(InternalQueryState& ids, PacketBuffer& query query.resize(4096); } - auto dq = DNSQuestion(ids, query); + auto dnsQuestion = DNSQuestion(ids, query); - BOOST_CHECK(addEDNSToQueryTurnedResponse(dq)); + BOOST_CHECK(addEDNSToQueryTurnedResponse(dnsQuestion)); - return dq; + return dnsQuestion; } static int getZ(const DNSName& qname, const uint16_t qtype, const uint16_t qclass, PacketBuffer& query) @@ -1504,16 +1555,15 @@ static int getZ(const DNSName& qname, const uint16_t qtype, const uint16_t qclas ids.origRemote = ComboAddress("127.0.0.1"); ids.queryRealTime.start(); - auto dq = DNSQuestion(ids, query); + auto dnsQuestion = DNSQuestion(ids, query); - return getEDNSZ(dq); + return getEDNSZ(dnsQuestion); } BOOST_AUTO_TEST_CASE(test_getEDNSZ) { - - uint16_t z; - uint16_t udpPayloadSize; + uint16_t zValue = 0; + uint16_t udpPayloadSize = 0; DNSName qname("www.powerdns.com."); uint16_t qtype = QType::A; uint16_t qclass = QClass::IN; @@ -1529,78 +1579,84 @@ BOOST_AUTO_TEST_CASE(test_getEDNSZ) { /* no EDNS */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); + packetWriter.commit(); BOOST_CHECK_EQUAL(getZ(qname, qtype, qclass, query), 0); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &z), false); - BOOST_CHECK_EQUAL(z, 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &zValue), false); + BOOST_CHECK_EQUAL(zValue, 0); BOOST_CHECK_EQUAL(udpPayloadSize, 0); } { /* truncated EDNS */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); - pw.addOpt(512, 0, EDNS_HEADER_FLAG_DO); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); + packetWriter.addOpt(512, 0, EDNS_HEADER_FLAG_DO); + packetWriter.commit(); query.resize(query.size() - (/* RDLEN */ sizeof(uint16_t) + /* last byte of TTL / Z */ 1)); BOOST_CHECK_EQUAL(getZ(qname, qtype, qclass, query), 0); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &z), false); - BOOST_CHECK_EQUAL(z, 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &zValue), false); + BOOST_CHECK_EQUAL(zValue, 0); BOOST_CHECK_EQUAL(udpPayloadSize, 0); } { /* valid EDNS, no options, DO not set */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); - pw.addOpt(512, 0, 0); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); + packetWriter.addOpt(512, 0, 0); + packetWriter.commit(); BOOST_CHECK_EQUAL(getZ(qname, qtype, qclass, query), 0); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &z), true); - BOOST_CHECK_EQUAL(z, 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &zValue), true); + BOOST_CHECK_EQUAL(zValue, 0); BOOST_CHECK_EQUAL(udpPayloadSize, 512); } { /* valid EDNS, no options, DO set */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); - pw.addOpt(512, 0, EDNS_HEADER_FLAG_DO); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); + packetWriter.addOpt(512, 0, EDNS_HEADER_FLAG_DO); + packetWriter.commit(); BOOST_CHECK_EQUAL(getZ(qname, qtype, qclass, query), EDNS_HEADER_FLAG_DO); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &z), true); - BOOST_CHECK_EQUAL(z, EDNS_HEADER_FLAG_DO); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &zValue), true); + BOOST_CHECK_EQUAL(zValue, EDNS_HEADER_FLAG_DO); BOOST_CHECK_EQUAL(udpPayloadSize, 512); } { /* valid EDNS, options, DO not set */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); BOOST_CHECK_EQUAL(getZ(qname, qtype, qclass, query), 0); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &z), true); - BOOST_CHECK_EQUAL(z, 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &zValue), true); + BOOST_CHECK_EQUAL(zValue, 0); BOOST_CHECK_EQUAL(udpPayloadSize, 512); } { /* valid EDNS, options, DO set */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); - pw.addOpt(512, 0, EDNS_HEADER_FLAG_DO, opts); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); + packetWriter.addOpt(512, 0, EDNS_HEADER_FLAG_DO, opts); + packetWriter.commit(); BOOST_CHECK_EQUAL(getZ(qname, qtype, qclass, query), EDNS_HEADER_FLAG_DO); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &z), true); - BOOST_CHECK_EQUAL(z, EDNS_HEADER_FLAG_DO); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(query.data()), query.size(), &udpPayloadSize, &zValue), true); + BOOST_CHECK_EQUAL(zValue, EDNS_HEADER_FLAG_DO); BOOST_CHECK_EQUAL(udpPayloadSize, 512); } } @@ -1614,8 +1670,8 @@ BOOST_AUTO_TEST_CASE(test_addEDNSToQueryTurnedResponse) ids.origDest = ComboAddress("127.0.0.1"); ids.origRemote = ComboAddress("127.0.0.1"); ids.queryRealTime.start(); - uint16_t z; - uint16_t udpPayloadSize; + uint16_t zValue = 0; + uint16_t udpPayloadSize = 0; EDNSSubnetOpts ecsOpts; ecsOpts.source = Netmask(ComboAddress("127.0.0.1"), ECSSourcePrefixV4); string origECSOptionStr = makeEDNSSubnetOptsString(ecsOpts); @@ -1628,86 +1684,92 @@ BOOST_AUTO_TEST_CASE(test_addEDNSToQueryTurnedResponse) { /* no EDNS */ PacketBuffer query; - GenericDNSPacketWriter pw(query, ids.qname, ids.qtype, ids.qclass, 0); - pw.getHeader()->qr = 1; - pw.getHeader()->rcode = RCode::NXDomain; - pw.commit(); - - auto dq = turnIntoResponse(ids, query); - BOOST_CHECK_EQUAL(getEDNSZ(dq), 0); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dq.getData().data()), dq.getData().size(), &udpPayloadSize, &z), false); - BOOST_CHECK_EQUAL(z, 0); + GenericDNSPacketWriter packetWriter(query, ids.qname, ids.qtype, ids.qclass, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.getHeader()->rcode = RCode::NXDomain; + packetWriter.commit(); + + auto dnsQuestion = turnIntoResponse(ids, query); + BOOST_CHECK_EQUAL(getEDNSZ(dnsQuestion), 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dnsQuestion.getData().data()), dnsQuestion.getData().size(), &udpPayloadSize, &zValue), false); + BOOST_CHECK_EQUAL(zValue, 0); BOOST_CHECK_EQUAL(udpPayloadSize, 0); } { /* truncated EDNS */ PacketBuffer query; - GenericDNSPacketWriter pw(query, ids.qname, ids.qtype, ids.qclass, 0); - pw.addOpt(512, 0, EDNS_HEADER_FLAG_DO); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, ids.qname, ids.qtype, ids.qclass, 0); + packetWriter.addOpt(512, 0, EDNS_HEADER_FLAG_DO); + packetWriter.commit(); query.resize(query.size() - (/* RDLEN */ sizeof(uint16_t) + /* last byte of TTL / Z */ 1)); - auto dq = turnIntoResponse(ids, query, false); - BOOST_CHECK_EQUAL(getEDNSZ(dq), 0); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dq.getData().data()), dq.getData().size(), &udpPayloadSize, &z), false); - BOOST_CHECK_EQUAL(z, 0); + auto dnsQuestion = turnIntoResponse(ids, query, false); + BOOST_CHECK_EQUAL(getEDNSZ(dnsQuestion), 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dnsQuestion.getData().data()), dnsQuestion.getData().size(), &udpPayloadSize, &zValue), false); + BOOST_CHECK_EQUAL(zValue, 0); BOOST_CHECK_EQUAL(udpPayloadSize, 0); } { /* valid EDNS, no options, DO not set */ PacketBuffer query; - GenericDNSPacketWriter pw(query, ids.qname, ids.qtype, ids.qclass, 0); - pw.addOpt(512, 0, 0); - pw.commit(); - - auto dq = turnIntoResponse(ids, query); - BOOST_CHECK_EQUAL(getEDNSZ(dq), 0); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dq.getData().data()), dq.getData().size(), &udpPayloadSize, &z), true); - BOOST_CHECK_EQUAL(z, 0); + GenericDNSPacketWriter packetWriter(query, ids.qname, ids.qtype, ids.qclass, 0); + packetWriter.addOpt(512, 0, 0); + packetWriter.commit(); + + auto dnsQuestion = turnIntoResponse(ids, query); + BOOST_CHECK_EQUAL(getEDNSZ(dnsQuestion), 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dnsQuestion.getData().data()), dnsQuestion.getData().size(), &udpPayloadSize, &zValue), true); + BOOST_CHECK_EQUAL(zValue, 0); BOOST_CHECK_EQUAL(udpPayloadSize, g_PayloadSizeSelfGenAnswers); } { /* valid EDNS, no options, DO set */ PacketBuffer query; - GenericDNSPacketWriter pw(query, ids.qname, ids.qtype, ids.qclass, 0); - pw.addOpt(512, 0, EDNS_HEADER_FLAG_DO); - pw.commit(); - - auto dq = turnIntoResponse(ids, query); - BOOST_CHECK_EQUAL(getEDNSZ(dq), EDNS_HEADER_FLAG_DO); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dq.getData().data()), dq.getData().size(), &udpPayloadSize, &z), true); - BOOST_CHECK_EQUAL(z, EDNS_HEADER_FLAG_DO); + GenericDNSPacketWriter packetWriter(query, ids.qname, ids.qtype, ids.qclass, 0); + packetWriter.addOpt(512, 0, EDNS_HEADER_FLAG_DO); + packetWriter.commit(); + + auto dnsQuestion = turnIntoResponse(ids, query); + BOOST_CHECK_EQUAL(getEDNSZ(dnsQuestion), EDNS_HEADER_FLAG_DO); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dnsQuestion.getData().data()), dnsQuestion.getData().size(), &udpPayloadSize, &zValue), true); + BOOST_CHECK_EQUAL(zValue, EDNS_HEADER_FLAG_DO); BOOST_CHECK_EQUAL(udpPayloadSize, g_PayloadSizeSelfGenAnswers); } { /* valid EDNS, options, DO not set */ PacketBuffer query; - GenericDNSPacketWriter pw(query, ids.qname, ids.qtype, ids.qclass, 0); - pw.addOpt(512, 0, 0, opts); - pw.commit(); - - auto dq = turnIntoResponse(ids, query); - BOOST_CHECK_EQUAL(getEDNSZ(dq), 0); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dq.getData().data()), dq.getData().size(), &udpPayloadSize, &z), true); - BOOST_CHECK_EQUAL(z, 0); + GenericDNSPacketWriter packetWriter(query, ids.qname, ids.qtype, ids.qclass, 0); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); + + auto dnsQuestion = turnIntoResponse(ids, query); + BOOST_CHECK_EQUAL(getEDNSZ(dnsQuestion), 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dnsQuestion.getData().data()), dnsQuestion.getData().size(), &udpPayloadSize, &zValue), true); + BOOST_CHECK_EQUAL(zValue, 0); BOOST_CHECK_EQUAL(udpPayloadSize, g_PayloadSizeSelfGenAnswers); } { /* valid EDNS, options, DO set */ PacketBuffer query; - GenericDNSPacketWriter pw(query, ids.qname, ids.qtype, ids.qclass, 0); - pw.addOpt(512, 0, EDNS_HEADER_FLAG_DO, opts); - pw.commit(); - - auto dq = turnIntoResponse(ids, query); - BOOST_CHECK_EQUAL(getEDNSZ(dq), EDNS_HEADER_FLAG_DO); - BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dq.getData().data()), dq.getData().size(), &udpPayloadSize, &z), true); - BOOST_CHECK_EQUAL(z, EDNS_HEADER_FLAG_DO); + GenericDNSPacketWriter packetWriter(query, ids.qname, ids.qtype, ids.qclass, 0); + packetWriter.addOpt(512, 0, EDNS_HEADER_FLAG_DO, opts); + packetWriter.commit(); + + auto dnsQuestion = turnIntoResponse(ids, query); + BOOST_CHECK_EQUAL(getEDNSZ(dnsQuestion), EDNS_HEADER_FLAG_DO); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + BOOST_CHECK_EQUAL(getEDNSUDPPayloadSizeAndZ(reinterpret_cast(dnsQuestion.getData().data()), dnsQuestion.getData().size(), &udpPayloadSize, &zValue), true); + BOOST_CHECK_EQUAL(zValue, EDNS_HEADER_FLAG_DO); BOOST_CHECK_EQUAL(udpPayloadSize, g_PayloadSizeSelfGenAnswers); } } @@ -1722,20 +1784,19 @@ BOOST_AUTO_TEST_CASE(test_getEDNSOptionsStart) const string ecsOptionStr = makeEDNSSubnetOptsString(ecsOpts); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, ecsOptionStr); - const ComboAddress lc("127.0.0.1"); const ComboAddress rem("127.0.0.1"); - uint16_t optRDPosition; - size_t remaining; + uint16_t optRDPosition = 0; + size_t remaining = 0; const size_t optRDExpectedOffset = sizeof(dnsheader) + qname.wirelength() + DNS_TYPE_SIZE + DNS_CLASS_SIZE + /* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE + DNS_TTL_SIZE; { /* no EDNS */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); - pw.getHeader()->qr = 1; - pw.getHeader()->rcode = RCode::NXDomain; - pw.commit(); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.getHeader()->rcode = RCode::NXDomain; + packetWriter.commit(); int res = getEDNSOptionsStart(query, qname.wirelength(), &optRDPosition, &remaining); @@ -1751,9 +1812,9 @@ BOOST_AUTO_TEST_CASE(test_getEDNSOptionsStart) { /* valid EDNS, no options */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); - pw.addOpt(512, 0, 0); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); + packetWriter.addOpt(512, 0, 0); + packetWriter.commit(); int res = getEDNSOptionsStart(query, qname.wirelength(), &optRDPosition, &remaining); @@ -1771,9 +1832,9 @@ BOOST_AUTO_TEST_CASE(test_getEDNSOptionsStart) { /* valid EDNS, options */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); int res = getEDNSOptionsStart(query, qname.wirelength(), &optRDPosition, &remaining); @@ -1794,8 +1855,8 @@ BOOST_AUTO_TEST_CASE(test_isEDNSOptionInOpt) { auto locateEDNSOption = [](const PacketBuffer& query, uint16_t code, size_t* optContentStart, uint16_t* optContentLen) { - uint16_t optStart; - size_t optLen; + uint16_t optStart = 0; + size_t optLen = 0; bool last = false; int res = locateEDNSOptRR(query, &optStart, &optLen, &last); if (res != 0) { @@ -1832,7 +1893,6 @@ BOOST_AUTO_TEST_CASE(test_isEDNSOptionInOpt) opts.emplace_back(EDNSOptionCode::ECS, ecsOptionStr); opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr); */ - const ComboAddress lc("127.0.0.1"); const ComboAddress rem("127.0.0.1"); size_t optContentStart{std::numeric_limits::max()}; uint16_t optContentLen{0}; @@ -1842,10 +1902,10 @@ BOOST_AUTO_TEST_CASE(test_isEDNSOptionInOpt) { /* no EDNS */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); - pw.getHeader()->qr = 1; - pw.getHeader()->rcode = RCode::NXDomain; - pw.commit(); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); + packetWriter.getHeader()->qr = 1; + packetWriter.getHeader()->rcode = RCode::NXDomain; + packetWriter.commit(); bool found = locateEDNSOption(query, EDNSOptionCode::ECS, &optContentStart, &optContentLen); BOOST_CHECK_EQUAL(found, false); @@ -1859,9 +1919,9 @@ BOOST_AUTO_TEST_CASE(test_isEDNSOptionInOpt) { /* valid EDNS, no options */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); - pw.addOpt(512, 0, 0); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); + packetWriter.addOpt(512, 0, 0); + packetWriter.commit(); bool found = locateEDNSOption(query, EDNSOptionCode::ECS, &optContentStart, &optContentLen); BOOST_CHECK_EQUAL(found, false); @@ -1874,12 +1934,12 @@ BOOST_AUTO_TEST_CASE(test_isEDNSOptionInOpt) { /* valid EDNS, two cookie options but no ECS */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr); opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); bool found = locateEDNSOption(query, EDNSOptionCode::ECS, &optContentStart, &optContentLen); BOOST_CHECK_EQUAL(found, false); @@ -1892,16 +1952,16 @@ BOOST_AUTO_TEST_CASE(test_isEDNSOptionInOpt) { /* valid EDNS, two ECS */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, ecsOptionStr); opts.emplace_back(EDNSOptionCode::ECS, ecsOptionStr); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); bool found = locateEDNSOption(query, EDNSOptionCode::ECS, &optContentStart, &optContentLen); BOOST_CHECK_EQUAL(found, true); - if (found == true) { + if (found) { BOOST_CHECK_EQUAL(optContentStart, optRDExpectedOffset + sizeof(uint16_t) /* RD len */ + /* option code */ 2 + /* option length */ 2); BOOST_CHECK_EQUAL(optContentLen, sizeOfECSContent); } @@ -1914,17 +1974,17 @@ BOOST_AUTO_TEST_CASE(test_isEDNSOptionInOpt) { /* valid EDNS, one ECS between two cookies */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr); opts.emplace_back(EDNSOptionCode::ECS, ecsOptionStr); opts.emplace_back(EDNSOptionCode::COOKIE, cookiesOptionStr); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); bool found = locateEDNSOption(query, EDNSOptionCode::ECS, &optContentStart, &optContentLen); BOOST_CHECK_EQUAL(found, true); - if (found == true) { + if (found) { BOOST_CHECK_EQUAL(optContentStart, optRDExpectedOffset + sizeof(uint16_t) /* RD len */ + sizeOfCookieOption + /* option code */ 2 + /* option length */ 2); BOOST_CHECK_EQUAL(optContentLen, sizeOfECSContent); } @@ -1937,16 +1997,16 @@ BOOST_AUTO_TEST_CASE(test_isEDNSOptionInOpt) { /* valid EDNS, one 65002 after an ECS */ PacketBuffer query; - GenericDNSPacketWriter pw(query, qname, qtype, qclass, 0); + GenericDNSPacketWriter packetWriter(query, qname, qtype, qclass, 0); GenericDNSPacketWriter::optvect_t opts; opts.emplace_back(EDNSOptionCode::ECS, ecsOptionStr); opts.emplace_back(65535, cookiesOptionStr); - pw.addOpt(512, 0, 0, opts); - pw.commit(); + packetWriter.addOpt(512, 0, 0, opts); + packetWriter.commit(); bool found = locateEDNSOption(query, 65535, &optContentStart, &optContentLen); BOOST_CHECK_EQUAL(found, true); - if (found == true) { + if (found) { BOOST_CHECK_EQUAL(optContentStart, optRDExpectedOffset + sizeof(uint16_t) /* RD len */ + sizeOfECSOption + /* option code */ 2 + /* option length */ 2); BOOST_CHECK_EQUAL(optContentLen, cookiesOptionStr.size()); } @@ -1968,23 +2028,24 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) PacketBuffer query; PacketBuffer queryWithEDNS; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; - GenericDNSPacketWriter pwEDNS(queryWithEDNS, name, QType::A, QClass::IN, 0); - pwEDNS.getHeader()->rd = 1; - pwEDNS.addOpt(1232, 0, 0); - pwEDNS.commit(); + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; + GenericDNSPacketWriter packetWriterEDNS(queryWithEDNS, name, QType::A, QClass::IN, 0); + packetWriterEDNS.getHeader()->rd = 1; + packetWriterEDNS.addOpt(1232, 0, 0); + packetWriterEDNS.commit(); /* test NXD */ { /* no incoming EDNS */ auto packet = query; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dnsQuestion, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); BOOST_CHECK(packet.size() > query.size()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); BOOST_CHECK_EQUAL(mdp.d_qname.toString(), "www.powerdns.com."); @@ -2001,12 +2062,13 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { /* now with incoming EDNS */ auto packet = queryWithEDNS; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dnsQuestion, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); BOOST_CHECK(packet.size() > queryWithEDNS.size()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); BOOST_CHECK_EQUAL(mdp.d_qname.toString(), "www.powerdns.com."); @@ -2027,12 +2089,13 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { /* no incoming EDNS */ auto packet = query; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dnsQuestion, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); BOOST_CHECK(packet.size() > query.size()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); BOOST_CHECK_EQUAL(mdp.d_qname.toString(), "www.powerdns.com."); @@ -2049,12 +2112,13 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { /* now with incoming EDNS */ auto packet = queryWithEDNS; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dnsQuestion, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, false)); BOOST_CHECK(packet.size() > queryWithEDNS.size()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); BOOST_CHECK_EQUAL(mdp.d_qname.toString(), "www.powerdns.com."); @@ -2077,13 +2141,14 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { /* no incoming EDNS */ auto packet = query; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, + BOOST_CHECK(setNegativeAndAdditionalSOA(dnsQuestion, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, true)); BOOST_CHECK(packet.size() > query.size()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); BOOST_CHECK_EQUAL(mdp.d_qname.toString(), "www.powerdns.com."); @@ -2100,12 +2165,13 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { /* now with incoming EDNS */ auto packet = queryWithEDNS; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, true)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dnsQuestion, true, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, true)); BOOST_CHECK(packet.size() > queryWithEDNS.size()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); BOOST_CHECK_EQUAL(mdp.d_qname.toString(), "www.powerdns.com."); @@ -2126,12 +2192,13 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { /* no incoming EDNS */ auto packet = query; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, true)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dnsQuestion, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, true)); BOOST_CHECK(packet.size() > query.size()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); BOOST_CHECK_EQUAL(mdp.d_qname.toString(), "www.powerdns.com."); @@ -2148,12 +2215,13 @@ BOOST_AUTO_TEST_CASE(test_setNegativeAndAdditionalSOA) { /* now with incoming EDNS */ auto packet = queryWithEDNS; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &ids.qtype, nullptr); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); - BOOST_CHECK(setNegativeAndAdditionalSOA(dq, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, true)); + BOOST_CHECK(setNegativeAndAdditionalSOA(dnsQuestion, false, DNSName("zone."), 42, DNSName("mname."), DNSName("rname."), 1, 2, 3, 4, 5, true)); BOOST_CHECK(packet.size() > queryWithEDNS.size()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) MOADNSParser mdp(true, reinterpret_cast(packet.data()), packet.size()); BOOST_CHECK_EQUAL(mdp.d_qname.toString(), "www.powerdns.com."); @@ -2178,67 +2246,70 @@ BOOST_AUTO_TEST_CASE(getEDNSOptionsWithoutEDNS) ids.protocol = dnsdist::Protocol::DoUDP; const DNSName name("www.powerdns.com."); - const ComboAddress v4("192.0.2.1"); + const ComboAddress v4Addr("192.0.2.1"); { /* no EDNS and no other additional record */ PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; - pw.commit(); + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; + packetWriter.commit(); /* large enough packet */ auto packet = query; unsigned int consumed = 0; - uint16_t qtype; - uint16_t qclass; + uint16_t qtype = 0; + uint16_t qclass = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, &qclass, &consumed); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); - BOOST_CHECK(!parseEDNSOptions(dq)); + BOOST_CHECK(!parseEDNSOptions(dnsQuestion)); } { /* nothing in additional (so no EDNS) but a record in ANSWER */ PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; - pw.startRecord(name, QType::A, 60, QClass::IN, DNSResourceRecord::ANSWER); - pw.xfrIP(v4.sin4.sin_addr.s_addr); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; + packetWriter.startRecord(name, QType::A, 60, QClass::IN, DNSResourceRecord::ANSWER); + packetWriter.xfrIP(v4Addr.sin4.sin_addr.s_addr); + packetWriter.commit(); /* large enough packet */ auto packet = query; unsigned int consumed = 0; - uint16_t qtype; - uint16_t qclass; + uint16_t qtype = 0; + uint16_t qclass = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, &qclass, &consumed); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); - BOOST_CHECK(!parseEDNSOptions(dq)); + BOOST_CHECK(!parseEDNSOptions(dnsQuestion)); } { /* nothing in additional (so no EDNS) but a record in AUTHORITY */ PacketBuffer query; - GenericDNSPacketWriter pw(query, name, QType::A, QClass::IN, 0); - pw.getHeader()->rd = 1; - pw.startRecord(name, QType::A, 60, QClass::IN, DNSResourceRecord::AUTHORITY); - pw.xfrIP(v4.sin4.sin_addr.s_addr); - pw.commit(); + GenericDNSPacketWriter packetWriter(query, name, QType::A, QClass::IN, 0); + packetWriter.getHeader()->rd = 1; + packetWriter.startRecord(name, QType::A, 60, QClass::IN, DNSResourceRecord::AUTHORITY); + packetWriter.xfrIP(v4Addr.sin4.sin_addr.s_addr); + packetWriter.commit(); /* large enough packet */ auto packet = query; unsigned int consumed = 0; - uint16_t qtype; - uint16_t qclass; + uint16_t qtype = 0; + uint16_t qclass = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) DNSName qname(reinterpret_cast(packet.data()), packet.size(), sizeof(dnsheader), false, &qtype, &qclass, &consumed); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); - BOOST_CHECK(!parseEDNSOptions(dq)); + BOOST_CHECK(!parseEDNSOptions(dnsQuestion)); } } @@ -2253,24 +2324,25 @@ BOOST_AUTO_TEST_CASE(test_setEDNSOption) ids.qclass = QClass::IN; ids.queryRealTime.start(); - struct timespec expiredTime; + timespec expiredTime{}; /* the internal QPS limiter does not use the real time */ gettime(&expiredTime); PacketBuffer packet; - GenericDNSPacketWriter pw(packet, ids.qname, ids.qtype, ids.qclass, 0); - pw.addOpt(4096, 0, EDNS_HEADER_FLAG_DO); - pw.commit(); + GenericDNSPacketWriter packetWriter(packet, ids.qname, ids.qtype, ids.qclass, 0); + packetWriter.addOpt(4096, 0, EDNS_HEADER_FLAG_DO); + packetWriter.commit(); - DNSQuestion dq(ids, packet); + DNSQuestion dnsQuestion(ids, packet); std::string result; EDNSCookiesOpt cookiesOpt("deadbeefdeadbeef"); string cookiesOptionStr = cookiesOpt.makeOptString(); - BOOST_REQUIRE(setEDNSOption(dq, EDNSOptionCode::COOKIE, cookiesOptionStr)); + BOOST_REQUIRE(setEDNSOption(dnsQuestion, EDNSOptionCode::COOKIE, cookiesOptionStr)); - const auto& data = dq.getData(); + const auto& data = dnsQuestion.getData(); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) MOADNSParser mdp(true, reinterpret_cast(data.data()), data.size()); BOOST_CHECK_EQUAL(mdp.d_qname.toString(), ids.qname.toString()); @@ -2281,17 +2353,17 @@ BOOST_AUTO_TEST_CASE(test_setEDNSOption) BOOST_CHECK_EQUAL(mdp.d_answers.at(0).first.d_type, static_cast(QType::OPT)); BOOST_CHECK_EQUAL(mdp.d_answers.at(0).first.d_name, g_rootdnsname); - EDNS0Record edns0; - BOOST_REQUIRE(getEDNS0Record(dq.getData(), edns0)); + EDNS0Record edns0{}; + BOOST_REQUIRE(getEDNS0Record(dnsQuestion.getData(), edns0)); BOOST_CHECK_EQUAL(edns0.version, 0U); BOOST_CHECK_EQUAL(edns0.extRCode, 0U); BOOST_CHECK_EQUAL(edns0.extFlags, EDNS_HEADER_FLAG_DO); - BOOST_REQUIRE(parseEDNSOptions(dq)); - BOOST_REQUIRE(dq.ednsOptions != nullptr); - BOOST_CHECK_EQUAL(dq.ednsOptions->size(), 1U); - const auto& ecsOption = dq.ednsOptions->find(EDNSOptionCode::COOKIE); - BOOST_REQUIRE(ecsOption != dq.ednsOptions->cend()); + BOOST_REQUIRE(parseEDNSOptions(dnsQuestion)); + BOOST_REQUIRE(dnsQuestion.ednsOptions != nullptr); + BOOST_CHECK_EQUAL(dnsQuestion.ednsOptions->size(), 1U); + const auto& ecsOption = dnsQuestion.ednsOptions->find(EDNSOptionCode::COOKIE); + BOOST_REQUIRE(ecsOption != dnsQuestion.ednsOptions->cend()); BOOST_REQUIRE_EQUAL(ecsOption->second.values.size(), 1U); BOOST_CHECK_EQUAL(cookiesOptionStr, std::string(ecsOption->second.values.at(0).content, ecsOption->second.values.at(0).size)); From 8889f847c9b406e4e082db3ef3c738010bb072fc Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 14:14:48 +0100 Subject: [PATCH 09/25] dnsdist: Delint dnsdist-dynbpf.cc --- pdns/dnsdistdist/dnsdist-dynbpf.cc | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-dynbpf.cc b/pdns/dnsdistdist/dnsdist-dynbpf.cc index 54902b367e6d..ab09f6dc0f46 100644 --- a/pdns/dnsdistdist/dnsdist-dynbpf.cc +++ b/pdns/dnsdistdist/dnsdist-dynbpf.cc @@ -31,10 +31,10 @@ bool DynBPFFilter::block(const ComboAddress& addr, const struct timespec& until) return inserted; } - const container_t::iterator it = data->d_entries.find(addr); - if (it != data->d_entries.end()) { - if (it->d_until < until) { - data->d_entries.replace(it, BlockEntry(addr, until)); + auto entriesIt = data->d_entries.find(addr); + if (entriesIt != data->d_entries.end()) { + if (entriesIt->d_until < until) { + data->d_entries.replace(entriesIt, BlockEntry(addr, until)); } } else { @@ -49,13 +49,13 @@ void DynBPFFilter::purgeExpired(const struct timespec& now) { auto data = d_data.lock(); - typedef boost::multi_index::nth_index::type ordered_until; - ordered_until& ou = boost::multi_index::get<1>(data->d_entries); + using ordered_until = boost::multi_index::nth_index::type; + ordered_until& orderedUntilIndex = boost::multi_index::get<1>(data->d_entries); - for (ordered_until::iterator it = ou.begin(); it != ou.end();) { - if (it->d_until < now) { - ComboAddress addr = it->d_addr; - it = ou.erase(it); + for (auto orderedUntilIt = orderedUntilIndex.begin(); orderedUntilIt != orderedUntilIndex.end();) { + if (orderedUntilIt->d_until < now) { + ComboAddress addr = orderedUntilIt->d_addr; + orderedUntilIt = orderedUntilIndex.erase(orderedUntilIt); data->d_bpf->unblock(addr); } else { @@ -76,9 +76,9 @@ std::vector> DynBPFFilter::g const auto& stats = data->d_bpf->getAddrStats(); result.reserve(stats.size()); for (const auto& stat : stats) { - const container_t::iterator it = data->d_entries.find(stat.first); - if (it != data->d_entries.end()) { - result.emplace_back(stat.first, stat.second, it->d_until); + const auto entriesIt = data->d_entries.find(stat.first); + if (entriesIt != data->d_entries.end()) { + result.emplace_back(stat.first, stat.second, entriesIt->d_until); } } return result; From 8377f8822a99831a08045a24b3dd7738627e6422 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 14:38:26 +0100 Subject: [PATCH 10/25] dnsdist: Delint dnsdist-lua-actions.cc --- pdns/dnsdistdist/dnsdist-lua-actions.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pdns/dnsdistdist/dnsdist-lua-actions.cc b/pdns/dnsdistdist/dnsdist-lua-actions.cc index e6430077c90a..ea0c57edd9e3 100644 --- a/pdns/dnsdistdist/dnsdist-lua-actions.cc +++ b/pdns/dnsdistdist/dnsdist-lua-actions.cc @@ -1964,7 +1964,7 @@ class SNMPTrapResponseAction : public DNSResponseAction } DNSResponseAction::Action operator()(DNSResponse* response, std::string* ruleresult) const override { - if (g_snmpAgent && g_snmpTrapsEnabled) { + if (g_snmpAgent != nullptr && g_snmpTrapsEnabled) { g_snmpAgent->sendDNSTrap(*response, d_reason); } From 40d01eff43973e68935c42bab13844133d50f8e3 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 15:40:48 +0100 Subject: [PATCH 11/25] dnsdist: Delint dnsdist-lua-bindings-dnsquestion.cc --- .../dnsdist-lua-bindings-dnsquestion.cc | 385 +++++++++--------- 1 file changed, 194 insertions(+), 191 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc b/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc index deb8c3f7aca5..7eea39f0849e 100644 --- a/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc +++ b/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc @@ -34,89 +34,90 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) /* DNSQuestion */ /* PowerDNS DNSQuestion compat */ luaCtx.registerMember( - "localaddr", [](const DNSQuestion& dq) -> const ComboAddress { return dq.ids.origDest; }, [](DNSQuestion& dq, const ComboAddress newLocal) { (void)newLocal; }); + "localaddr", [](const DNSQuestion& dnsQuestion) -> ComboAddress { return dnsQuestion.ids.origDest; }, [](DNSQuestion& dnsQuestion, const ComboAddress newLocal) { (void)newLocal; }); luaCtx.registerMember( - "qname", [](const DNSQuestion& dq) -> const DNSName { return dq.ids.qname; }, [](DNSQuestion& dq, const DNSName& newName) { (void)newName; }); + "qname", [](const DNSQuestion& dnsQuestion) -> DNSName { return dnsQuestion.ids.qname; }, [](DNSQuestion& dnsQuestion, const DNSName& newName) { (void)newName; }); luaCtx.registerMember( - "qtype", [](const DNSQuestion& dq) -> uint16_t { return dq.ids.qtype; }, [](DNSQuestion& dq, uint16_t newType) { (void)newType; }); + "qtype", [](const DNSQuestion& dnsQuestion) -> uint16_t { return dnsQuestion.ids.qtype; }, [](DNSQuestion& dnsQuestion, uint16_t newType) { (void)newType; }); luaCtx.registerMember( - "qclass", [](const DNSQuestion& dq) -> uint16_t { return dq.ids.qclass; }, [](DNSQuestion& dq, uint16_t newClass) { (void)newClass; }); + "qclass", [](const DNSQuestion& dnsQuestion) -> uint16_t { return dnsQuestion.ids.qclass; }, [](DNSQuestion& dnsQuestion, uint16_t newClass) { (void)newClass; }); luaCtx.registerMember( - "rcode", [](const DNSQuestion& dq) -> int { return static_cast(dq.getHeader()->rcode); }, [](DNSQuestion& dq, int newRCode) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [newRCode](dnsheader& header) { + "rcode", [](const DNSQuestion& dnsQuestion) -> int { return static_cast(dnsQuestion.getHeader()->rcode); }, [](DNSQuestion& dnsQuestion, int newRCode) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [newRCode](dnsheader& header) { header.rcode = static_cast(newRCode); return true; }); }); luaCtx.registerMember( - "remoteaddr", [](const DNSQuestion& dq) -> const ComboAddress { return dq.ids.origRemote; }, [](DNSQuestion& dq, const ComboAddress newRemote) { (void)newRemote; }); + "remoteaddr", [](const DNSQuestion& dnsQuestion) -> ComboAddress { return dnsQuestion.ids.origRemote; }, [](DNSQuestion& dnsQuestion, const ComboAddress newRemote) { (void)newRemote; }); /* DNSDist DNSQuestion */ luaCtx.registerMember( - "dh", [](const DNSQuestion& dq) -> dnsheader* { return dq.getMutableHeader(); }, [](DNSQuestion& dq, const dnsheader* dh) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [&dh](dnsheader& header) { - header = *dh; + "dh", [](const DNSQuestion& dnsQuestion) -> dnsheader* { return dnsQuestion.getMutableHeader(); }, [](DNSQuestion& dnsQuestion, const dnsheader* dnsHeader) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [&dnsHeader](dnsheader& header) { + header = *dnsHeader; return true; }); }); luaCtx.registerMember( - "len", [](const DNSQuestion& dq) -> uint16_t { return dq.getData().size(); }, [](DNSQuestion& dq, uint16_t newlen) { dq.getMutableData().resize(newlen); }); + "len", [](const DNSQuestion& dnsQuestion) -> uint16_t { return dnsQuestion.getData().size(); }, [](DNSQuestion& dnsQuestion, uint16_t newlen) { dnsQuestion.getMutableData().resize(newlen); }); luaCtx.registerMember( - "opcode", [](const DNSQuestion& dq) -> uint8_t { return dq.getHeader()->opcode; }, [](DNSQuestion& dq, uint8_t newOpcode) { (void)newOpcode; }); + "opcode", [](const DNSQuestion& dnsQuestion) -> uint8_t { return dnsQuestion.getHeader()->opcode; }, [](DNSQuestion& dnsQuestion, uint8_t newOpcode) { (void)newOpcode; }); luaCtx.registerMember( - "tcp", [](const DNSQuestion& dq) -> bool { return dq.overTCP(); }, [](DNSQuestion& dq, bool newTcp) { (void)newTcp; }); + "tcp", [](const DNSQuestion& dnsQuestion) -> bool { return dnsQuestion.overTCP(); }, [](DNSQuestion& dnsQuestion, bool newTcp) { (void)newTcp; }); luaCtx.registerMember( - "skipCache", [](const DNSQuestion& dq) -> bool { return dq.ids.skipCache; }, [](DNSQuestion& dq, bool newSkipCache) { dq.ids.skipCache = newSkipCache; }); + "skipCache", [](const DNSQuestion& dnsQuestion) -> bool { return dnsQuestion.ids.skipCache; }, [](DNSQuestion& dnsQuestion, bool newSkipCache) { dnsQuestion.ids.skipCache = newSkipCache; }); luaCtx.registerMember( - "pool", [](const DNSQuestion& dq) -> std::string { return dq.ids.poolName; }, [](DNSQuestion& dq, const std::string& newPoolName) { dq.ids.poolName = newPoolName; }); + "pool", [](const DNSQuestion& dnsQuestion) -> std::string { return dnsQuestion.ids.poolName; }, [](DNSQuestion& dnsQuestion, const std::string& newPoolName) { dnsQuestion.ids.poolName = newPoolName; }); luaCtx.registerMember( - "useECS", [](const DNSQuestion& dq) -> bool { return dq.useECS; }, [](DNSQuestion& dq, bool useECS) { dq.useECS = useECS; }); + "useECS", [](const DNSQuestion& dnsQuestion) -> bool { return dnsQuestion.useECS; }, [](DNSQuestion& dnsQuestion, bool useECS) { dnsQuestion.useECS = useECS; }); luaCtx.registerMember( - "ecsOverride", [](const DNSQuestion& dq) -> bool { return dq.ecsOverride; }, [](DNSQuestion& dq, bool ecsOverride) { dq.ecsOverride = ecsOverride; }); + "ecsOverride", [](const DNSQuestion& dnsQuestion) -> bool { return dnsQuestion.ecsOverride; }, [](DNSQuestion& dnsQuestion, bool ecsOverride) { dnsQuestion.ecsOverride = ecsOverride; }); luaCtx.registerMember( - "ecsPrefixLength", [](const DNSQuestion& dq) -> uint16_t { return dq.ecsPrefixLength; }, [](DNSQuestion& dq, uint16_t newPrefixLength) { dq.ecsPrefixLength = newPrefixLength; }); + "ecsPrefixLength", [](const DNSQuestion& dnsQuestion) -> uint16_t { return dnsQuestion.ecsPrefixLength; }, [](DNSQuestion& dnsQuestion, uint16_t newPrefixLength) { dnsQuestion.ecsPrefixLength = newPrefixLength; }); luaCtx.registerMember(DNSQuestion::*)>( "tempFailureTTL", - [](const DNSQuestion& dq) -> boost::optional { - return dq.ids.tempFailureTTL; + [](const DNSQuestion& dnsQuestion) -> boost::optional { + return dnsQuestion.ids.tempFailureTTL; }, - [](DNSQuestion& dq, boost::optional newValue) { - dq.ids.tempFailureTTL = newValue; + [](DNSQuestion& dnsQuestion, boost::optional newValue) { + dnsQuestion.ids.tempFailureTTL = newValue; }); luaCtx.registerMember( - "deviceID", [](const DNSQuestion& dq) -> std::string { - if (dq.ids.d_protoBufData) { - return dq.ids.d_protoBufData->d_deviceID; + "deviceID", [](const DNSQuestion& dnsQuestion) -> std::string { + if (dnsQuestion.ids.d_protoBufData) { + return dnsQuestion.ids.d_protoBufData->d_deviceID; } - return std::string(); }, [](DNSQuestion& dq, const std::string& newValue) { - if (!dq.ids.d_protoBufData) { - dq.ids.d_protoBufData = std::make_unique(); + return {}; }, [](DNSQuestion& dnsQuestion, const std::string& newValue) { + if (!dnsQuestion.ids.d_protoBufData) { + dnsQuestion.ids.d_protoBufData = std::make_unique(); } - dq.ids.d_protoBufData->d_deviceID = newValue; }); + dnsQuestion.ids.d_protoBufData->d_deviceID = newValue; }); luaCtx.registerMember( - "deviceName", [](const DNSQuestion& dq) -> std::string { - if (dq.ids.d_protoBufData) { - return dq.ids.d_protoBufData->d_deviceName; + "deviceName", [](const DNSQuestion& dnsQuestion) -> std::string { + if (dnsQuestion.ids.d_protoBufData) { + return dnsQuestion.ids.d_protoBufData->d_deviceName; } - return std::string(); }, [](DNSQuestion& dq, const std::string& newValue) { - if (!dq.ids.d_protoBufData) { - dq.ids.d_protoBufData = std::make_unique(); + return {}; }, [](DNSQuestion& dnsQuestion, const std::string& newValue) { + if (!dnsQuestion.ids.d_protoBufData) { + dnsQuestion.ids.d_protoBufData = std::make_unique(); } - dq.ids.d_protoBufData->d_deviceName = newValue; }); + dnsQuestion.ids.d_protoBufData->d_deviceName = newValue; }); luaCtx.registerMember( - "requestorID", [](const DNSQuestion& dq) -> std::string { - if (dq.ids.d_protoBufData) { - return dq.ids.d_protoBufData->d_requestorID; + "requestorID", [](const DNSQuestion& dnsQuestion) -> std::string { + if (dnsQuestion.ids.d_protoBufData) { + return dnsQuestion.ids.d_protoBufData->d_requestorID; } - return std::string(); }, [](DNSQuestion& dq, const std::string& newValue) { - if (!dq.ids.d_protoBufData) { - dq.ids.d_protoBufData = std::make_unique(); + return {}; }, [](DNSQuestion& dnsQuestion, const std::string& newValue) { + if (!dnsQuestion.ids.d_protoBufData) { + dnsQuestion.ids.d_protoBufData = std::make_unique(); } - dq.ids.d_protoBufData->d_requestorID = newValue; }); - luaCtx.registerFunction("getDO", [](const DNSQuestion& dq) { - return getEDNSZ(dq) & EDNS_HEADER_FLAG_DO; + dnsQuestion.ids.d_protoBufData->d_requestorID = newValue; }); + luaCtx.registerFunction("getDO", [](const DNSQuestion& dnsQuestion) { + return getEDNSZ(dnsQuestion) & EDNS_HEADER_FLAG_DO; }); - luaCtx.registerFunction("getContent", [](const DNSQuestion& dq) { - return std::string(reinterpret_cast(dq.getData().data()), dq.getData().size()); + luaCtx.registerFunction("getContent", [](const DNSQuestion& dnsQuestion) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + return std::string(reinterpret_cast(dnsQuestion.getData().data()), dnsQuestion.getData().size()); }); - luaCtx.registerFunction("setContent", [](DNSQuestion& dq, const std::string& raw) { - uint16_t oldID = dq.getHeader()->id; - auto& buffer = dq.getMutableData(); + luaCtx.registerFunction("setContent", [](DNSQuestion& dnsQuestion, const std::string& raw) { + uint16_t oldID = dnsQuestion.getHeader()->id; + auto& buffer = dnsQuestion.getMutableData(); buffer.clear(); buffer.insert(buffer.begin(), raw.begin(), raw.end()); @@ -125,113 +126,113 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) return true; }); }); - luaCtx.registerFunction (DNSQuestion::*)() const>("getEDNSOptions", [](const DNSQuestion& dq) { - if (dq.ednsOptions == nullptr) { - parseEDNSOptions(dq); - if (dq.ednsOptions == nullptr) { + luaCtx.registerFunction (DNSQuestion::*)() const>("getEDNSOptions", [](const DNSQuestion& dnsQuestion) { + if (dnsQuestion.ednsOptions == nullptr) { + parseEDNSOptions(dnsQuestion); + if (dnsQuestion.ednsOptions == nullptr) { throw std::runtime_error("parseEDNSOptions should have populated the EDNS options"); } } - return *dq.ednsOptions; + return *dnsQuestion.ednsOptions; }); - luaCtx.registerFunction("getTrailingData", [](const DNSQuestion& dq) { - return dq.getTrailingData(); + luaCtx.registerFunction("getTrailingData", [](const DNSQuestion& dnsQuestion) { + return dnsQuestion.getTrailingData(); }); - luaCtx.registerFunction("setTrailingData", [](DNSQuestion& dq, const std::string& tail) { - return dq.setTrailingData(tail); + luaCtx.registerFunction("setTrailingData", [](DNSQuestion& dnsQuestion, const std::string& tail) { + return dnsQuestion.setTrailingData(tail); }); - luaCtx.registerFunction("getServerNameIndication", [](const DNSQuestion& dq) { - return dq.sni; + luaCtx.registerFunction("getServerNameIndication", [](const DNSQuestion& dnsQuestion) { + return dnsQuestion.sni; }); - luaCtx.registerFunction("getProtocol", [](const DNSQuestion& dq) { - return dq.getProtocol().toPrettyString(); + luaCtx.registerFunction("getProtocol", [](const DNSQuestion& dnsQuestion) { + return dnsQuestion.getProtocol().toPrettyString(); }); - luaCtx.registerFunction("getQueryTime", [](const DNSQuestion& dq) { - return dq.ids.queryRealTime.getStartTime(); + luaCtx.registerFunction("getQueryTime", [](const DNSQuestion& dnsQuestion) { + return dnsQuestion.ids.queryRealTime.getStartTime(); }); - luaCtx.registerFunction("sendTrap", [](const DNSQuestion& dq, boost::optional reason) { + luaCtx.registerFunction("sendTrap", [](const DNSQuestion& dnsQuestion, boost::optional reason) { #ifdef HAVE_NET_SNMP - if (g_snmpAgent && g_snmpTrapsEnabled) { - g_snmpAgent->sendDNSTrap(dq, reason ? *reason : ""); + if (g_snmpAgent != nullptr && g_snmpTrapsEnabled) { + g_snmpAgent->sendDNSTrap(dnsQuestion, reason ? *reason : ""); } #endif /* HAVE_NET_SNMP */ }); - luaCtx.registerFunction("setTag", [](DNSQuestion& dq, const std::string& strLabel, const std::string& strValue) { - dq.setTag(strLabel, strValue); + luaCtx.registerFunction("setTag", [](DNSQuestion& dnsQuestion, const std::string& strLabel, const std::string& strValue) { + dnsQuestion.setTag(strLabel, strValue); }); - luaCtx.registerFunction)>("setTagArray", [](DNSQuestion& dq, const LuaAssociativeTable& tags) { + luaCtx.registerFunction)>("setTagArray", [](DNSQuestion& dnsQuestion, const LuaAssociativeTable& tags) { for (const auto& tag : tags) { - dq.setTag(tag.first, tag.second); + dnsQuestion.setTag(tag.first, tag.second); } }); - luaCtx.registerFunction("getTag", [](const DNSQuestion& dq, const std::string& strLabel) { - if (!dq.ids.qTag) { + luaCtx.registerFunction("getTag", [](const DNSQuestion& dnsQuestion, const std::string& strLabel) { + if (!dnsQuestion.ids.qTag) { return string(); } std::string strValue; - const auto it = dq.ids.qTag->find(strLabel); - if (it == dq.ids.qTag->cend()) { + const auto tagIt = dnsQuestion.ids.qTag->find(strLabel); + if (tagIt == dnsQuestion.ids.qTag->cend()) { return string(); } - return it->second; + return tagIt->second; }); - luaCtx.registerFunction("getTagArray", [](const DNSQuestion& dq) { - if (!dq.ids.qTag) { + luaCtx.registerFunction("getTagArray", [](const DNSQuestion& dnsQuestion) { + if (!dnsQuestion.ids.qTag) { QTag empty; return empty; } - return *dq.ids.qTag; + return *dnsQuestion.ids.qTag; }); - luaCtx.registerFunction)>("setProxyProtocolValues", [](DNSQuestion& dq, const LuaArray& values) { - if (!dq.proxyProtocolValues) { - dq.proxyProtocolValues = make_unique>(); + luaCtx.registerFunction)>("setProxyProtocolValues", [](DNSQuestion& dnsQuestion, const LuaArray& values) { + if (!dnsQuestion.proxyProtocolValues) { + dnsQuestion.proxyProtocolValues = make_unique>(); } - dq.proxyProtocolValues->clear(); - dq.proxyProtocolValues->reserve(values.size()); + dnsQuestion.proxyProtocolValues->clear(); + dnsQuestion.proxyProtocolValues->reserve(values.size()); for (const auto& value : values) { checkParameterBound("setProxyProtocolValues", value.first, std::numeric_limits::max()); - dq.proxyProtocolValues->push_back({value.second, static_cast(value.first)}); + dnsQuestion.proxyProtocolValues->push_back({value.second, static_cast(value.first)}); } }); - luaCtx.registerFunction("addProxyProtocolValue", [](DNSQuestion& dq, uint64_t type, std::string value) { + luaCtx.registerFunction("addProxyProtocolValue", [](DNSQuestion& dnsQuestion, uint64_t type, std::string value) { checkParameterBound("addProxyProtocolValue", type, std::numeric_limits::max()); - if (!dq.proxyProtocolValues) { - dq.proxyProtocolValues = make_unique>(); + if (!dnsQuestion.proxyProtocolValues) { + dnsQuestion.proxyProtocolValues = make_unique>(); } - dq.proxyProtocolValues->push_back({std::move(value), static_cast(type)}); + dnsQuestion.proxyProtocolValues->push_back({std::move(value), static_cast(type)}); }); - luaCtx.registerFunction (DNSQuestion::*)()>("getProxyProtocolValues", [](const DNSQuestion& dq) { + luaCtx.registerFunction (DNSQuestion::*)()>("getProxyProtocolValues", [](const DNSQuestion& dnsQuestion) { LuaArray result; - if (!dq.proxyProtocolValues) { + if (!dnsQuestion.proxyProtocolValues) { return result; } - result.resize(dq.proxyProtocolValues->size()); - for (const auto& value : *dq.proxyProtocolValues) { - result.push_back({value.type, value.content}); + result.resize(dnsQuestion.proxyProtocolValues->size()); + for (const auto& value : *dnsQuestion.proxyProtocolValues) { + result.emplace_back(value.type, value.content); } return result; }); - luaCtx.registerFunction("changeName", [](DNSQuestion& dq, const DNSName& newName) -> bool { - if (!dnsdist::changeNameInDNSPacket(dq.getMutableData(), dq.ids.qname, newName)) { + luaCtx.registerFunction("changeName", [](DNSQuestion& dnsQuestion, const DNSName& newName) -> bool { + if (!dnsdist::changeNameInDNSPacket(dnsQuestion.getMutableData(), dnsQuestion.ids.qname, newName)) { return false; } - dq.ids.qname = newName; + dnsQuestion.ids.qname = newName; return true; }); @@ -262,8 +263,8 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) } }); - luaCtx.registerFunction("setEDNSOption", [](DNSQuestion& dq, uint16_t code, const std::string& data) { - setEDNSOption(dq, code, data); + luaCtx.registerFunction("setEDNSOption", [](DNSQuestion& dnsQuestion, uint16_t code, const std::string& data) { + setEDNSOption(dnsQuestion, code, data); }); luaCtx.registerFunction& extraText)>("setExtendedDNSError", [](DNSQuestion& dnsQuestion, uint16_t infoCode, const boost::optional& extraText) { @@ -275,13 +276,13 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) dnsQuestion.ids.d_extendedError = std::make_unique(ede); }); - luaCtx.registerFunction("suspend", [](DNSQuestion& dq, uint16_t asyncID, uint16_t queryID, uint32_t timeoutMs) { - dq.asynchronous = true; - return dnsdist::suspendQuery(dq, asyncID, queryID, timeoutMs); + luaCtx.registerFunction("suspend", [](DNSQuestion& dnsQuestion, uint16_t asyncID, uint16_t queryID, uint32_t timeoutMs) { + dnsQuestion.asynchronous = true; + return dnsdist::suspendQuery(dnsQuestion, asyncID, queryID, timeoutMs); }); - luaCtx.registerFunction("setRestartable", [](DNSQuestion& dq) { - dq.ids.d_packet = std::make_unique(dq.getData()); + luaCtx.registerFunction("setRestartable", [](DNSQuestion& dnsQuestion) { + dnsQuestion.ids.d_packet = std::make_unique(dnsQuestion.getData()); return true; }); @@ -293,12 +294,12 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) { } - DNSQuestion getDQ() const + [[nodiscard]] DNSQuestion getDQ() const { return object->getDQ(); } - DNSResponse getDR() const + [[nodiscard]] DNSResponse getDR() const { return object->getDR(); } @@ -315,7 +316,7 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) return false; } - struct timeval now; + timeval now{}; gettimeofday(&now, nullptr); sender->notifyIOError(now, TCPResponse(std::move(object->query))); return true; @@ -358,52 +359,54 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) if (!query) { throw std::runtime_error("Unable to find asynchronous object"); } - return AsynchronousObject(std::move(query)); + return {std::move(query)}; }); /* LuaWrapper doesn't support inheritance */ luaCtx.registerMember( - "localaddr", [](const DNSResponse& dq) -> const ComboAddress { return dq.ids.origDest; }, [](DNSResponse& dq, const ComboAddress newLocal) { (void)newLocal; }); + "localaddr", [](const DNSResponse& dnsQuestion) -> ComboAddress { return dnsQuestion.ids.origDest; }, [](DNSResponse& dnsQuestion, const ComboAddress newLocal) { (void)newLocal; }); luaCtx.registerMember( - "qname", [](const DNSResponse& dq) -> const DNSName { return dq.ids.qname; }, [](DNSResponse& dq, const DNSName& newName) { (void)newName; }); + "qname", [](const DNSResponse& dnsQuestion) -> DNSName { return dnsQuestion.ids.qname; }, [](DNSResponse& dnsQuestion, const DNSName& newName) { (void)newName; }); luaCtx.registerMember( - "qtype", [](const DNSResponse& dq) -> uint16_t { return dq.ids.qtype; }, [](DNSResponse& dq, uint16_t newType) { (void)newType; }); + "qtype", [](const DNSResponse& dnsQuestion) -> uint16_t { return dnsQuestion.ids.qtype; }, [](DNSResponse& dnsQuestion, uint16_t newType) { (void)newType; }); luaCtx.registerMember( - "qclass", [](const DNSResponse& dq) -> uint16_t { return dq.ids.qclass; }, [](DNSResponse& dq, uint16_t newClass) { (void)newClass; }); + "qclass", [](const DNSResponse& dnsQuestion) -> uint16_t { return dnsQuestion.ids.qclass; }, [](DNSResponse& dnsQuestion, uint16_t newClass) { (void)newClass; }); luaCtx.registerMember( - "rcode", [](const DNSResponse& dq) -> int { return static_cast(dq.getHeader()->rcode); }, [](DNSResponse& dq, int newRCode) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [newRCode](dnsheader& header) { + "rcode", [](const DNSResponse& dnsQuestion) -> int { return static_cast(dnsQuestion.getHeader()->rcode); }, [](DNSResponse& dnsQuestion, int newRCode) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [newRCode](dnsheader& header) { header.rcode = static_cast(newRCode); return true; }); }); - luaCtx.registerMember( - "remoteaddr", [](const DNSResponse& dq) -> const ComboAddress { return dq.ids.origRemote; }, [](DNSResponse& dq, const ComboAddress newRemote) { (void)newRemote; }); + luaCtx.registerMember( + "remoteaddr", [](const DNSResponse& dnsQuestion) -> ComboAddress { return dnsQuestion.ids.origRemote; }, [](DNSResponse& dnsQuestion, const ComboAddress newRemote) { (void)newRemote; }); luaCtx.registerMember( - "dh", [](const DNSResponse& dr) -> dnsheader* { return dr.getMutableHeader(); }, [](DNSResponse& dr, const dnsheader* dh) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dr.getMutableData(), [&dh](dnsheader& header) { - header = *dh; + "dh", [](const DNSResponse& dnsResponse) -> dnsheader* { return dnsResponse.getMutableHeader(); }, [](DNSResponse& dnsResponse, const dnsheader* dnsHeader) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsResponse.getMutableData(), [&dnsHeader](dnsheader& header) { + header = *dnsHeader; return true; }); }); luaCtx.registerMember( - "len", [](const DNSResponse& dq) -> uint16_t { return dq.getData().size(); }, [](DNSResponse& dq, uint16_t newlen) { dq.getMutableData().resize(newlen); }); + "len", [](const DNSResponse& dnsQuestion) -> uint16_t { return dnsQuestion.getData().size(); }, [](DNSResponse& dnsQuestion, uint16_t newlen) { dnsQuestion.getMutableData().resize(newlen); }); luaCtx.registerMember( - "opcode", [](const DNSResponse& dq) -> uint8_t { return dq.getHeader()->opcode; }, [](DNSResponse& dq, uint8_t newOpcode) { (void)newOpcode; }); + "opcode", [](const DNSResponse& dnsQuestion) -> uint8_t { return dnsQuestion.getHeader()->opcode; }, [](DNSResponse& dnsQuestion, uint8_t newOpcode) { (void)newOpcode; }); luaCtx.registerMember( - "tcp", [](const DNSResponse& dq) -> bool { return dq.overTCP(); }, [](DNSResponse& dq, bool newTcp) { (void)newTcp; }); + "tcp", [](const DNSResponse& dnsQuestion) -> bool { return dnsQuestion.overTCP(); }, [](DNSResponse& dnsQuestion, bool newTcp) { (void)newTcp; }); luaCtx.registerMember( - "skipCache", [](const DNSResponse& dq) -> bool { return dq.ids.skipCache; }, [](DNSResponse& dq, bool newSkipCache) { dq.ids.skipCache = newSkipCache; }); + "skipCache", [](const DNSResponse& dnsQuestion) -> bool { return dnsQuestion.ids.skipCache; }, [](DNSResponse& dnsQuestion, bool newSkipCache) { dnsQuestion.ids.skipCache = newSkipCache; }); luaCtx.registerMember( - "pool", [](const DNSResponse& dq) -> std::string { return dq.ids.poolName; }, [](DNSResponse& dq, const std::string& newPoolName) { dq.ids.poolName = newPoolName; }); - luaCtx.registerFunction editFunc)>("editTTLs", [](DNSResponse& dr, std::function editFunc) { - editDNSPacketTTL(reinterpret_cast(dr.getMutableData().data()), dr.getData().size(), editFunc); + "pool", [](const DNSResponse& dnsQuestion) -> std::string { return dnsQuestion.ids.poolName; }, [](DNSResponse& dnsQuestion, const std::string& newPoolName) { dnsQuestion.ids.poolName = newPoolName; }); + luaCtx.registerFunction editFunc)>("editTTLs", [](DNSResponse& dnsResponse, const std::function& editFunc) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + editDNSPacketTTL(reinterpret_cast(dnsResponse.getMutableData().data()), dnsResponse.getData().size(), editFunc); }); - luaCtx.registerFunction("getDO", [](const DNSResponse& dq) { - return getEDNSZ(dq) & EDNS_HEADER_FLAG_DO; + luaCtx.registerFunction("getDO", [](const DNSResponse& dnsQuestion) { + return getEDNSZ(dnsQuestion) & EDNS_HEADER_FLAG_DO; }); - luaCtx.registerFunction("getContent", [](const DNSResponse& dq) { - return std::string(reinterpret_cast(dq.getData().data()), dq.getData().size()); + luaCtx.registerFunction("getContent", [](const DNSResponse& dnsQuestion) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + return std::string(reinterpret_cast(dnsQuestion.getData().data()), dnsQuestion.getData().size()); }); - luaCtx.registerFunction("setContent", [](DNSResponse& dr, const std::string& raw) { - uint16_t oldID = dr.getHeader()->id; - auto& buffer = dr.getMutableData(); + luaCtx.registerFunction("setContent", [](DNSResponse& dnsResponse, const std::string& raw) { + uint16_t oldID = dnsResponse.getHeader()->id; + auto& buffer = dnsResponse.getMutableData(); buffer.clear(); buffer.insert(buffer.begin(), raw.begin(), raw.end()); dnsdist::PacketMangling::editDNSHeaderFromPacket(buffer, [oldID](dnsheader& header) { @@ -412,116 +415,116 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) }); }); - luaCtx.registerFunction (DNSResponse::*)() const>("getEDNSOptions", [](const DNSResponse& dq) { - if (dq.ednsOptions == nullptr) { - parseEDNSOptions(dq); - if (dq.ednsOptions == nullptr) { + luaCtx.registerFunction (DNSResponse::*)() const>("getEDNSOptions", [](const DNSResponse& dnsQuestion) { + if (dnsQuestion.ednsOptions == nullptr) { + parseEDNSOptions(dnsQuestion); + if (dnsQuestion.ednsOptions == nullptr) { throw std::runtime_error("parseEDNSOptions should have populated the EDNS options"); } } - return *dq.ednsOptions; + return *dnsQuestion.ednsOptions; }); - luaCtx.registerFunction("getTrailingData", [](const DNSResponse& dq) { - return dq.getTrailingData(); + luaCtx.registerFunction("getTrailingData", [](const DNSResponse& dnsQuestion) { + return dnsQuestion.getTrailingData(); }); - luaCtx.registerFunction("setTrailingData", [](DNSResponse& dq, const std::string& tail) { - return dq.setTrailingData(tail); + luaCtx.registerFunction("setTrailingData", [](DNSResponse& dnsQuestion, const std::string& tail) { + return dnsQuestion.setTrailingData(tail); }); - luaCtx.registerFunction("setTag", [](DNSResponse& dr, const std::string& strLabel, const std::string& strValue) { - dr.setTag(strLabel, strValue); + luaCtx.registerFunction("setTag", [](DNSResponse& dnsResponse, const std::string& strLabel, const std::string& strValue) { + dnsResponse.setTag(strLabel, strValue); }); - luaCtx.registerFunction)>("setTagArray", [](DNSResponse& dr, const LuaAssociativeTable& tags) { + luaCtx.registerFunction)>("setTagArray", [](DNSResponse& dnsResponse, const LuaAssociativeTable& tags) { for (const auto& tag : tags) { - dr.setTag(tag.first, tag.second); + dnsResponse.setTag(tag.first, tag.second); } }); - luaCtx.registerFunction("getTag", [](const DNSResponse& dr, const std::string& strLabel) { - if (!dr.ids.qTag) { + luaCtx.registerFunction("getTag", [](const DNSResponse& dnsResponse, const std::string& strLabel) { + if (!dnsResponse.ids.qTag) { return string(); } std::string strValue; - const auto it = dr.ids.qTag->find(strLabel); - if (it == dr.ids.qTag->cend()) { + const auto tagIt = dnsResponse.ids.qTag->find(strLabel); + if (tagIt == dnsResponse.ids.qTag->cend()) { return string(); } - return it->second; + return tagIt->second; }); - luaCtx.registerFunction("getTagArray", [](const DNSResponse& dr) { - if (!dr.ids.qTag) { + luaCtx.registerFunction("getTagArray", [](const DNSResponse& dnsResponse) { + if (!dnsResponse.ids.qTag) { QTag empty; return empty; } - return *dr.ids.qTag; + return *dnsResponse.ids.qTag; }); - luaCtx.registerFunction("getProtocol", [](const DNSResponse& dr) { - return dr.getProtocol().toPrettyString(); + luaCtx.registerFunction("getProtocol", [](const DNSResponse& dnsResponse) { + return dnsResponse.getProtocol().toPrettyString(); }); - luaCtx.registerFunction("getQueryTime", [](const DNSResponse& dr) { - return dr.ids.queryRealTime.getStartTime(); + luaCtx.registerFunction("getQueryTime", [](const DNSResponse& dnsResponse) { + return dnsResponse.ids.queryRealTime.getStartTime(); }); - luaCtx.registerFunction("sendTrap", [](const DNSResponse& dr, boost::optional reason) { + luaCtx.registerFunction("sendTrap", [](const DNSResponse& dnsResponse, boost::optional reason) { #ifdef HAVE_NET_SNMP - if (g_snmpAgent && g_snmpTrapsEnabled) { - g_snmpAgent->sendDNSTrap(dr, reason ? *reason : ""); + if (g_snmpAgent != nullptr && g_snmpTrapsEnabled) { + g_snmpAgent->sendDNSTrap(dnsResponse, reason ? *reason : ""); } #endif /* HAVE_NET_SNMP */ }); #ifdef HAVE_DNS_OVER_HTTPS - luaCtx.registerFunction("getHTTPPath", [](const DNSQuestion& dq) { - if (dq.ids.du == nullptr) { + luaCtx.registerFunction("getHTTPPath", [](const DNSQuestion& dnsQuestion) { + if (dnsQuestion.ids.du == nullptr) { return std::string(); } - return dq.ids.du->getHTTPPath(); + return dnsQuestion.ids.du->getHTTPPath(); }); - luaCtx.registerFunction("getHTTPQueryString", [](const DNSQuestion& dq) { - if (dq.ids.du == nullptr) { + luaCtx.registerFunction("getHTTPQueryString", [](const DNSQuestion& dnsQuestion) { + if (dnsQuestion.ids.du == nullptr) { return std::string(); } - return dq.ids.du->getHTTPQueryString(); + return dnsQuestion.ids.du->getHTTPQueryString(); }); - luaCtx.registerFunction("getHTTPHost", [](const DNSQuestion& dq) { - if (dq.ids.du == nullptr) { + luaCtx.registerFunction("getHTTPHost", [](const DNSQuestion& dnsQuestion) { + if (dnsQuestion.ids.du == nullptr) { return std::string(); } - return dq.ids.du->getHTTPHost(); + return dnsQuestion.ids.du->getHTTPHost(); }); - luaCtx.registerFunction("getHTTPScheme", [](const DNSQuestion& dq) { - if (dq.ids.du == nullptr) { + luaCtx.registerFunction("getHTTPScheme", [](const DNSQuestion& dnsQuestion) { + if (dnsQuestion.ids.du == nullptr) { return std::string(); } - return dq.ids.du->getHTTPScheme(); + return dnsQuestion.ids.du->getHTTPScheme(); }); - luaCtx.registerFunction (DNSQuestion::*)(void) const>("getHTTPHeaders", [](const DNSQuestion& dq) { - if (dq.ids.du == nullptr) { + luaCtx.registerFunction (DNSQuestion::*)(void) const>("getHTTPHeaders", [](const DNSQuestion& dnsQuestion) { + if (dnsQuestion.ids.du == nullptr) { return LuaAssociativeTable(); } - return dq.ids.du->getHTTPHeaders(); + return dnsQuestion.ids.du->getHTTPHeaders(); }); - luaCtx.registerFunction contentType)>("setHTTPResponse", [](DNSQuestion& dq, uint64_t statusCode, const std::string& body, const boost::optional contentType) { - if (dq.ids.du == nullptr) { + luaCtx.registerFunction contentType)>("setHTTPResponse", [](DNSQuestion& dnsQuestion, uint64_t statusCode, const std::string& body, const boost::optional& contentType) { + if (dnsQuestion.ids.du == nullptr) { return; } checkParameterBound("DNSQuestion::setHTTPResponse", statusCode, std::numeric_limits::max()); PacketBuffer vect(body.begin(), body.end()); - dq.ids.du->setHTTPResponse(statusCode, std::move(vect), contentType ? *contentType : ""); + dnsQuestion.ids.du->setHTTPResponse(statusCode, std::move(vect), contentType ? *contentType : ""); }); #endif /* HAVE_DNS_OVER_HTTPS */ - luaCtx.registerFunction("setNegativeAndAdditionalSOA", [](DNSQuestion& dq, bool nxd, const std::string& zone, uint64_t ttl, const std::string& mname, const std::string& rname, uint64_t serial, uint64_t refresh, uint64_t retry, uint64_t expire, uint64_t minimum) { + luaCtx.registerFunction("setNegativeAndAdditionalSOA", [](DNSQuestion& dnsQuestion, bool nxd, const std::string& zone, uint64_t ttl, const std::string& mname, const std::string& rname, uint64_t serial, uint64_t refresh, uint64_t retry, uint64_t expire, uint64_t minimum) { checkParameterBound("setNegativeAndAdditionalSOA", ttl, std::numeric_limits::max()); checkParameterBound("setNegativeAndAdditionalSOA", serial, std::numeric_limits::max()); checkParameterBound("setNegativeAndAdditionalSOA", refresh, std::numeric_limits::max()); @@ -529,7 +532,7 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) checkParameterBound("setNegativeAndAdditionalSOA", expire, std::numeric_limits::max()); checkParameterBound("setNegativeAndAdditionalSOA", minimum, std::numeric_limits::max()); - return setNegativeAndAdditionalSOA(dq, nxd, DNSName(zone), ttl, DNSName(mname), DNSName(rname), serial, refresh, retry, expire, minimum, false); + return setNegativeAndAdditionalSOA(dnsQuestion, nxd, DNSName(zone), ttl, DNSName(mname), DNSName(rname), serial, refresh, retry, expire, minimum, false); }); luaCtx.registerFunction& extraText)>("setExtendedDNSError", [](DNSResponse& dnsResponse, uint16_t infoCode, const boost::optional& extraText) { @@ -541,31 +544,31 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) dnsResponse.ids.d_extendedError = std::make_unique(ede); }); - luaCtx.registerFunction("suspend", [](DNSResponse& dr, uint16_t asyncID, uint16_t queryID, uint32_t timeoutMs) { - dr.asynchronous = true; - return dnsdist::suspendResponse(dr, asyncID, queryID, timeoutMs); + luaCtx.registerFunction("suspend", [](DNSResponse& dnsResponse, uint16_t asyncID, uint16_t queryID, uint32_t timeoutMs) { + dnsResponse.asynchronous = true; + return dnsdist::suspendResponse(dnsResponse, asyncID, queryID, timeoutMs); }); - luaCtx.registerFunction("changeName", [](DNSResponse& dr, const DNSName& newName) -> bool { - if (!dnsdist::changeNameInDNSPacket(dr.getMutableData(), dr.ids.qname, newName)) { + luaCtx.registerFunction("changeName", [](DNSResponse& dnsResponse, const DNSName& newName) -> bool { + if (!dnsdist::changeNameInDNSPacket(dnsResponse.getMutableData(), dnsResponse.ids.qname, newName)) { return false; } - dr.ids.qname = newName; + dnsResponse.ids.qname = newName; return true; }); - luaCtx.registerFunction("restart", [](DNSResponse& dr) { - if (!dr.ids.d_packet) { + luaCtx.registerFunction("restart", [](DNSResponse& dnsResponse) { + if (!dnsResponse.ids.d_packet) { return false; } - dr.asynchronous = true; - dr.getMutableData() = *dr.ids.d_packet; - auto query = dnsdist::getInternalQueryFromDQ(dr, false); + dnsResponse.asynchronous = true; + dnsResponse.getMutableData() = *dnsResponse.ids.d_packet; + auto query = dnsdist::getInternalQueryFromDQ(dnsResponse, false); return dnsdist::queueQueryResumptionEvent(std::move(query)); }); - luaCtx.registerFunction (DNSResponse::*)(void) const>("getSelectedBackend", [](const DNSResponse& dr) { - return dr.d_downstream; + luaCtx.registerFunction (DNSResponse::*)(void) const>("getSelectedBackend", [](const DNSResponse& dnsResponse) { + return dnsResponse.d_downstream; }); #endif /* DISABLE_NON_FFI_DQ_BINDINGS */ } From aa74fa6798d3cd258a8b4d162f8f6fe71d663157 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 15:45:30 +0100 Subject: [PATCH 12/25] dnsdist: Delint dnsdist-lua-bindings.cc --- pdns/dnsdistdist/dnsdist-lua-bindings.cc | 293 +++++++++++------------ 1 file changed, 146 insertions(+), 147 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-lua-bindings.cc b/pdns/dnsdistdist/dnsdist-lua-bindings.cc index 8f15f197ed3f..ba63b54692a1 100644 --- a/pdns/dnsdistdist/dnsdist-lua-bindings.cc +++ b/pdns/dnsdistdist/dnsdist-lua-bindings.cc @@ -59,19 +59,19 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } } catch (const std::exception& e) { - return string(e.what()); + return {e.what()}; } catch (const PDNSException& e) { return e.reason; } catch (...) { - return string("Unknown exception"); + return {"Unknown exception"}; } - return string("No exception"); + return {"No exception"}; }); #ifndef DISABLE_POLICIES_BINDINGS /* ServerPolicy */ - luaCtx.writeFunction("newServerPolicy", [](string name, ServerPolicy::policyfunc_t policy) { return std::make_shared(name, policy, true); }); + luaCtx.writeFunction("newServerPolicy", [](const string& name, const ServerPolicy::policyfunc_t& policy) { return std::make_shared(name, policy, true); }); luaCtx.registerMember("name", &ServerPolicy::d_name); luaCtx.registerMember("policy", &ServerPolicy::d_policy); luaCtx.registerMember("ffipolicy", &ServerPolicy::d_ffipolicy); @@ -95,13 +95,13 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) #endif /* DISABLE_POLICIES_BINDINGS */ /* ServerPool */ - luaCtx.registerFunction::*)(std::shared_ptr)>("setCache", [](std::shared_ptr pool, std::shared_ptr cache) { + luaCtx.registerFunction::*)(std::shared_ptr)>("setCache", [](const std::shared_ptr& pool, std::shared_ptr cache) { if (pool) { pool->packetCache = std::move(cache); } }); luaCtx.registerFunction("getCache", &ServerPool::getCache); - luaCtx.registerFunction::*)()>("unsetCache", [](std::shared_ptr pool) { + luaCtx.registerFunction::*)()>("unsetCache", [](const std::shared_ptr& pool) { if (pool) { pool->packetCache = nullptr; } @@ -154,68 +154,69 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) [](const DownstreamState& state) -> int { return state.d_config.order; }, [](DownstreamState& state, int newOrder) { state.d_config.order = newOrder; }); luaCtx.registerMember( - "name", [](const DownstreamState& backend) -> const std::string { return backend.getName(); }, [](DownstreamState& backend, const std::string& newName) { backend.setName(newName); }); + "name", [](const DownstreamState& backend) -> std::string { return backend.getName(); }, [](DownstreamState& backend, const std::string& newName) { backend.setName(newName); }); luaCtx.registerFunction("getID", [](const DownstreamState& state) { return boost::uuids::to_string(*state.d_config.id); }); #endif /* DISABLE_DOWNSTREAM_BINDINGS */ #ifndef DISABLE_DNSHEADER_BINDINGS /* dnsheader */ - luaCtx.registerFunction("setRD", [](dnsheader& dh, bool v) { - dh.rd = v; + luaCtx.registerFunction("setRD", [](dnsheader& dnsHeader, bool value) { + dnsHeader.rd = value; }); - luaCtx.registerFunction("getRD", [](const dnsheader& dh) { - return (bool)dh.rd; + luaCtx.registerFunction("getRD", [](const dnsheader& dnsHeader) { + return (bool)dnsHeader.rd; }); - luaCtx.registerFunction("setRA", [](dnsheader& dh, bool v) { - dh.ra = v; + luaCtx.registerFunction("setRA", [](dnsheader& dnsHeader, bool value) { + dnsHeader.ra = value; }); - luaCtx.registerFunction("getRA", [](const dnsheader& dh) { - return (bool)dh.ra; + luaCtx.registerFunction("getRA", [](const dnsheader& dnsHeader) { + return (bool)dnsHeader.ra; }); - luaCtx.registerFunction("setAD", [](dnsheader& dh, bool v) { - dh.ad = v; + luaCtx.registerFunction("setAD", [](dnsheader& dnsHeader, bool value) { + dnsHeader.ad = value; }); - luaCtx.registerFunction("getAD", [](const dnsheader& dh) { - return (bool)dh.ad; + luaCtx.registerFunction("getAD", [](const dnsheader& dnsHeader) { + return (bool)dnsHeader.ad; }); - luaCtx.registerFunction("setAA", [](dnsheader& dh, bool v) { - dh.aa = v; + luaCtx.registerFunction("setAA", [](dnsheader& dnsHeader, bool value) { + dnsHeader.aa = value; }); - luaCtx.registerFunction("getAA", [](const dnsheader& dh) { - return (bool)dh.aa; + luaCtx.registerFunction("getAA", [](const dnsheader& dnsHeader) { + return (bool)dnsHeader.aa; }); - luaCtx.registerFunction("setCD", [](dnsheader& dh, bool v) { - dh.cd = v; + luaCtx.registerFunction("setCD", [](dnsheader& dnsHeader, bool value) { + dnsHeader.cd = value; }); - luaCtx.registerFunction("getCD", [](const dnsheader& dh) { - return (bool)dh.cd; + luaCtx.registerFunction("getCD", [](const dnsheader& dnsHeader) { + return (bool)dnsHeader.cd; }); - luaCtx.registerFunction("getID", [](const dnsheader& dh) { - return ntohs(dh.id); + luaCtx.registerFunction("getID", [](const dnsheader& dnsHeader) { + return ntohs(dnsHeader.id); }); - luaCtx.registerFunction("getTC", [](const dnsheader& dh) { - return (bool)dh.tc; + luaCtx.registerFunction("getTC", [](const dnsheader& dnsHeader) { + return (bool)dnsHeader.tc; }); - luaCtx.registerFunction("setTC", [](dnsheader& dh, bool v) { - dh.tc = v; - if (v) - dh.ra = dh.rd; // you'll always need this, otherwise TC=1 gets ignored + luaCtx.registerFunction("setTC", [](dnsheader& dnsHeader, bool value) { + dnsHeader.tc = value; + if (value) { + dnsHeader.ra = dnsHeader.rd; // you'll always need this, otherwise TC=1 gets ignored + } }); - luaCtx.registerFunction("setQR", [](dnsheader& dh, bool v) { - dh.qr = v; + luaCtx.registerFunction("setQR", [](dnsheader& dnsHeader, bool value) { + dnsHeader.qr = value; }); #endif /* DISABLE_DNSHEADER_BINDINGS */ @@ -224,7 +225,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) luaCtx.writeFunction("newCA", [](const std::string& name) { return ComboAddress(name); }); luaCtx.writeFunction("newCAFromRaw", [](const std::string& raw, boost::optional port) { if (raw.size() == 4) { - struct sockaddr_in sin4; + sockaddr_in sin4{}; memset(&sin4, 0, sizeof(sin4)); sin4.sin_family = AF_INET; memcpy(&sin4.sin_addr.s_addr, raw.c_str(), raw.size()); @@ -233,8 +234,8 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } return ComboAddress(&sin4); } - else if (raw.size() == 16) { - struct sockaddr_in6 sin6; + if (raw.size() == 16) { + sockaddr_in6 sin6{}; memset(&sin6, 0, sizeof(sin6)); sin6.sin6_family = AF_INET6; memcpy(&sin6.sin6_addr.s6_addr, raw.c_str(), raw.size()); @@ -245,33 +246,33 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } return ComboAddress(); }); - luaCtx.registerFunction("tostring", [](const ComboAddress& ca) { return ca.toString(); }); - luaCtx.registerFunction("tostringWithPort", [](const ComboAddress& ca) { return ca.toStringWithPort(); }); - luaCtx.registerFunction("__tostring", [](const ComboAddress& ca) { return ca.toString(); }); - luaCtx.registerFunction("toString", [](const ComboAddress& ca) { return ca.toString(); }); - luaCtx.registerFunction("toStringWithPort", [](const ComboAddress& ca) { return ca.toStringWithPort(); }); - luaCtx.registerFunction("getPort", [](const ComboAddress& ca) { return ntohs(ca.sin4.sin_port); }); - luaCtx.registerFunction("truncate", [](ComboAddress& ca, unsigned int bits) { ca.truncate(bits); }); - luaCtx.registerFunction("isIPv4", [](const ComboAddress& ca) { return ca.sin4.sin_family == AF_INET; }); - luaCtx.registerFunction("isIPv6", [](const ComboAddress& ca) { return ca.sin4.sin_family == AF_INET6; }); - luaCtx.registerFunction("isMappedIPv4", [](const ComboAddress& ca) { return ca.isMappedIPv4(); }); - luaCtx.registerFunction("mapToIPv4", [](const ComboAddress& ca) { return ca.mapToIPv4(); }); - luaCtx.registerFunction("match", [](nmts_t& s, const ComboAddress& ca) { return s.match(ca); }); + luaCtx.registerFunction("tostring", [](const ComboAddress& addr) { return addr.toString(); }); + luaCtx.registerFunction("tostringWithPort", [](const ComboAddress& addr) { return addr.toStringWithPort(); }); + luaCtx.registerFunction("__tostring", [](const ComboAddress& addr) { return addr.toString(); }); + luaCtx.registerFunction("toString", [](const ComboAddress& addr) { return addr.toString(); }); + luaCtx.registerFunction("toStringWithPort", [](const ComboAddress& addr) { return addr.toStringWithPort(); }); + luaCtx.registerFunction("getPort", [](const ComboAddress& addr) { return ntohs(addr.sin4.sin_port); }); + luaCtx.registerFunction("truncate", [](ComboAddress& addr, unsigned int bits) { addr.truncate(bits); }); + luaCtx.registerFunction("isIPv4", [](const ComboAddress& addr) { return addr.sin4.sin_family == AF_INET; }); + luaCtx.registerFunction("isIPv6", [](const ComboAddress& addr) { return addr.sin4.sin_family == AF_INET6; }); + luaCtx.registerFunction("isMappedIPv4", [](const ComboAddress& addr) { return addr.isMappedIPv4(); }); + luaCtx.registerFunction("mapToIPv4", [](const ComboAddress& addr) { return addr.mapToIPv4(); }); + luaCtx.registerFunction("match", [](nmts_t& set, const ComboAddress& addr) { return set.match(addr); }); #endif /* DISABLE_COMBO_ADDR_BINDINGS */ #ifndef DISABLE_DNSNAME_BINDINGS /* DNSName */ luaCtx.registerFunction("isPartOf", &DNSName::isPartOf); - luaCtx.registerFunction("chopOff", [](DNSName& dn) { return dn.chopOff(); }); + luaCtx.registerFunction("chopOff", [](DNSName& name) { return name.chopOff(); }); luaCtx.registerFunction("countLabels", [](const DNSName& name) { return name.countLabels(); }); luaCtx.registerFunction("hash", [](const DNSName& name) { return name.hash(); }); luaCtx.registerFunction("wirelength", [](const DNSName& name) { return name.wirelength(); }); - luaCtx.registerFunction("tostring", [](const DNSName& dn) { return dn.toString(); }); - luaCtx.registerFunction("toString", [](const DNSName& dn) { return dn.toString(); }); - luaCtx.registerFunction("toStringNoDot", [](const DNSName& dn) { return dn.toStringNoDot(); }); - luaCtx.registerFunction("__tostring", [](const DNSName& dn) { return dn.toString(); }); - luaCtx.registerFunction("toDNSString", [](const DNSName& dn) { return dn.toDNSString(); }); - luaCtx.registerFunction("makeRelative", [](const DNSName& dn, const DNSName& to) { return dn.makeRelative(to); }); + luaCtx.registerFunction("tostring", [](const DNSName& name) { return name.toString(); }); + luaCtx.registerFunction("toString", [](const DNSName& name) { return name.toString(); }); + luaCtx.registerFunction("toStringNoDot", [](const DNSName& name) { return name.toStringNoDot(); }); + luaCtx.registerFunction("__tostring", [](const DNSName& name) { return name.toString(); }); + luaCtx.registerFunction("toDNSString", [](const DNSName& name) { return name.toDNSString(); }); + luaCtx.registerFunction("makeRelative", [](const DNSName& name, const DNSName& relTo) { return name.makeRelative(relTo); }); luaCtx.writeFunction("newDNSName", [](const std::string& name) { return DNSName(name); }); luaCtx.writeFunction("newDNSNameFromRaw", [](const std::string& name) { return DNSName(name.c_str(), name.size(), 0, false); }); luaCtx.writeFunction("newSuffixMatchNode", []() { return SuffixMatchNode(); }); @@ -280,12 +281,12 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) /* DNSNameSet */ luaCtx.registerFunction("toString", [](const DNSNameSet& dns) { return dns.toString(); }); luaCtx.registerFunction("__tostring", [](const DNSNameSet& dns) { return dns.toString(); }); - luaCtx.registerFunction("add", [](DNSNameSet& dns, DNSName& dn) { dns.insert(dn); }); - luaCtx.registerFunction("check", [](DNSNameSet& dns, DNSName& dn) { return dns.find(dn) != dns.end(); }); - luaCtx.registerFunction("delete", (size_t(DNSNameSet::*)(const DNSName&)) & DNSNameSet::erase); - luaCtx.registerFunction("size", (size_t(DNSNameSet::*)() const) & DNSNameSet::size); - luaCtx.registerFunction("clear", (void(DNSNameSet::*)()) & DNSNameSet::clear); - luaCtx.registerFunction("empty", (bool(DNSNameSet::*)() const) & DNSNameSet::empty); + luaCtx.registerFunction("add", [](DNSNameSet& dns, DNSName& name) { dns.insert(name); }); + luaCtx.registerFunction("check", [](DNSNameSet& dns, DNSName& name) { return dns.find(name) != dns.end(); }); + luaCtx.registerFunction("delete", (size_t (DNSNameSet::*)(const DNSName&)) &DNSNameSet::erase); + luaCtx.registerFunction("size", (size_t (DNSNameSet::*)() const) &DNSNameSet::size); + luaCtx.registerFunction("clear", (void (DNSNameSet::*)()) &DNSNameSet::clear); + luaCtx.registerFunction("empty", (bool (DNSNameSet::*)() const) &DNSNameSet::empty); #endif /* DISABLE_DNSNAME_BINDINGS */ #ifndef DISABLE_SUFFIX_MATCH_BINDINGS @@ -345,7 +346,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } }); - luaCtx.registerFunction("check", (bool(SuffixMatchNode::*)(const DNSName&) const) & SuffixMatchNode::check); + luaCtx.registerFunction("check", (bool (SuffixMatchNode::*)(const DNSName&) const) &SuffixMatchNode::check); luaCtx.registerFunction (SuffixMatchNode::*)(const DNSName&) const>("getBestMatch", [](const SuffixMatchNode& smn, const DNSName& needle) { boost::optional result{boost::none}; auto res = smn.getBestMatch(needle); @@ -374,13 +375,13 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) }); luaCtx.registerFunction("empty", &Netmask::empty); luaCtx.registerFunction("getBits", &Netmask::getBits); - luaCtx.registerFunction("getNetwork", [](const Netmask& nm) { return nm.getNetwork(); }); // const reference makes this necessary - luaCtx.registerFunction("getMaskedNetwork", [](const Netmask& nm) { return nm.getMaskedNetwork(); }); + luaCtx.registerFunction("getNetwork", [](const Netmask& netmask) { return netmask.getNetwork(); }); // const reference makes this necessary + luaCtx.registerFunction("getMaskedNetwork", [](const Netmask& netmask) { return netmask.getMaskedNetwork(); }); luaCtx.registerFunction("isIpv4", &Netmask::isIPv4); luaCtx.registerFunction("isIPv4", &Netmask::isIPv4); luaCtx.registerFunction("isIpv6", &Netmask::isIPv6); luaCtx.registerFunction("isIPv6", &Netmask::isIPv6); - luaCtx.registerFunction("match", (bool(Netmask::*)(const string&) const) & Netmask::match); + luaCtx.registerFunction("match", (bool (Netmask::*)(const string&) const) &Netmask::match); luaCtx.registerFunction("toString", &Netmask::toString); luaCtx.registerFunction("__tostring", &Netmask::toString); luaCtx.registerEqFunction(&Netmask::operator==); @@ -404,7 +405,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } }); - luaCtx.registerFunction("match", (bool(NetmaskGroup::*)(const ComboAddress&) const) & NetmaskGroup::match); + luaCtx.registerFunction("match", (bool (NetmaskGroup::*)(const ComboAddress&) const) &NetmaskGroup::match); luaCtx.registerFunction("size", &NetmaskGroup::size); luaCtx.registerFunction("clear", &NetmaskGroup::clear); luaCtx.registerFunction("toString", [](const NetmaskGroup& nmg) { return "NetmaskGroup " + nmg.toString(); }); @@ -419,34 +420,34 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) #ifndef DISABLE_CLIENT_STATE_BINDINGS /* ClientState */ - luaCtx.registerFunction("toString", [](const ClientState& fe) { + luaCtx.registerFunction("toString", [](const ClientState& frontend) { setLuaNoSideEffect(); - return fe.local.toStringWithPort(); + return frontend.local.toStringWithPort(); }); - luaCtx.registerFunction("__tostring", [](const ClientState& fe) { + luaCtx.registerFunction("__tostring", [](const ClientState& frontend) { setLuaNoSideEffect(); - return fe.local.toStringWithPort(); + return frontend.local.toStringWithPort(); }); - luaCtx.registerFunction("getType", [](const ClientState& fe) { + luaCtx.registerFunction("getType", [](const ClientState& frontend) { setLuaNoSideEffect(); - return fe.getType(); + return frontend.getType(); }); - luaCtx.registerFunction("getConfiguredTLSProvider", [](const ClientState& fe) { + luaCtx.registerFunction("getConfiguredTLSProvider", [](const ClientState& frontend) { setLuaNoSideEffect(); - if (fe.tlsFrontend != nullptr) { - return fe.tlsFrontend->getRequestedProvider(); + if (frontend.tlsFrontend != nullptr) { + return frontend.tlsFrontend->getRequestedProvider(); } - else if (fe.dohFrontend != nullptr) { + if (frontend.dohFrontend != nullptr) { return std::string("openssl"); } return std::string(); }); - luaCtx.registerFunction("getEffectiveTLSProvider", [](const ClientState& fe) { + luaCtx.registerFunction("getEffectiveTLSProvider", [](const ClientState& frontend) { setLuaNoSideEffect(); - if (fe.tlsFrontend != nullptr) { - return fe.tlsFrontend->getEffectiveProvider(); + if (frontend.tlsFrontend != nullptr) { + return frontend.tlsFrontend->getEffectiveProvider(); } - else if (fe.dohFrontend != nullptr) { + if (frontend.dohFrontend != nullptr) { return std::string("openssl"); } return std::string(); @@ -504,12 +505,13 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) BPFFilter::MapFormat format = BPFFilter::MapFormat::Legacy; bool external = false; - if (opts.count("external")) { + if (opts.count("external") != 0) { const auto& tmp = opts.at("external"); if (tmp.type() != typeid(bool)) { throw std::runtime_error("params is invalid"); } - if ((external = boost::get(tmp))) { + external = boost::get(tmp); + if (external) { format = BPFFilter::MapFormat::WithActions; } } @@ -517,36 +519,34 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) return std::make_shared(mapsConfig, format, external); }); - luaCtx.registerFunction::*)(const ComboAddress& ca, boost::optional action)>("block", [](std::shared_ptr bpf, const ComboAddress& ca, boost::optional action) { + luaCtx.registerFunction::*)(const ComboAddress& addr, boost::optional action)>("block", [](const std::shared_ptr& bpf, const ComboAddress& addr, boost::optional action) { if (bpf) { if (!action) { - return bpf->block(ca, BPFFilter::MatchAction::Drop); + return bpf->block(addr, BPFFilter::MatchAction::Drop); } - else { - BPFFilter::MatchAction match; - - switch (*action) { - case 0: - match = BPFFilter::MatchAction::Pass; - break; - case 1: - match = BPFFilter::MatchAction::Drop; - break; - case 2: - match = BPFFilter::MatchAction::Truncate; - break; - default: - throw std::runtime_error("Unsupported action for BPFFilter::block"); - } - return bpf->block(ca, match); + BPFFilter::MatchAction match{}; + + switch (*action) { + case 0: + match = BPFFilter::MatchAction::Pass; + break; + case 1: + match = BPFFilter::MatchAction::Drop; + break; + case 2: + match = BPFFilter::MatchAction::Truncate; + break; + default: + throw std::runtime_error("Unsupported action for BPFFilter::block"); } + return bpf->block(addr, match); } }); - luaCtx.registerFunction::*)(const string& range, uint32_t action, boost::optional force)>("addRangeRule", [](std::shared_ptr bpf, const string& range, uint32_t action, boost::optional force) { + luaCtx.registerFunction::*)(const string& range, uint32_t action, boost::optional force)>("addRangeRule", [](const std::shared_ptr& bpf, const string& range, uint32_t action, boost::optional force) { if (!bpf) { return; } - BPFFilter::MatchAction match; + BPFFilter::MatchAction match{}; switch (action) { case 0: match = BPFFilter::MatchAction::Pass; @@ -562,44 +562,42 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } return bpf->addRangeRule(Netmask(range), force ? *force : false, match); }); - luaCtx.registerFunction::*)(const DNSName& qname, boost::optional qtype, boost::optional action)>("blockQName", [](std::shared_ptr bpf, const DNSName& qname, boost::optional qtype, boost::optional action) { + luaCtx.registerFunction::*)(const DNSName& qname, boost::optional qtype, boost::optional action)>("blockQName", [](const std::shared_ptr& bpf, const DNSName& qname, boost::optional qtype, boost::optional action) { if (bpf) { if (!action) { return bpf->block(qname, BPFFilter::MatchAction::Drop, qtype ? *qtype : 255); } - else { - BPFFilter::MatchAction match; - - switch (*action) { - case 0: - match = BPFFilter::MatchAction::Pass; - break; - case 1: - match = BPFFilter::MatchAction::Drop; - break; - case 2: - match = BPFFilter::MatchAction::Truncate; - break; - default: - throw std::runtime_error("Unsupported action for BPFFilter::blockQName"); - } - return bpf->block(qname, match, qtype ? *qtype : 255); + BPFFilter::MatchAction match{}; + + switch (*action) { + case 0: + match = BPFFilter::MatchAction::Pass; + break; + case 1: + match = BPFFilter::MatchAction::Drop; + break; + case 2: + match = BPFFilter::MatchAction::Truncate; + break; + default: + throw std::runtime_error("Unsupported action for BPFFilter::blockQName"); } + return bpf->block(qname, match, qtype ? *qtype : 255); } }); - luaCtx.registerFunction::*)(const ComboAddress& ca)>("unblock", [](std::shared_ptr bpf, const ComboAddress& ca) { + luaCtx.registerFunction::*)(const ComboAddress& addr)>("unblock", [](const std::shared_ptr& bpf, const ComboAddress& addr) { if (bpf) { - return bpf->unblock(ca); + return bpf->unblock(addr); } }); - luaCtx.registerFunction::*)(const string& range)>("rmRangeRule", [](std::shared_ptr bpf, const string& range) { + luaCtx.registerFunction::*)(const string& range)>("rmRangeRule", [](const std::shared_ptr& bpf, const string& range) { if (!bpf) { return; } bpf->rmRangeRule(Netmask(range)); }); - luaCtx.registerFunction::*)() const>("lsRangeRule", [](const std::shared_ptr bpf) { + luaCtx.registerFunction::*)() const>("lsRangeRule", [](const std::shared_ptr& bpf) { setLuaNoSideEffect(); std::string res; if (!bpf) { @@ -616,13 +614,13 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } return res; }); - luaCtx.registerFunction::*)(const DNSName& qname, boost::optional qtype)>("unblockQName", [](std::shared_ptr bpf, const DNSName& qname, boost::optional qtype) { + luaCtx.registerFunction::*)(const DNSName& qname, boost::optional qtype)>("unblockQName", [](const std::shared_ptr& bpf, const DNSName& qname, boost::optional qtype) { if (bpf) { return bpf->unblock(qname, qtype ? *qtype : 255); } }); - luaCtx.registerFunction::*)() const>("getStats", [](const std::shared_ptr bpf) { + luaCtx.registerFunction::*)() const>("getStats", [](const std::shared_ptr& bpf) { setLuaNoSideEffect(); std::string res; if (bpf) { @@ -652,7 +650,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) return res; }); - luaCtx.registerFunction::*)()>("attachToAllBinds", [](std::shared_ptr bpf) { + luaCtx.registerFunction::*)()>("attachToAllBinds", [](std::shared_ptr& bpf) { std::string res; if (!g_configurationDone) { throw std::runtime_error("attachToAllBinds() cannot be used at configuration time!"); @@ -665,31 +663,31 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } }); - luaCtx.writeFunction("newDynBPFFilter", [client](std::shared_ptr bpf) { + luaCtx.writeFunction("newDynBPFFilter", [client](std::shared_ptr& bpf) { if (client) { return std::shared_ptr(nullptr); } return std::make_shared(bpf); }); - luaCtx.registerFunction::*)(const ComboAddress& addr, boost::optional seconds)>("block", [](std::shared_ptr dbpf, const ComboAddress& addr, boost::optional seconds) { + luaCtx.registerFunction::*)(const ComboAddress& addr, boost::optional seconds)>("block", [](const std::shared_ptr& dbpf, const ComboAddress& addr, boost::optional seconds) { if (dbpf) { - struct timespec until; + timespec until{}; clock_gettime(CLOCK_MONOTONIC, &until); until.tv_sec += seconds ? *seconds : 10; dbpf->block(addr, until); } }); - luaCtx.registerFunction::*)()>("purgeExpired", [](std::shared_ptr dbpf) { + luaCtx.registerFunction::*)()>("purgeExpired", [](const std::shared_ptr& dbpf) { if (dbpf) { - struct timespec now; + timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now); dbpf->purgeExpired(now); } }); - luaCtx.registerFunction::*)(LuaTypeOrArrayOf)>("excludeRange", [](std::shared_ptr dbpf, LuaTypeOrArrayOf ranges) { + luaCtx.registerFunction::*)(LuaTypeOrArrayOf)>("excludeRange", [](const std::shared_ptr& dbpf, LuaTypeOrArrayOf ranges) { if (!dbpf) { return; } @@ -704,7 +702,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } }); - luaCtx.registerFunction::*)(LuaTypeOrArrayOf)>("includeRange", [](std::shared_ptr dbpf, LuaTypeOrArrayOf ranges) { + luaCtx.registerFunction::*)(LuaTypeOrArrayOf)>("includeRange", [](const std::shared_ptr& dbpf, LuaTypeOrArrayOf ranges) { if (!dbpf) { return; } @@ -728,7 +726,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) if (client) { return std::shared_ptr(nullptr); } - uint32_t queue_id; + uint32_t queue_id{}; uint32_t frameNums{65536}; std::string ifName; std::string path("/sys/fs/bpf/dnsdist/xskmap"); @@ -767,8 +765,9 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) }); luaCtx.registerFunction (EDNSOptionView::*)() const>("getValues", [](const EDNSOptionView& option) { std::vector values; + values.reserve(values.size()); for (const auto& value : option.values) { - values.push_back(std::string(value.content, value.size)); + values.emplace_back(value.content, value.size); } return values; }); @@ -802,7 +801,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) auto itfs = getListOfNetworkInterfaces(); int counter = 1; for (const auto& itf : itfs) { - result.push_back({counter++, itf}); + result.emplace_back(counter++, itf); } return result; }); @@ -812,7 +811,7 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) auto addrs = getListOfAddressesOfNetworkInterface(itf); int counter = 1; for (const auto& addr : addrs) { - result.push_back({counter++, addr.toString()}); + result.emplace_back(counter++, addr.toString()); } return result; }); @@ -822,17 +821,17 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) auto addrs = getListOfRangesOfNetworkInterface(itf); int counter = 1; for (const auto& addr : addrs) { - result.push_back({counter++, addr.toString()}); + result.emplace_back(counter++, addr.toString()); } return result; }); - luaCtx.writeFunction("getMACAddress", [](const std::string& ip) { - return getMACAddress(ComboAddress(ip)); + luaCtx.writeFunction("getMACAddress", [](const std::string& addr) { + return getMACAddress(ComboAddress(addr)); }); luaCtx.writeFunction("getCurrentTime", []() -> timespec { - timespec now; + timespec now{}; if (gettime(&now, true) < 0) { unixDie("Getting timestamp"); } From 9a5ebd13956cd221fac9a0677a9b067fbadcb90e Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 17:37:31 +0100 Subject: [PATCH 13/25] dnsdist: Delint dnsdist-lua-rules.cc --- pdns/dnsdistdist/dnsdist-lua-rules.cc | 174 +++++++++++++------------- 1 file changed, 89 insertions(+), 85 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-lua-rules.cc b/pdns/dnsdistdist/dnsdist-lua-rules.cc index d58bedba765f..c02a9f38d109 100644 --- a/pdns/dnsdistdist/dnsdist-lua-rules.cc +++ b/pdns/dnsdistdist/dnsdist-lua-rules.cc @@ -70,13 +70,13 @@ std::shared_ptr makeRule(const luadnsrule_t& var, const std::string& ca return std::make_shared(nmg, true); } -static boost::uuids::uuid makeRuleID(std::string& id) +static boost::uuids::uuid makeRuleID(std::string& identifier) { - if (id.empty()) { + if (identifier.empty()) { return getUniqueID(); } - return getUniqueID(id); + return getUniqueID(identifier); } void parseRuleParams(boost::optional& params, boost::uuids::uuid& uuid, std::string& name, uint64_t& creationOrder) @@ -92,7 +92,7 @@ void parseRuleParams(boost::optional& params, boost::uuids::uui creationOrder = s_creationOrder++; } -typedef LuaAssociativeTable>> ruleparams_t; +using ruleparams_t = LuaAssociativeTable>>; template static std::string rulesToString(const std::vector& rules, boost::optional& vars) @@ -137,11 +137,11 @@ static void showRules(GlobalStateHolder>* someRuleActions, boost::opti } template -static void rmRule(GlobalStateHolder>* someRuleActions, const boost::variant& id) +static void rmRule(GlobalStateHolder>* someRuleActions, const boost::variant& ruleID) { setLuaSideEffect(); auto rules = someRuleActions->getCopy(); - if (auto str = boost::get(&id)) { + if (const auto* str = boost::get(&ruleID)) { try { const auto uuid = getUniqueID(*str); auto removeIt = std::remove_if(rules.begin(), @@ -167,7 +167,7 @@ static void rmRule(GlobalStateHolder>* someRuleActions, const boost::v rules.end()); } } - else if (auto pos = boost::get(&id)) { + else if (const auto* pos = boost::get(&ruleID)) { if (*pos >= rules.size()) { g_outputBuffer = "Error: attempt to delete non-existing rule\n"; return; @@ -182,8 +182,9 @@ static void moveRuleToTop(GlobalStateHolder>* someRuleActions) { setLuaSideEffect(); auto rules = someRuleActions->getCopy(); - if (rules.empty()) + if (rules.empty()) { return; + } auto subject = *rules.rbegin(); rules.erase(std::prev(rules.end())); rules.insert(rules.begin(), subject); @@ -191,22 +192,24 @@ static void moveRuleToTop(GlobalStateHolder>* someRuleActions) } template -static void mvRule(GlobalStateHolder>* someRespRuleActions, unsigned int from, unsigned int to) +static void mvRule(GlobalStateHolder>* someRespRuleActions, unsigned int from, unsigned int destination) { setLuaSideEffect(); auto rules = someRespRuleActions->getCopy(); - if (from >= rules.size() || to > rules.size()) { + if (from >= rules.size() || destination > rules.size()) { g_outputBuffer = "Error: attempt to move rules from/to invalid index\n"; return; } auto subject = rules[from]; rules.erase(rules.begin() + from); - if (to > rules.size()) + if (destination > rules.size()) { rules.push_back(subject); + } else { - if (from < to) - --to; - rules.insert(rules.begin() + to, subject); + if (from < destination) { + --destination; + } + rules.insert(rules.begin() + destination, subject); } someRespRuleActions->setState(std::move(rules)); } @@ -223,8 +226,8 @@ static std::vector getTopRules(const std::vector& rules, unsigned int top) pos++; } - sort(counts.begin(), counts.end(), [](const decltype(counts)::value_type& a, const decltype(counts)::value_type& b) { - return b.first < a.first; + sort(counts.begin(), counts.end(), [](const decltype(counts)::value_type& lhs, const decltype(counts)::value_type& rhs) { + return rhs.first < lhs.first; }); std::vector results; @@ -260,7 +263,7 @@ static LuaArray toLuaArray(std::vector&& rules) template static boost::optional getRuleFromSelector(const std::vector& rules, const boost::variant& selector) { - if (auto str = boost::get(&selector)) { + if (const auto* str = boost::get(&selector)) { /* let's see if this a UUID */ try { const auto uuid = getUniqueID(*str); @@ -279,7 +282,7 @@ static boost::optional getRuleFromSelector(const std::vector& rules, const } } } - else if (auto pos = boost::get(&selector)) { + else if (const auto* pos = boost::get(&selector)) { /* this will throw a std::out_of_range exception if the supplied position is out of bounds, this is fine */ return rules.at(*pos); @@ -333,76 +336,76 @@ void setupLuaRules(LuaContext& luaCtx) showRules(&g_respruleactions, vars); }); - luaCtx.writeFunction("rmResponseRule", [](boost::variant id) { - rmRule(&g_respruleactions, id); + luaCtx.writeFunction("rmResponseRule", [](const boost::variant& identifier) { + rmRule(&g_respruleactions, identifier); }); luaCtx.writeFunction("mvResponseRuleToTop", []() { moveRuleToTop(&g_respruleactions); }); - luaCtx.writeFunction("mvResponseRule", [](unsigned int from, unsigned int to) { - mvRule(&g_respruleactions, from, to); + luaCtx.writeFunction("mvResponseRule", [](unsigned int from, unsigned int dest) { + mvRule(&g_respruleactions, from, dest); }); luaCtx.writeFunction("showCacheHitResponseRules", [](boost::optional vars) { showRules(&g_cachehitrespruleactions, vars); }); - luaCtx.writeFunction("rmCacheHitResponseRule", [](boost::variant id) { - rmRule(&g_cachehitrespruleactions, id); + luaCtx.writeFunction("rmCacheHitResponseRule", [](const boost::variant& identifier) { + rmRule(&g_cachehitrespruleactions, identifier); }); luaCtx.writeFunction("mvCacheHitResponseRuleToTop", []() { moveRuleToTop(&g_cachehitrespruleactions); }); - luaCtx.writeFunction("mvCacheHitResponseRule", [](unsigned int from, unsigned int to) { - mvRule(&g_cachehitrespruleactions, from, to); + luaCtx.writeFunction("mvCacheHitResponseRule", [](unsigned int from, unsigned int dest) { + mvRule(&g_cachehitrespruleactions, from, dest); }); luaCtx.writeFunction("showCacheInsertedResponseRules", [](boost::optional vars) { showRules(&g_cacheInsertedRespRuleActions, vars); }); - luaCtx.writeFunction("rmCacheInsertedResponseRule", [](boost::variant id) { - rmRule(&g_cacheInsertedRespRuleActions, id); + luaCtx.writeFunction("rmCacheInsertedResponseRule", [](const boost::variant& identifier) { + rmRule(&g_cacheInsertedRespRuleActions, identifier); }); luaCtx.writeFunction("mvCacheInsertedResponseRuleToTop", []() { moveRuleToTop(&g_cacheInsertedRespRuleActions); }); - luaCtx.writeFunction("mvCacheInsertedResponseRule", [](unsigned int from, unsigned int to) { - mvRule(&g_cacheInsertedRespRuleActions, from, to); + luaCtx.writeFunction("mvCacheInsertedResponseRule", [](unsigned int from, unsigned int dest) { + mvRule(&g_cacheInsertedRespRuleActions, from, dest); }); luaCtx.writeFunction("showSelfAnsweredResponseRules", [](boost::optional vars) { showRules(&g_selfansweredrespruleactions, vars); }); - luaCtx.writeFunction("rmSelfAnsweredResponseRule", [](boost::variant id) { - rmRule(&g_selfansweredrespruleactions, id); + luaCtx.writeFunction("rmSelfAnsweredResponseRule", [](const boost::variant& identifier) { + rmRule(&g_selfansweredrespruleactions, identifier); }); luaCtx.writeFunction("mvSelfAnsweredResponseRuleToTop", []() { moveRuleToTop(&g_selfansweredrespruleactions); }); - luaCtx.writeFunction("mvSelfAnsweredResponseRule", [](unsigned int from, unsigned int to) { - mvRule(&g_selfansweredrespruleactions, from, to); + luaCtx.writeFunction("mvSelfAnsweredResponseRule", [](unsigned int from, unsigned int dest) { + mvRule(&g_selfansweredrespruleactions, from, dest); }); - luaCtx.writeFunction("rmRule", [](boost::variant id) { - rmRule(&g_ruleactions, id); + luaCtx.writeFunction("rmRule", [](const boost::variant& identifier) { + rmRule(&g_ruleactions, identifier); }); luaCtx.writeFunction("mvRuleToTop", []() { moveRuleToTop(&g_ruleactions); }); - luaCtx.writeFunction("mvRule", [](unsigned int from, unsigned int to) { - mvRule(&g_ruleactions, from, to); + luaCtx.writeFunction("mvRule", [](unsigned int from, unsigned int dest) { + mvRule(&g_ruleactions, from, dest); }); luaCtx.writeFunction("clearRules", []() { @@ -426,7 +429,7 @@ void setupLuaRules(LuaContext& luaCtx) }); }); - luaCtx.writeFunction("getRule", [](boost::variant selector) -> boost::optional { + luaCtx.writeFunction("getRule", [](const boost::variant& selector) -> boost::optional { auto rules = g_ruleactions.getLocal(); return getRuleFromSelector(*rules, selector); }); @@ -443,7 +446,7 @@ void setupLuaRules(LuaContext& luaCtx) return rulesToString(getTopRules(*rules, (top ? *top : 10)), vars); }); - luaCtx.writeFunction("getCacheHitResponseRule", [](boost::variant selector) -> boost::optional { + luaCtx.writeFunction("getCacheHitResponseRule", [](const boost::variant& selector) -> boost::optional { auto rules = g_cachehitrespruleactions.getLocal(); return getRuleFromSelector(*rules, selector); }); @@ -460,7 +463,7 @@ void setupLuaRules(LuaContext& luaCtx) return rulesToString(getTopRules(*rules, (top ? *top : 10)), vars); }); - luaCtx.writeFunction("getCacheInsertedResponseRule", [](boost::variant selector) -> boost::optional { + luaCtx.writeFunction("getCacheInsertedResponseRule", [](const boost::variant& selector) -> boost::optional { auto rules = g_cacheInsertedRespRuleActions.getLocal(); return getRuleFromSelector(*rules, selector); }); @@ -477,7 +480,7 @@ void setupLuaRules(LuaContext& luaCtx) return rulesToString(getTopRules(*rules, (top ? *top : 10)), vars); }); - luaCtx.writeFunction("getResponseRule", [](boost::variant selector) -> boost::optional { + luaCtx.writeFunction("getResponseRule", [](const boost::variant& selector) -> boost::optional { auto rules = g_respruleactions.getLocal(); return getRuleFromSelector(*rules, selector); }); @@ -494,7 +497,7 @@ void setupLuaRules(LuaContext& luaCtx) return rulesToString(getTopRules(*rules, (top ? *top : 10)), vars); }); - luaCtx.writeFunction("getSelfAnsweredResponseRule", [](boost::variant selector) -> boost::optional { + luaCtx.writeFunction("getSelfAnsweredResponseRule", [](const boost::variant& selector) -> boost::optional { auto rules = g_selfansweredrespruleactions.getLocal(); return getRuleFromSelector(*rules, selector); }); @@ -516,10 +519,10 @@ void setupLuaRules(LuaContext& luaCtx) }); luaCtx.writeFunction("MaxQPSRule", [](unsigned int qps, boost::optional burst) { - if (!burst) + if (!burst) { return std::shared_ptr(new MaxQPSRule(qps)); - else - return std::shared_ptr(new MaxQPSRule(qps, *burst)); + } + return std::shared_ptr(new MaxQPSRule(qps, *burst)); }); luaCtx.writeFunction("RegexRule", [](const std::string& str) { @@ -569,10 +572,11 @@ void setupLuaRules(LuaContext& luaCtx) return std::shared_ptr(new NetmaskGroupRule(nmg, src ? *src : true, quiet ? *quiet : false)); }); - luaCtx.writeFunction("benchRule", [](std::shared_ptr rule, boost::optional times_, boost::optional suffix_) { + luaCtx.writeFunction("benchRule", [](const std::shared_ptr& rule, boost::optional times_, boost::optional suffix_) { setLuaNoSideEffect(); unsigned int times = times_ ? *times_ : 100000; DNSName suffix(suffix_ ? *suffix_ : "powerdns.com"); + // NOLINTNEXTLINE(bugprone-exception-escape): not sure what clang-tidy smoked, but we do not really care here struct item { PacketBuffer packet; @@ -580,33 +584,33 @@ void setupLuaRules(LuaContext& luaCtx) }; vector items; items.reserve(1000); - for (int n = 0; n < 1000; ++n) { - struct item i; - i.ids.qname = DNSName(std::to_string(dns_random_uint32())); - i.ids.qname += suffix; - i.ids.qtype = dns_random(0xff); - i.ids.qclass = QClass::IN; - i.ids.protocol = dnsdist::Protocol::DoUDP; - i.ids.origRemote = ComboAddress("127.0.0.1"); - i.ids.origRemote.sin4.sin_addr.s_addr = random(); - i.ids.queryRealTime.start(); - GenericDNSPacketWriter pw(i.packet, i.ids.qname, i.ids.qtype); - items.push_back(std::move(i)); + for (int counter = 0; counter < 1000; ++counter) { + item entry; + entry.ids.qname = DNSName(std::to_string(dns_random_uint32())); + entry.ids.qname += suffix; + entry.ids.qtype = dns_random(0xff); + entry.ids.qclass = QClass::IN; + entry.ids.protocol = dnsdist::Protocol::DoUDP; + entry.ids.origRemote = ComboAddress("127.0.0.1"); + entry.ids.origRemote.sin4.sin_addr.s_addr = random(); + entry.ids.queryRealTime.start(); + GenericDNSPacketWriter writer(entry.packet, entry.ids.qname, entry.ids.qtype); + items.push_back(std::move(entry)); } int matches = 0; ComboAddress dummy("127.0.0.1"); - StopWatch sw; - sw.start(); - for (unsigned int n = 0; n < times; ++n) { - item& i = items[n % items.size()]; - DNSQuestion dq(i.ids, i.packet); + StopWatch swatch; + swatch.start(); + for (unsigned int counter = 0; counter < times; ++counter) { + item& entry = items[counter % items.size()]; + DNSQuestion dnsQuestion(entry.ids, entry.packet); - if (rule->matches(&dq)) { + if (rule->matches(&dnsQuestion)) { matches++; } } - double udiff = sw.udiff(); + double udiff = swatch.udiff(); g_outputBuffer = (boost::format("Had %d matches out of %d, %.1f qps, in %.1f us\n") % matches % times % (1000000 * (1.0 * times / udiff)) % udiff).str(); }); @@ -625,23 +629,23 @@ void setupLuaRules(LuaContext& luaCtx) luaCtx.writeFunction("QNameSuffixRule", qnameSuffixRule); luaCtx.writeFunction("QTypeRule", [](boost::variant str) { - uint16_t qtype; - if (auto dir = boost::get(&str)) { + uint16_t qtype{}; + if (const auto* dir = boost::get(&str)) { qtype = *dir; } else { string val = boost::get(str); qtype = QType::chartocode(val.c_str()); - if (!qtype) { + if (qtype == 0) { throw std::runtime_error("Unable to convert '" + val + "' to a DNS type"); } } return std::shared_ptr(new QTypeRule(qtype)); }); - luaCtx.writeFunction("QClassRule", [](uint64_t c) { - checkParameterBound("QClassRule", c, std::numeric_limits::max()); - return std::shared_ptr(new QClassRule(c)); + luaCtx.writeFunction("QClassRule", [](uint64_t cla) { + checkParameterBound("QClassRule", cla, std::numeric_limits::max()); + return std::shared_ptr(new QClassRule(cla)); }); luaCtx.writeFunction("OpcodeRule", [](uint64_t code) { @@ -649,12 +653,12 @@ void setupLuaRules(LuaContext& luaCtx) return std::shared_ptr(new OpcodeRule(code)); }); - luaCtx.writeFunction("AndRule", [](const LuaArray>& a) { - return std::shared_ptr(new AndRule(a)); + luaCtx.writeFunction("AndRule", [](const LuaArray>& rules) { + return std::shared_ptr(new AndRule(rules)); }); - luaCtx.writeFunction("OrRule", [](const LuaArray>& a) { - return std::shared_ptr(new OrRule(a)); + luaCtx.writeFunction("OrRule", [](const LuaArray>& rules) { + return std::shared_ptr(new OrRule(rules)); }); luaCtx.writeFunction("DSTPortRule", [](uint64_t port) { @@ -736,7 +740,7 @@ void setupLuaRules(LuaContext& luaCtx) }); luaCtx.writeFunction("TimedIPSetRule", []() { - return std::shared_ptr(new TimedIPSetRule()); + return std::make_shared(); }); luaCtx.writeFunction("PoolAvailableRule", [](const std::string& poolname) { @@ -747,22 +751,22 @@ void setupLuaRules(LuaContext& luaCtx) return std::shared_ptr(new PoolOutstandingRule(poolname, limit)); }); - luaCtx.registerFunction::*)()>("clear", [](std::shared_ptr tisr) { + luaCtx.registerFunction::*)()>("clear", [](const std::shared_ptr& tisr) { tisr->clear(); }); - luaCtx.registerFunction::*)()>("cleanup", [](std::shared_ptr tisr) { + luaCtx.registerFunction::*)()>("cleanup", [](const std::shared_ptr& tisr) { tisr->cleanup(); }); - luaCtx.registerFunction::*)(const ComboAddress& ca, int t)>("add", [](std::shared_ptr tisr, const ComboAddress& ca, int t) { - tisr->add(ca, time(0) + t); + luaCtx.registerFunction::*)(const ComboAddress&, int)>("add", [](const std::shared_ptr& tisr, const ComboAddress& addr, int additional) { + tisr->add(addr, time(nullptr) + additional); }); - luaCtx.registerFunction (std::shared_ptr::*)()>("slice", [](std::shared_ptr tisr) { + luaCtx.registerFunction (std::shared_ptr::*)()>("slice", [](const std::shared_ptr& tisr) { return std::dynamic_pointer_cast(tisr); }); - luaCtx.registerFunction::*)()>("__tostring", [](std::shared_ptr tisr) { + luaCtx.registerFunction::*)()>("__tostring", [](const std::shared_ptr& tisr) { tisr->toString(); }); @@ -780,11 +784,11 @@ void setupLuaRules(LuaContext& luaCtx) }); #endif /* defined(HAVE_LMDB) || defined(HAVE_CDB) */ - luaCtx.writeFunction("LuaRule", [](LuaRule::func_t func) { + luaCtx.writeFunction("LuaRule", [](const LuaRule::func_t& func) { return std::shared_ptr(new LuaRule(func)); }); - luaCtx.writeFunction("LuaFFIRule", [](LuaFFIRule::func_t func) { + luaCtx.writeFunction("LuaFFIRule", [](const LuaFFIRule::func_t& func) { return std::shared_ptr(new LuaFFIRule(func)); }); From 0a53d3427e2a61adf8ad28ffd83710a30d02390e Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 4 Mar 2024 17:38:44 +0100 Subject: [PATCH 14/25] dnsdist: Delint dnsdist-lua-inspection.cc --- pdns/dnsdistdist/dnsdist-lua-inspection.cc | 646 +++++++++++---------- 1 file changed, 346 insertions(+), 300 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-lua-inspection.cc b/pdns/dnsdistdist/dnsdist-lua-inspection.cc index 304a05af5d01..f5fdcca8a70b 100644 --- a/pdns/dnsdistdist/dnsdist-lua-inspection.cc +++ b/pdns/dnsdistdist/dnsdist-lua-inspection.cc @@ -31,29 +31,31 @@ #include "statnode.hh" #ifndef DISABLE_TOP_N_BINDINGS -static LuaArray>> getGenResponses(uint64_t top, boost::optional labels, std::function pred) +static LuaArray>> getGenResponses(uint64_t top, boost::optional labels, const std::function& pred) { setLuaNoSideEffect(); map counts; unsigned int total = 0; { for (const auto& shard : g_rings.d_shards) { - auto rl = shard->respRing.lock(); + auto respRing = shard->respRing.lock(); if (!labels) { - for (const auto& a : *rl) { - if (!pred(a)) + for (const auto& entry : *respRing) { + if (!pred(entry)) { continue; - counts[a.name]++; + } + counts[entry.name]++; total++; } } else { unsigned int lab = *labels; - for (const auto& a : *rl) { - if (!pred(a)) + for (const auto& entry : *respRing) { + if (!pred(entry)) { continue; + } - DNSName temp(a.name); + DNSName temp(entry.name); temp.trimToLabels(lab); counts[temp]++; total++; @@ -64,23 +66,24 @@ static LuaArray>> getGenResponses(uin // cout<<"Looked at "<> rcounts; rcounts.reserve(counts.size()); - for (const auto& c : counts) - rcounts.emplace_back(c.second, c.first.makeLowerCase()); + for (const auto& val : counts) { + rcounts.emplace_back(val.second, val.first.makeLowerCase()); + } - sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& a, const decltype(rcounts)::value_type& b) { - return b.first < a.first; + sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& lhs, const decltype(rcounts)::value_type& rhs) { + return rhs.first < lhs.first; }); LuaArray>> ret; ret.reserve(std::min(rcounts.size(), static_cast(top + 1U))); int count = 1; unsigned int rest = 0; - for (const auto& rc : rcounts) { + for (const auto& rcEntry : rcounts) { if (count == static_cast(top + 1)) { - rest += rc.first; + rest += rcEntry.first; } else { - ret.push_back({count++, {rc.second.toString(), rc.first, 100.0 * rc.first / total}}); + ret.emplace_back(count++, std::vector>{rcEntry.second.toString(), rcEntry.first, 100.0 * rcEntry.first / total}); } } @@ -98,7 +101,7 @@ static LuaArray>> getGenResponses(uin #ifndef DISABLE_DYNBLOCKS #ifndef DISABLE_DEPRECATED_DYNBLOCK -typedef std::unordered_map counts_t; +using counts_t = std::unordered_map; static counts_t filterScore(const counts_t& counts, double delta, unsigned int rate) @@ -106,9 +109,9 @@ static counts_t filterScore(const counts_t& counts, counts_t ret; double lim = delta * rate; - for (const auto& c : counts) { - if (c.second > lim) { - ret[c.first] = c.second; + for (const auto& entry : counts) { + if (entry.second > lim) { + ret[entry.first] = entry.second; } } @@ -119,26 +122,26 @@ using statvisitor_t = std::function(seconds); StatNode root; for (const auto& shard : g_rings.d_shards) { - auto rl = shard->respRing.lock(); + auto respRing = shard->respRing.lock(); - for (const auto& c : *rl) { - if (now < c.when) { + for (const auto& entry : *respRing) { + if (now < entry.when) { continue; } - if (seconds && c.when < cutoff) { + if (seconds != 0 && entry.when < cutoff) { continue; } - const bool hit = c.isACacheHit(); - root.submit(c.name, ((c.dh.rcode == 0 && c.usec == std::numeric_limits::max()) ? -1 : c.dh.rcode), c.size, hit, boost::none); + const bool hit = entry.isACacheHit(); + root.submit(entry.name, ((entry.dh.rcode == 0 && entry.usec == std::numeric_limits::max()) ? -1 : entry.dh.rcode), entry.size, hit, boost::none); } } @@ -148,21 +151,21 @@ static void statNodeRespRing(statvisitor_t visitor, uint64_t seconds) static LuaArray> getRespRing(boost::optional rcode) { - typedef LuaAssociativeTable entry_t; + using entry_t = LuaAssociativeTable; LuaArray ret; for (const auto& shard : g_rings.d_shards) { - auto rl = shard->respRing.lock(); + auto respRing = shard->respRing.lock(); int count = 1; - for (const auto& c : *rl) { - if (rcode && (rcode.get() != c.dh.rcode)) { + for (const auto& entry : *respRing) { + if (rcode && (rcode.get() != entry.dh.rcode)) { continue; } - entry_t e; - e["qname"] = c.name.toString(); - e["rcode"] = std::to_string(c.dh.rcode); - ret.emplace_back(count, std::move(e)); + entry_t newEntry; + newEntry["qname"] = entry.name.toString(); + newEntry["rcode"] = std::to_string(entry.dh.rcode); + ret.emplace_back(count, std::move(newEntry)); count++; } } @@ -170,79 +173,182 @@ static LuaArray> getRespRing(boost::optional T) +static counts_t exceedRespGen(unsigned int rate, int seconds, const std::function& visitor) { counts_t counts; - struct timespec cutoff, mintime, now; + timespec now{}; gettime(&now); - cutoff = mintime = now; + timespec mintime{now}; + timespec cutoff{now}; cutoff.tv_sec -= seconds; counts.reserve(g_rings.getNumberOfResponseEntries()); for (const auto& shard : g_rings.d_shards) { - auto rl = shard->respRing.lock(); - for (const auto& c : *rl) { + auto respRing = shard->respRing.lock(); + for (const auto& entry : *respRing) { - if (seconds && c.when < cutoff) + if (seconds != 0 && entry.when < cutoff) { continue; - if (now < c.when) + } + if (now < entry.when) { continue; + } - T(counts, c); - if (c.when < mintime) - mintime = c.when; + visitor(counts, entry); + if (entry.when < mintime) { + mintime = entry.when; + } } } - double delta = seconds ? seconds : DiffTime(now, mintime); + double delta = seconds != 0 ? seconds : DiffTime(now, mintime); return filterScore(counts, delta, rate); } -static counts_t exceedQueryGen(unsigned int rate, int seconds, std::function T) +static counts_t exceedQueryGen(unsigned int rate, int seconds, const std::function& visitor) { counts_t counts; - struct timespec cutoff, mintime, now; + timespec now{}; gettime(&now); - cutoff = mintime = now; + timespec mintime{now}; + timespec cutoff{now}; cutoff.tv_sec -= seconds; counts.reserve(g_rings.getNumberOfQueryEntries()); for (const auto& shard : g_rings.d_shards) { - auto rl = shard->queryRing.lock(); - for (const auto& c : *rl) { - if (seconds && c.when < cutoff) + auto respRing = shard->queryRing.lock(); + for (const auto& entry : *respRing) { + if (seconds != 0 && entry.when < cutoff) { continue; - if (now < c.when) + } + if (now < entry.when) { continue; - T(counts, c); - if (c.when < mintime) - mintime = c.when; + } + visitor(counts, entry); + if (entry.when < mintime) { + mintime = entry.when; + } } } - double delta = seconds ? seconds : DiffTime(now, mintime); + double delta = seconds != 0 ? seconds : DiffTime(now, mintime); return filterScore(counts, delta, rate); } static counts_t exceedRCode(unsigned int rate, int seconds, int rcode) { - return exceedRespGen(rate, seconds, [rcode](counts_t& counts, const Rings::Response& r) { - if (r.dh.rcode == rcode) - counts[r.requestor]++; + return exceedRespGen(rate, seconds, [rcode](counts_t& counts, const Rings::Response& resp) { + if (resp.dh.rcode == rcode) { + counts[resp.requestor]++; + } }); } static counts_t exceedRespByterate(unsigned int rate, int seconds) { - return exceedRespGen(rate, seconds, [](counts_t& counts, const Rings::Response& r) { - counts[r.requestor] += r.size; + return exceedRespGen(rate, seconds, [](counts_t& counts, const Rings::Response& resp) { + counts[resp.requestor] += resp.size; }); } #endif /* DISABLE_DEPRECATED_DYNBLOCK */ #endif /* DISABLE_DYNBLOCKS */ + +// NOLINTNEXTLINE(bugprone-exception-escape) +struct GrepQParams +{ + boost::optional netmask; + boost::optional name; + std::unique_ptr outputFile{nullptr, fclose}; + int msec = -1; +}; + +static std::optional parseGrepQParams(const LuaTypeOrArrayOf& inp, boost::optional>& options) +{ + GrepQParams result{}; + + if (options) { + std::string outputFileName; + if (getOptionalValue(options, "outputFile", outputFileName) > 0) { + int fileDesc = open(outputFileName.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0600); + if (fileDesc < 0) { + g_outputBuffer = "Error opening dump file for writing: " + stringerror() + "\n"; + return std::nullopt; + } + result.outputFile = std::unique_ptr(fdopen(fileDesc, "w"), fclose); + if (result.outputFile == nullptr) { + g_outputBuffer = "Error opening dump file for writing: " + stringerror() + "\n"; + close(fileDesc); + return std::nullopt; + } + } + checkAllParametersConsumed("grepq", options); + } + + vector filters; + const auto* str = boost::get(&inp); + if (str != nullptr) { + filters.push_back(*str); + } + else { + auto values = boost::get>(inp); + for (const auto& filter : values) { + filters.push_back(filter.second); + } + } + + for (const auto& filter : filters) { + try { + result.netmask = Netmask(filter); + } + catch (...) { + if (boost::ends_with(filter, "ms") && sscanf(filter.c_str(), "%ums", &result.msec) != 0) { + ; + } + else { + try { + result.name = DNSName(filter); + } + catch (...) { + g_outputBuffer = "Could not parse '" + filter + "' as domain name or netmask"; + return std::nullopt; + } + } + } + } + return result; +} + +template +static bool ringEntryMatches(const GrepQParams& params, const C& entry) +{ + bool nmmatch = true; + bool dnmatch = true; + bool msecmatch = true; + if (params.netmask) { + nmmatch = params.netmask->match(entry.requestor); + } + if (params.name) { + if (entry.name.empty()) { + dnmatch = false; + } + else { + dnmatch = entry.name.isPartOf(*params.name); + } + } + + constexpr bool response = std::is_same_v; + if constexpr (response) { + if (params.msec != -1) { + msecmatch = (entry.usec / 1000 > static_cast(params.msec)); + } + } + + return nmmatch && dnmatch && msecmatch; +} + // NOLINTNEXTLINE(readability-function-cognitive-complexity): this function declares Lua bindings, even with a good refactoring it will likely blow up the threshold void setupLuaInspection(LuaContext& luaCtx) { @@ -254,28 +360,32 @@ void setupLuaInspection(LuaContext& luaCtx) unsigned int total = 0; { for (const auto& shard : g_rings.d_shards) { - auto rl = shard->queryRing.lock(); - for (const auto& c : *rl) { - counts[c.requestor]++; + auto respRing = shard->queryRing.lock(); + for (const auto& entry : *respRing) { + counts[entry.requestor]++; total++; } } } vector> rcounts; rcounts.reserve(counts.size()); - for (const auto& c : counts) - rcounts.emplace_back(c.second, c.first); + for (const auto& entry : counts) { + rcounts.emplace_back(entry.second, entry.first); + } - sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& a, const decltype(rcounts)::value_type& b) { - return b.first < a.first; + sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& lhs, const decltype(rcounts)::value_type& rhs) { + return rhs.first < lhs.first; }); - unsigned int count = 1, rest = 0; + unsigned int count = 1; + unsigned int rest = 0; boost::format fmt("%4d %-40s %4d %4.1f%%\n"); - for (const auto& rc : rcounts) { - if (count == top + 1) - rest += rc.first; - else - g_outputBuffer += (fmt % (count++) % rc.second.toString() % rc.first % (100.0 * rc.first / total)).str(); + for (const auto& entry : rcounts) { + if (count == top + 1) { + rest += entry.first; + } + else { + g_outputBuffer += (fmt % (count++) % entry.second.toString() % entry.first % (100.0 * entry.first / total)).str(); + } } g_outputBuffer += (fmt % (count) % "Rest" % rest % (total > 0 ? 100.0 * rest / total : 100.0)).str(); }); @@ -286,9 +396,9 @@ void setupLuaInspection(LuaContext& luaCtx) unsigned int total = 0; if (!labels) { for (const auto& shard : g_rings.d_shards) { - auto rl = shard->queryRing.lock(); - for (const auto& a : *rl) { - counts[a.name]++; + auto respRing = shard->queryRing.lock(); + for (const auto& entry : *respRing) { + counts[entry.name]++; total++; } } @@ -296,32 +406,36 @@ void setupLuaInspection(LuaContext& luaCtx) else { unsigned int lab = *labels; for (const auto& shard : g_rings.d_shards) { - auto rl = shard->queryRing.lock(); - // coverity[auto_causes_copy] - for (auto a : *rl) { - a.name.trimToLabels(lab); - counts[a.name]++; + auto respRing = shard->queryRing.lock(); + for (const auto& entry : *respRing) { + auto name = entry.name; + name.trimToLabels(lab); + counts[name]++; total++; } } } - // cout<<"Looked at "<> rcounts; rcounts.reserve(counts.size()); - for (const auto& c : counts) - rcounts.emplace_back(c.second, c.first.makeLowerCase()); + for (const auto& entry : counts) { + rcounts.emplace_back(entry.second, entry.first.makeLowerCase()); + } - sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& a, const decltype(rcounts)::value_type& b) { - return b.first < a.first; + sort(rcounts.begin(), rcounts.end(), [](const decltype(rcounts)::value_type& lhs, const decltype(rcounts)::value_type& rhs) { + return rhs.first < lhs.first; }); std::unordered_map>> ret; - unsigned int count = 1, rest = 0; - for (const auto& rc : rcounts) { - if (count == top + 1) - rest += rc.first; - else - ret.insert({count++, {rc.second.toString(), rc.first, 100.0 * rc.first / total}}); + unsigned int count = 1; + unsigned int rest = 0; + for (const auto& entry : rcounts) { + if (count == top + 1) { + rest += entry.first; + } + else { + ret.insert({count++, {entry.second.toString(), entry.first, 100.0 * entry.first / total}}); + } } if (total > 0) { @@ -343,34 +457,34 @@ void setupLuaInspection(LuaContext& luaCtx) rings.reserve(g_rings.getNumberOfShards()); for (const auto& shard : g_rings.d_shards) { { - auto rl = shard->respRing.lock(); - rings.push_back(*rl); + auto respRing = shard->respRing.lock(); + rings.push_back(*respRing); } totalEntries += rings.back().size(); } vector>> ret; ret.reserve(totalEntries); - decltype(ret)::value_type item; - for (size_t idx = 0; idx < rings.size(); idx++) { - for (const auto& r : rings[idx]) { - item["name"] = r.name.toString(); - item["qtype"] = r.qtype; - item["rcode"] = r.dh.rcode; - item["usec"] = r.usec; - ret.push_back(item); + for (const auto& ring : rings) { + for (const auto& entry : ring) { + decltype(ret)::value_type item; + item["name"] = entry.name.toString(); + item["qtype"] = entry.qtype; + item["rcode"] = entry.dh.rcode; + item["usec"] = entry.usec; + ret.push_back(std::move(item)); } } return ret; }); luaCtx.writeFunction("getTopResponses", [](uint64_t top, uint64_t kind, boost::optional labels) { - return getGenResponses(top, labels, [kind](const Rings::Response& r) { return r.dh.rcode == kind; }); + return getGenResponses(top, labels, [kind](const Rings::Response& resp) { return resp.dh.rcode == kind; }); }); luaCtx.executeCode(R"(function topResponses(top, kind, labels) top = top or 10; kind = kind or 0; for k,v in ipairs(getTopResponses(top, kind, labels)) do show(string.format("%4d %-40s %4d %4.1f%%",k,v[1],v[2],v[3])) end end)"); luaCtx.writeFunction("getSlowResponses", [](uint64_t top, uint64_t msec, boost::optional labels) { - return getGenResponses(top, labels, [msec](const Rings::Response& r) { return r.usec > msec * 1000; }); + return getGenResponses(top, labels, [msec](const Rings::Response& resp) { return resp.usec > msec * 1000; }); }); luaCtx.executeCode(R"(function topSlow(top, msec, labels) top = top or 10; msec = msec or 500; for k,v in ipairs(getSlowResponses(top, msec, labels)) do show(string.format("%4d %-40s %4d %4.1f%%",k,v[1],v[2],v[3])) end end)"); @@ -386,200 +500,123 @@ void setupLuaInspection(LuaContext& luaCtx) luaCtx.writeFunction("delta", []() { setLuaNoSideEffect(); // we hold the lua lock already! - for (const auto& d : g_confDelta) { - struct tm tm; - localtime_r(&d.first.tv_sec, &tm); - char date[80]; - strftime(date, sizeof(date) - 1, "-- %a %b %d %Y %H:%M:%S %Z\n", &tm); - g_outputBuffer += date; - g_outputBuffer += d.second + "\n"; + for (const auto& entry : g_confDelta) { + tm entryTime{}; + localtime_r(&entry.first.tv_sec, &entryTime); + std::array date{}; + strftime(date.data(), date.size() - 1, "-- %a %b %d %Y %H:%M:%S %Z\n", &entryTime); + g_outputBuffer += date.data(); + g_outputBuffer += entry.second + "\n"; } }); - luaCtx.writeFunction("grepq", [](LuaTypeOrArrayOf inp, boost::optional limit, boost::optional> options) { + luaCtx.writeFunction("grepq", [](const LuaTypeOrArrayOf& inp, boost::optional limit, boost::optional> options) { setLuaNoSideEffect(); - boost::optional nm; - boost::optional dn; - int msec = -1; - std::unique_ptr outputFile{nullptr, fclose}; - - if (options) { - std::string outputFileName; - if (getOptionalValue(options, "outputFile", outputFileName) > 0) { - int fd = open(outputFileName.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0600); - if (fd < 0) { - g_outputBuffer = "Error opening dump file for writing: " + stringerror() + "\n"; - return; - } - outputFile = std::unique_ptr(fdopen(fd, "w"), fclose); - if (outputFile == nullptr) { - g_outputBuffer = "Error opening dump file for writing: " + stringerror() + "\n"; - close(fd); - return; - } - } - checkAllParametersConsumed("grepq", options); - } - - vector vec; - auto str = boost::get(&inp); - if (str) { - vec.push_back(*str); - } - else { - auto v = boost::get>(inp); - for (const auto& a : v) { - vec.push_back(a.second); - } - } - for (const auto& s : vec) { - try { - nm = Netmask(s); - } - catch (...) { - if (boost::ends_with(s, "ms") && sscanf(s.c_str(), "%ums", &msec)) { - ; - } - else { - try { - dn = DNSName(s); - } - catch (...) { - g_outputBuffer = "Could not parse '" + s + "' as domain name or netmask"; - return; - } - } - } + auto paramsOrError = parseGrepQParams(inp, options); + if (!paramsOrError) { + return; } + auto params = std::move(*paramsOrError); - std::vector qr; - std::vector rr; - qr.reserve(g_rings.getNumberOfQueryEntries()); - rr.reserve(g_rings.getNumberOfResponseEntries()); + std::vector queries; + std::vector responses; + queries.reserve(g_rings.getNumberOfQueryEntries()); + responses.reserve(g_rings.getNumberOfResponseEntries()); for (const auto& shard : g_rings.d_shards) { { - auto rl = shard->queryRing.lock(); - for (const auto& entry : *rl) { - qr.push_back(entry); + auto respRing = shard->queryRing.lock(); + for (const auto& entry : *respRing) { + queries.push_back(entry); } } { - auto rl = shard->respRing.lock(); - for (const auto& entry : *rl) { - rr.push_back(entry); + auto respRing = shard->respRing.lock(); + for (const auto& entry : *respRing) { + responses.push_back(entry); } } } - sort(qr.begin(), qr.end(), [](const decltype(qr)::value_type& a, const decltype(qr)::value_type& b) { - return b.when < a.when; + sort(queries.begin(), queries.end(), [](const decltype(queries)::value_type& lhs, const decltype(queries)::value_type& rhs) { + return rhs.when < lhs.when; }); - sort(rr.begin(), rr.end(), [](const decltype(rr)::value_type& a, const decltype(rr)::value_type& b) { - return b.when < a.when; + sort(responses.begin(), responses.end(), [](const decltype(responses)::value_type& lhs, const decltype(responses)::value_type& rhs) { + return rhs.when < lhs.when; }); unsigned int num = 0; - struct timespec now; + timespec now{}; gettime(&now); std::multimap out; boost::format fmt("%-7.1f %-47s %-12s %-12s %-5d %-25s %-5s %-6.1f %-2s %-2s %-2s %-s\n"); const auto headLine = (fmt % "Time" % "Client" % "Protocol" % "Server" % "ID" % "Name" % "Type" % "Lat." % "TC" % "RD" % "AA" % "Rcode").str(); - if (!outputFile) { + if (!params.outputFile) { g_outputBuffer += headLine; } else { - fprintf(outputFile.get(), "%s", headLine.c_str()); + fprintf(params.outputFile.get(), "%s", headLine.c_str()); } - if (msec == -1) { - for (const auto& c : qr) { - bool nmmatch = true; - bool dnmatch = true; - if (nm) { - nmmatch = nm->match(c.requestor); + if (params.msec == -1) { + for (const auto& entry : queries) { + if (!ringEntryMatches(params, entry)) { + continue; } - if (dn) { - if (c.name.empty()) { - dnmatch = false; - } - else { - dnmatch = c.name.isPartOf(*dn); - } + QType qtype(entry.qtype); + std::string extra; + if (entry.dh.opcode != 0) { + extra = " (" + Opcode::to_s(entry.dh.opcode) + ")"; } - if (nmmatch && dnmatch) { - QType qt(c.qtype); - std::string extra; - if (c.dh.opcode != 0) { - extra = " (" + Opcode::to_s(c.dh.opcode) + ")"; - } - out.emplace(c.when, (fmt % DiffTime(now, c.when) % c.requestor.toStringWithPort() % dnsdist::Protocol(c.protocol).toString() % "" % htons(c.dh.id) % c.name.toString() % qt.toString() % "" % (c.dh.tc ? "TC" : "") % (c.dh.rd ? "RD" : "") % (c.dh.aa ? "AA" : "") % ("Question" + extra)).str()); + out.emplace(entry.when, (fmt % DiffTime(now, entry.when) % entry.requestor.toStringWithPort() % dnsdist::Protocol(entry.protocol).toString() % "" % htons(entry.dh.id) % entry.name.toString() % qtype.toString() % "" % (entry.dh.tc != 0 ? "TC" : "") % (entry.dh.rd != 0 ? "RD" : "") % (entry.dh.aa != 0 ? "AA" : "") % ("Question" + extra)).str()); - if (limit && *limit == ++num) { - break; - } + if (limit && *limit == ++num) { + break; } } } num = 0; string extra; - for (const auto& c : rr) { - bool nmmatch = true; - bool dnmatch = true; - bool msecmatch = true; - if (nm) { - nmmatch = nm->match(c.requestor); - } - if (dn) { - if (c.name.empty()) { - dnmatch = false; - } - else { - dnmatch = c.name.isPartOf(*dn); - } + for (const auto& entry : responses) { + if (!ringEntryMatches(params, entry)) { + continue; } - if (msec != -1) { - msecmatch = (c.usec / 1000 > (unsigned int)msec); + QType qtype(entry.qtype); + if (entry.dh.rcode == 0) { + extra = ". " + std::to_string(htons(entry.dh.ancount)) + " answers"; + } + else { + extra.clear(); } - if (nmmatch && dnmatch && msecmatch) { - QType qt(c.qtype); - if (!c.dh.rcode) { - extra = ". " + std::to_string(htons(c.dh.ancount)) + " answers"; - } - else { - extra.clear(); - } - - std::string server = c.ds.toStringWithPort(); - std::string protocol = dnsdist::Protocol(c.protocol).toString(); - if (server == "0.0.0.0:0") { - server = "Cache"; - protocol = "-"; - } - if (c.usec != std::numeric_limits::max()) { - out.emplace(c.when, (fmt % DiffTime(now, c.when) % c.requestor.toStringWithPort() % protocol % server % htons(c.dh.id) % c.name.toString() % qt.toString() % (c.usec / 1000.0) % (c.dh.tc ? "TC" : "") % (c.dh.rd ? "RD" : "") % (c.dh.aa ? "AA" : "") % (RCode::to_s(c.dh.rcode) + extra)).str()); - } - else { - out.emplace(c.when, (fmt % DiffTime(now, c.when) % c.requestor.toStringWithPort() % protocol % server % htons(c.dh.id) % c.name.toString() % qt.toString() % "T.O" % (c.dh.tc ? "TC" : "") % (c.dh.rd ? "RD" : "") % (c.dh.aa ? "AA" : "") % (RCode::to_s(c.dh.rcode) + extra)).str()); - } + std::string server = entry.ds.toStringWithPort(); + std::string protocol = dnsdist::Protocol(entry.protocol).toString(); + if (server == "0.0.0.0:0") { + server = "Cache"; + protocol = "-"; + } + if (entry.usec != std::numeric_limits::max()) { + out.emplace(entry.when, (fmt % DiffTime(now, entry.when) % entry.requestor.toStringWithPort() % protocol % server % htons(entry.dh.id) % entry.name.toString() % qtype.toString() % (entry.usec / 1000.0) % (entry.dh.tc != 0 ? "TC" : "") % (entry.dh.rd != 0 ? "RD" : "") % (entry.dh.aa != 0 ? "AA" : "") % (RCode::to_s(entry.dh.rcode) + extra)).str()); + } + else { + out.emplace(entry.when, (fmt % DiffTime(now, entry.when) % entry.requestor.toStringWithPort() % protocol % server % htons(entry.dh.id) % entry.name.toString() % qtype.toString() % "T.O" % (entry.dh.tc != 0 ? "TC" : "") % (entry.dh.rd != 0 ? "RD" : "") % (entry.dh.aa != 0 ? "AA" : "") % (RCode::to_s(entry.dh.rcode) + extra)).str()); + } - if (limit && *limit == ++num) { - break; - } + if (limit && *limit == ++num) { + break; } } - for (const auto& p : out) { - if (!outputFile) { - g_outputBuffer += p.second; + for (const auto& entry : out) { + if (!params.outputFile) { + g_outputBuffer += entry.second; } else { - fprintf(outputFile.get(), "%s", p.second.c_str()); + fprintf(params.outputFile.get(), "%s", entry.second.c_str()); } } }); @@ -588,7 +625,7 @@ void setupLuaInspection(LuaContext& luaCtx) setLuaNoSideEffect(); map histo; double bin = 100; - for (int i = 0; i < 15; ++i) { + for (int idx = 0; idx < 15; ++idx) { histo[bin]; bin *= 2; } @@ -597,19 +634,22 @@ void setupLuaInspection(LuaContext& luaCtx) unsigned int size = 0; { for (const auto& shard : g_rings.d_shards) { - auto rl = shard->respRing.lock(); - for (const auto& r : *rl) { + auto respRing = shard->respRing.lock(); + for (const auto& entry : *respRing) { /* skip actively discovered timeouts */ - if (r.usec == std::numeric_limits::max()) + if (entry.usec == std::numeric_limits::max()) { continue; + } ++size; - auto iter = histo.lower_bound(r.usec); - if (iter != histo.end()) + auto iter = histo.lower_bound(entry.usec); + if (iter != histo.end()) { iter->second++; - else + } + else { histo.rbegin()++; - totlat += r.usec; + } + totlat += entry.usec; } } } @@ -622,23 +662,25 @@ void setupLuaInspection(LuaContext& luaCtx) g_outputBuffer = (boost::format("Average response latency: %.02f ms\n") % (0.001 * totlat / size)).str(); double highest = 0; - for (auto iter = histo.cbegin(); iter != histo.cend(); ++iter) { - highest = std::max(highest, iter->second * 1.0); + for (const auto& entry : histo) { + highest = std::max(highest, entry.second * 1.0); } boost::format fmt("%7.2f\t%s\n"); g_outputBuffer += (fmt % "ms" % "").str(); - for (auto iter = histo.cbegin(); iter != histo.cend(); ++iter) { - int stars = (70.0 * iter->second / highest); - char c = '*'; - if (!stars && iter->second) { + for (const auto& entry : histo) { + int stars = static_cast(70.0 * entry.second / highest); + char value = '*'; + if (stars == 0 && entry.second != 0) { stars = 1; // you get 1 . to show something is there.. - if (70.0 * iter->second / highest > 0.5) - c = ':'; - else - c = '.'; + if (70.0 * entry.second / highest > 0.5) { + value = ':'; + } + else { + value = '.'; + } } - g_outputBuffer += (fmt % (iter->first / 1000.0) % string(stars, c)).str(); + g_outputBuffer += (fmt % (entry.first / 1000.0) % string(stars, value)).str(); } }); @@ -655,8 +697,8 @@ void setupLuaInspection(LuaContext& luaCtx) ret << (fmt % "#" % "Address" % "Connections" % "Max concurrent conn" % "Died reading query" % "Died sending response" % "Gave up" % "Client timeouts" % "Downstream timeouts" % "Avg queries/conn" % "Avg duration" % "TLS new sessions" % "TLS Resumptions" % "TLS unknown ticket keys" % "TLS inactive ticket keys" % "TLS 1.0" % "TLS 1.1" % "TLS 1.2" % "TLS 1.3" % "TLS other") << endl; size_t counter = 0; - for (const auto& f : g_frontends) { - ret << (fmt % counter % f->local.toStringWithPort() % f->tcpCurrentConnections % f->tcpMaxConcurrentConnections % f->tcpDiedReadingQuery % f->tcpDiedSendingResponse % f->tcpGaveUp % f->tcpClientTimeouts % f->tcpDownstreamTimeouts % f->tcpAvgQueriesPerConnection % f->tcpAvgConnectionDuration % f->tlsNewSessions % f->tlsResumptions % f->tlsUnknownTicketKey % f->tlsInactiveTicketKey % f->tls10queries % f->tls11queries % f->tls12queries % f->tls13queries % f->tlsUnknownqueries) << endl; + for (const auto& frontend : g_frontends) { + ret << (fmt % counter % frontend->local.toStringWithPort() % frontend->tcpCurrentConnections % frontend->tcpMaxConcurrentConnections % frontend->tcpDiedReadingQuery % frontend->tcpDiedSendingResponse % frontend->tcpGaveUp % frontend->tcpClientTimeouts % frontend->tcpDownstreamTimeouts % frontend->tcpAvgQueriesPerConnection % frontend->tcpAvgConnectionDuration % frontend->tlsNewSessions % frontend->tlsResumptions % frontend->tlsUnknownTicketKey % frontend->tlsInactiveTicketKey % frontend->tls10queries % frontend->tls11queries % frontend->tls12queries % frontend->tls13queries % frontend->tlsUnknownqueries) << endl; ++counter; } ret << endl; @@ -667,8 +709,8 @@ void setupLuaInspection(LuaContext& luaCtx) auto states = g_dstates.getLocal(); counter = 0; - for (const auto& s : *states) { - ret << (fmt % counter % s->getName() % s->d_config.remote.toStringWithPort() % s->tcpCurrentConnections % s->tcpMaxConcurrentConnections % s->tcpDiedSendingQuery % s->tcpDiedReadingResponse % s->tcpGaveUp % s->tcpReadTimeouts % s->tcpWriteTimeouts % s->tcpConnectTimeouts % s->tcpTooManyConcurrentConnections % s->tcpNewConnections % s->tcpReusedConnections % s->tlsResumptions % s->tcpAvgQueriesPerConnection % s->tcpAvgConnectionDuration) << endl; + for (const auto& backend : *states) { + ret << (fmt % counter % backend->getName() % backend->d_config.remote.toStringWithPort() % backend->tcpCurrentConnections % backend->tcpMaxConcurrentConnections % backend->tcpDiedSendingQuery % backend->tcpDiedReadingResponse % backend->tcpGaveUp % backend->tcpReadTimeouts % backend->tcpWriteTimeouts % backend->tcpConnectTimeouts % backend->tcpTooManyConcurrentConnections % backend->tcpNewConnections % backend->tcpReusedConnections % backend->tlsResumptions % backend->tcpAvgQueriesPerConnection % backend->tcpAvgConnectionDuration) << endl; ++counter; } @@ -683,22 +725,22 @@ void setupLuaInspection(LuaContext& luaCtx) ret << (fmt % "#" % "Address" % "DH key too small" % "Inappropriate fallback" % "No shared cipher" % "Unknown cipher type" % "Unknown exchange type" % "Unknown protocol" % "Unsupported EC" % "Unsupported protocol") << endl; size_t counter = 0; - for (const auto& f : g_frontends) { - if (!f->hasTLS()) { + for (const auto& frontend : g_frontends) { + if (!frontend->hasTLS()) { continue; } const TLSErrorCounters* errorCounters = nullptr; - if (f->tlsFrontend != nullptr) { - errorCounters = &f->tlsFrontend->d_tlsCounters; + if (frontend->tlsFrontend != nullptr) { + errorCounters = &frontend->tlsFrontend->d_tlsCounters; } - else if (f->dohFrontend != nullptr) { - errorCounters = &f->dohFrontend->d_tlsContext.d_tlsCounters; + else if (frontend->dohFrontend != nullptr) { + errorCounters = &frontend->dohFrontend->d_tlsContext.d_tlsCounters; } if (errorCounters == nullptr) { continue; } - ret << (fmt % counter % f->local.toStringWithPort() % errorCounters->d_dhKeyTooSmall % errorCounters->d_inappropriateFallBack % errorCounters->d_noSharedCipher % errorCounters->d_unknownCipherType % errorCounters->d_unknownKeyExchangeType % errorCounters->d_unknownProtocol % errorCounters->d_unsupportedEC % errorCounters->d_unsupportedProtocol) << endl; + ret << (fmt % counter % frontend->local.toStringWithPort() % errorCounters->d_dhKeyTooSmall % errorCounters->d_inappropriateFallBack % errorCounters->d_noSharedCipher % errorCounters->d_unknownCipherType % errorCounters->d_unknownKeyExchangeType % errorCounters->d_unknownProtocol % errorCounters->d_unsupportedEC % errorCounters->d_unsupportedProtocol) << endl; ++counter; } ret << endl; @@ -721,14 +763,15 @@ void setupLuaInspection(LuaContext& luaCtx) luaCtx.writeFunction("dumpStats", [] { setLuaNoSideEffect(); - vector leftcolumn, rightcolumn; + vector leftcolumn; + vector rightcolumn; boost::format fmt("%-35s\t%+11s"); g_outputBuffer.clear(); auto entries = *dnsdist::metrics::g_stats.entries.read_lock(); sort(entries.begin(), entries.end(), - [](const decltype(entries)::value_type& a, const decltype(entries)::value_type& b) { - return a.d_name < b.d_name; + [](const decltype(entries)::value_type& lhs, const decltype(entries)::value_type& rhs) { + return lhs.d_name < rhs.d_name; }); boost::format flt(" %9.1f"); for (const auto& entry : entries) { @@ -754,11 +797,13 @@ void setupLuaInspection(LuaContext& luaCtx) } } - auto leftiter = leftcolumn.begin(), rightiter = rightcolumn.begin(); + auto leftiter = leftcolumn.begin(); + auto rightiter = rightcolumn.begin(); boost::format clmn("%|0t|%1% %|51t|%2%\n"); for (; leftiter != leftcolumn.end() || rightiter != rightcolumn.end();) { - string lentry, rentry; + string lentry; + string rentry; if (leftiter != leftcolumn.end()) { lentry = *leftiter; leftiter++; @@ -789,16 +834,17 @@ void setupLuaInspection(LuaContext& luaCtx) luaCtx.writeFunction("exceedQTypeRate", [](uint16_t type, unsigned int rate, int seconds) { setLuaNoSideEffect(); - return exceedQueryGen(rate, seconds, [type](counts_t& counts, const Rings::Query& q) { - if (q.qtype == type) - counts[q.requestor]++; + return exceedQueryGen(rate, seconds, [type](counts_t& counts, const Rings::Query& query) { + if (query.qtype == type) { + counts[query.requestor]++; + } }); }); luaCtx.writeFunction("exceedQRate", [](unsigned int rate, int seconds) { setLuaNoSideEffect(); - return exceedQueryGen(rate, seconds, [](counts_t& counts, const Rings::Query& q) { - counts[q.requestor]++; + return exceedQueryGen(rate, seconds, [](counts_t& counts, const Rings::Query& query) { + counts[query.requestor]++; }); }); @@ -806,8 +852,8 @@ void setupLuaInspection(LuaContext& luaCtx) /* StatNode */ luaCtx.registerFunction("numChildren", - [](const StatNode& sn) -> unsigned int { - return sn.children.size(); + [](const StatNode& node) -> unsigned int { + return node.children.size(); }); luaCtx.registerMember("fullname", &StatNode::fullname); luaCtx.registerMember("labelsCount", &StatNode::labelsCount); @@ -871,21 +917,21 @@ void setupLuaInspection(LuaContext& luaCtx) group->setCacheMissRatio(ratio, warningRatio ? *warningRatio : 0.0, seconds, reason, blockDuration, action ? *action : DNSAction::Action::None, minimumNumberOfResponses, minimumGlobalCacheHitRatio); } }); - luaCtx.registerFunction::*)(uint8_t, uint8_t, uint8_t)>("setMasks", [](std::shared_ptr& group, uint8_t v4, uint8_t v6, uint8_t port) { + luaCtx.registerFunction::*)(uint8_t, uint8_t, uint8_t)>("setMasks", [](std::shared_ptr& group, uint8_t v4addr, uint8_t v6addr, uint8_t port) { if (group) { - if (v4 > 32) { - throw std::runtime_error("Trying to set an invalid IPv4 mask (" + std::to_string(v4) + ") to a Dynamic Block object"); + if (v4addr > 32) { + throw std::runtime_error("Trying to set an invalid IPv4 mask (" + std::to_string(v4addr) + ") to a Dynamic Block object"); } - if (v6 > 128) { - throw std::runtime_error("Trying to set an invalid IPv6 mask (" + std::to_string(v6) + ") to a Dynamic Block object"); + if (v6addr > 128) { + throw std::runtime_error("Trying to set an invalid IPv6 mask (" + std::to_string(v6addr) + ") to a Dynamic Block object"); } if (port > 16) { throw std::runtime_error("Trying to set an invalid port mask (" + std::to_string(port) + ") to a Dynamic Block object"); } - if (port > 0 && v4 != 32) { + if (port > 0 && v4addr != 32) { throw std::runtime_error("Setting a non-zero port mask for Dynamic Blocks while only considering parts of IPv4 addresses does not make sense"); } - group->setMasks(v4, v6, port); + group->setMasks(v4addr, v6addr, port); } }); luaCtx.registerFunction::*)(boost::variant, NetmaskGroup>)>("excludeRange", [](std::shared_ptr& group, boost::variant, NetmaskGroup> ranges) { From 7d937037d4d5ade331f8e25439c9756023c8476b Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Tue, 5 Mar 2024 09:10:38 +0100 Subject: [PATCH 15/25] dnsdist: Delint dnsdist-rings.cc --- pdns/dnsdistdist/dnsdist-rings.cc | 61 ++++++++++++++++--------------- 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-rings.cc b/pdns/dnsdistdist/dnsdist-rings.cc index 7ab00f1b7ba4..ba55561fede9 100644 --- a/pdns/dnsdistdist/dnsdist-rings.cc +++ b/pdns/dnsdistdist/dnsdist-rings.cc @@ -83,14 +83,14 @@ void Rings::setRecordResponses(bool record) size_t Rings::numDistinctRequestors() { - std::set s; + std::set requestors; for (const auto& shard : d_shards) { - auto rl = shard->queryRing.lock(); - for (const auto& q : *rl) { - s.insert(q.requestor); + auto queries = shard->queryRing.lock(); + for (const auto& query : *queries) { + requestors.insert(query.requestor); } } - return s.size(); + return requestors.size(); } std::unordered_map>> Rings::getTopBandwidth(unsigned int numentries) @@ -99,44 +99,45 @@ std::unordered_map>> Rings::getTopBan uint64_t total = 0; for (const auto& shard : d_shards) { { - auto rl = shard->queryRing.lock(); - for (const auto& q : *rl) { - counts[q.requestor] += q.size; - total += q.size; + auto queries = shard->queryRing.lock(); + for (const auto& query : *queries) { + counts[query.requestor] += query.size; + total += query.size; } } { - auto rl = shard->respRing.lock(); - for (const auto& r : *rl) { - counts[r.requestor] += r.size; - total += r.size; + auto responses = shard->respRing.lock(); + for (const auto& response : *responses) { + counts[response.requestor] += response.size; + total += response.size; } } } - typedef vector> ret_t; + using ret_t = vector>; ret_t rcounts; rcounts.reserve(counts.size()); - for (const auto& p : counts) - rcounts.push_back({p.second, p.first}); + for (const auto& count : counts) { + rcounts.emplace_back(count.second, count.first); + } numentries = rcounts.size() < numentries ? rcounts.size() : numentries; - partial_sort(rcounts.begin(), rcounts.begin() + numentries, rcounts.end(), [](const ret_t::value_type& a, const ret_t::value_type& b) { - return (b.first < a.first); + partial_sort(rcounts.begin(), rcounts.begin() + numentries, rcounts.end(), [](const ret_t::value_type& lhs, const ret_t::value_type& rhs) { + return (rhs.first < lhs.first); }); std::unordered_map>> ret; uint64_t rest = 0; int count = 1; - for (const auto& rc : rcounts) { + for (const auto& rcount : rcounts) { if (count == static_cast(numentries + 1)) { - rest += rc.first; + rest += rcount.first; } else { - ret.insert({count++, {rc.second.toString(), rc.first, 100.0 * rc.first / total}}); + ret.insert({count++, {rcount.second.toString(), rcount.first, 100.0 * rcount.first / static_cast(total)}}); } } if (total > 0) { - ret.insert({count, {"Rest", rest, 100.0 * rest / total}}); + ret.insert({count, {"Rest", rest, 100.0 * static_cast(rest) / static_cast(total)}}); } else { ret.insert({count, {"Rest", rest, 100.0}}); @@ -154,8 +155,8 @@ size_t Rings::loadFromFile(const std::string& filepath, const struct timespec& n size_t inserted = 0; string line; - dnsheader dh; - memset(&dh, 0, sizeof(dh)); + dnsheader dnsHeader{}; + memset(&dnsHeader, 0, sizeof(dnsHeader)); while (std::getline(ifs, line)) { boost::trim_right_if(line, boost::is_any_of(" \r\n\x1a")); @@ -182,10 +183,10 @@ size_t Rings::loadFromFile(const std::string& filepath, const struct timespec& n continue; } - struct timespec when; + timespec when{}; try { when.tv_sec = now.tv_sec + std::stoi(timeStr.at(0)); - when.tv_nsec = now.tv_nsec + std::stoi(timeStr.at(1)) * 100 * 1000 * 1000; + when.tv_nsec = now.tv_nsec + static_cast(std::stoi(timeStr.at(1)) * 100 * 1000 * 1000); } catch (const std::exception& e) { cerr << "error parsing time " << parts.at(idx - 1) << " from line " << line << endl; @@ -193,10 +194,10 @@ size_t Rings::loadFromFile(const std::string& filepath, const struct timespec& n } ComboAddress from(parts.at(idx++)); - ComboAddress to; + ComboAddress dest; dnsdist::Protocol protocol(parts.at(idx++)); if (isResponse) { - to = ComboAddress(parts.at(idx++)); + dest = ComboAddress(parts.at(idx++)); } /* skip ID */ idx++; @@ -204,10 +205,10 @@ size_t Rings::loadFromFile(const std::string& filepath, const struct timespec& n QType qtype(QType::chartocode(parts.at(idx++).c_str())); if (isResponse) { - insertResponse(when, from, qname, qtype.getCode(), 0, 0, dh, to, protocol); + insertResponse(when, from, qname, qtype.getCode(), 0, 0, dnsHeader, dest, protocol); } else { - insertQuery(when, from, qname, qtype.getCode(), 0, dh, protocol); + insertQuery(when, from, qname, qtype.getCode(), 0, dnsHeader, protocol); } ++inserted; } From 69534a0995c4dfa0651f407a1229c1be70feaf0f Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Tue, 5 Mar 2024 10:46:27 +0100 Subject: [PATCH 16/25] dnsdist: Fix formatting in dnsdist-lua-bindings-dnsquestion.cc --- .../dnsdist-lua-bindings-dnsquestion.cc | 40 +++++++++++-------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc b/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc index 7eea39f0849e..6003f5c5e84b 100644 --- a/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc +++ b/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc @@ -42,18 +42,22 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) luaCtx.registerMember( "qclass", [](const DNSQuestion& dnsQuestion) -> uint16_t { return dnsQuestion.ids.qclass; }, [](DNSQuestion& dnsQuestion, uint16_t newClass) { (void)newClass; }); luaCtx.registerMember( - "rcode", [](const DNSQuestion& dnsQuestion) -> int { return static_cast(dnsQuestion.getHeader()->rcode); }, [](DNSQuestion& dnsQuestion, int newRCode) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [newRCode](dnsheader& header) { - header.rcode = static_cast(newRCode); - return true; - }); }); + "rcode", [](const DNSQuestion& dnsQuestion) -> int { return static_cast(dnsQuestion.getHeader()->rcode); }, [](DNSQuestion& dnsQuestion, int newRCode) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [newRCode](dnsheader& header) { + header.rcode = static_cast(newRCode); + return true; + }); + }); luaCtx.registerMember( "remoteaddr", [](const DNSQuestion& dnsQuestion) -> ComboAddress { return dnsQuestion.ids.origRemote; }, [](DNSQuestion& dnsQuestion, const ComboAddress newRemote) { (void)newRemote; }); /* DNSDist DNSQuestion */ luaCtx.registerMember( - "dh", [](const DNSQuestion& dnsQuestion) -> dnsheader* { return dnsQuestion.getMutableHeader(); }, [](DNSQuestion& dnsQuestion, const dnsheader* dnsHeader) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [&dnsHeader](dnsheader& header) { - header = *dnsHeader; - return true; - }); }); + "dh", [](const DNSQuestion& dnsQuestion) -> dnsheader* { return dnsQuestion.getMutableHeader(); }, [](DNSQuestion& dnsQuestion, const dnsheader* dnsHeader) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [&dnsHeader](dnsheader& header) { + header = *dnsHeader; + return true; + }); + }); luaCtx.registerMember( "len", [](const DNSQuestion& dnsQuestion) -> uint16_t { return dnsQuestion.getData().size(); }, [](DNSQuestion& dnsQuestion, uint16_t newlen) { dnsQuestion.getMutableData().resize(newlen); }); luaCtx.registerMember( @@ -372,17 +376,21 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) luaCtx.registerMember( "qclass", [](const DNSResponse& dnsQuestion) -> uint16_t { return dnsQuestion.ids.qclass; }, [](DNSResponse& dnsQuestion, uint16_t newClass) { (void)newClass; }); luaCtx.registerMember( - "rcode", [](const DNSResponse& dnsQuestion) -> int { return static_cast(dnsQuestion.getHeader()->rcode); }, [](DNSResponse& dnsQuestion, int newRCode) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [newRCode](dnsheader& header) { - header.rcode = static_cast(newRCode); - return true; - }); }); + "rcode", [](const DNSResponse& dnsQuestion) -> int { return static_cast(dnsQuestion.getHeader()->rcode); }, [](DNSResponse& dnsQuestion, int newRCode) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [newRCode](dnsheader& header) { + header.rcode = static_cast(newRCode); + return true; + }); + }); luaCtx.registerMember( "remoteaddr", [](const DNSResponse& dnsQuestion) -> ComboAddress { return dnsQuestion.ids.origRemote; }, [](DNSResponse& dnsQuestion, const ComboAddress newRemote) { (void)newRemote; }); luaCtx.registerMember( - "dh", [](const DNSResponse& dnsResponse) -> dnsheader* { return dnsResponse.getMutableHeader(); }, [](DNSResponse& dnsResponse, const dnsheader* dnsHeader) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsResponse.getMutableData(), [&dnsHeader](dnsheader& header) { - header = *dnsHeader; - return true; - }); }); + "dh", [](const DNSResponse& dnsResponse) -> dnsheader* { return dnsResponse.getMutableHeader(); }, [](DNSResponse& dnsResponse, const dnsheader* dnsHeader) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsResponse.getMutableData(), [&dnsHeader](dnsheader& header) { + header = *dnsHeader; + return true; + }); + }); luaCtx.registerMember( "len", [](const DNSResponse& dnsQuestion) -> uint16_t { return dnsQuestion.getData().size(); }, [](DNSResponse& dnsQuestion, uint16_t newlen) { dnsQuestion.getMutableData().resize(newlen); }); luaCtx.registerMember( From 2f587fe1e69392521874f72dc4d269f7e54a70ad Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Tue, 5 Mar 2024 10:47:49 +0100 Subject: [PATCH 17/25] dnsdist: Delint dnsdist-lua.cc and dnsdist-snmp.cc --- pdns/dnsdistdist/dnsdist-lua.cc | 351 ++++++++------- pdns/dnsdistdist/dnsdist-snmp.cc | 422 +++++++++--------- pdns/dnsdistdist/dnsdist.hh | 2 +- pdns/dnsdistdist/test-dnsdistlbpolicies_cc.cc | 2 +- 4 files changed, 406 insertions(+), 371 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-lua.cc b/pdns/dnsdistdist/dnsdist-lua.cc index 73a8567b241a..55075c8efcd5 100644 --- a/pdns/dnsdistdist/dnsdist-lua.cc +++ b/pdns/dnsdistdist/dnsdist-lua.cc @@ -90,8 +90,10 @@ static bool g_included{false}; has done so before on this invocation, this call won't be part of delta() output */ void setLuaNoSideEffect() { - if (g_noLuaSideEffect == false) // there has been a side effect already + if (g_noLuaSideEffect == false) { + // there has been a side effect already return; + } g_noLuaSideEffect = true; } @@ -103,6 +105,7 @@ void setLuaSideEffect() bool getLuaNoSideEffect() { if (g_noLuaSideEffect) { + // NOLINTNEXTLINE(readability-simplify-boolean-expr): it's a tribool, not a boolean return true; } return false; @@ -257,7 +260,7 @@ void checkParameterBound(const std::string& parameter, uint64_t value, size_t ma static void LuaThread(const std::string& code) { setThreadName("dnsdist/lua-bg"); - LuaContext l; + LuaContext context; // mask SIGTERM on threads so the signal always comes to dnsdist itself sigset_t blockSignals; @@ -269,7 +272,7 @@ static void LuaThread(const std::string& code) // submitToMainThread is camelcased, threadmessage is not. // This follows our tradition of hooks we call being lowercased but functions the user can call being camelcased. - l.writeFunction("submitToMainThread", [](std::string cmd, LuaAssociativeTable data) { + context.writeFunction("submitToMainThread", [](std::string cmd, LuaAssociativeTable data) { auto lua = g_lua.lock(); // maybe offer more than `void` auto func = lua->readVariable data)>>>("threadmessage"); @@ -285,7 +288,7 @@ static void LuaThread(const std::string& code) for (;;) { try { - l.executeCode(code); + context.executeCode(code); errlog("Lua thread exited, restarting in 5 seconds"); } catch (const std::exception& e) { @@ -294,7 +297,7 @@ static void LuaThread(const std::string& code) catch (...) { errlog("Lua thread crashed, restarting in 5 seconds"); } - sleep(5); + std::this_thread::sleep_for(std::chrono::seconds(5)); } } @@ -400,7 +403,56 @@ static void handleNewServerHealthCheckParameters(boost::optional& v getOptionalIntegerValue("newServer", vars, "rise", config.minRiseSuccesses); } -// NOLINTNEXTLINE(readability-function-cognitive-complexity): this function declares Lua bindings, even with a good refactoring it will likely blow up the threshold +static void handleNewServerSourceParameter(boost::optional& vars, DownstreamState::Config& config) +{ + std::string source; + if (getOptionalValue(vars, "source", source) > 0) { + /* handle source in the following forms: + - v4 address ("192.0.2.1") + - v6 address ("2001:DB8::1") + - interface name ("eth0") + - v4 address and interface name ("192.0.2.1@eth0") + - v6 address and interface name ("2001:DB8::1@eth0") + */ + bool parsed = false; + std::string::size_type pos = source.find('@'); + if (pos == std::string::npos) { + /* no '@', try to parse that as a valid v4/v6 address */ + try { + config.sourceAddr = ComboAddress(source); + parsed = true; + } + catch (...) { + } + } + + if (!parsed) { + /* try to parse as interface name, or v4/v6@itf */ + config.sourceItfName = source.substr(pos == std::string::npos ? 0 : pos + 1); + unsigned int itfIdx = if_nametoindex(config.sourceItfName.c_str()); + if (itfIdx != 0) { + if (pos == 0 || pos == std::string::npos) { + /* "eth0" or "@eth0" */ + config.sourceItf = itfIdx; + } + else { + /* "192.0.2.1@eth0" */ + config.sourceAddr = ComboAddress(source.substr(0, pos)); + config.sourceItf = itfIdx; + } +#ifdef SO_BINDTODEVICE + /* we need to retain CAP_NET_RAW to be able to set SO_BINDTODEVICE in the health checks */ + g_capabilitiesToRetain.insert("CAP_NET_RAW"); +#endif + } + else { + warnlog("Dismissing source %s because '%s' is not a valid interface name", source, config.sourceItfName); + } + } + } +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity,readability-function-size): this function declares Lua bindings, even with a good refactoring it will likely blow up the threshold static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) { luaCtx.writeFunction("inClientStartup", [client]() { @@ -419,7 +471,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) DownstreamState::Config config; std::string serverAddressStr; - if (auto addrStr = boost::get(&pvars)) { + if (auto* addrStr = boost::get(&pvars)) { serverAddressStr = *addrStr; if (qps) { (*vars)["qps"] = std::to_string(*qps); @@ -430,51 +482,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) getOptionalValue(vars, "address", serverAddressStr); } - std::string source; - if (getOptionalValue(vars, "source", source) > 0) { - /* handle source in the following forms: - - v4 address ("192.0.2.1") - - v6 address ("2001:DB8::1") - - interface name ("eth0") - - v4 address and interface name ("192.0.2.1@eth0") - - v6 address and interface name ("2001:DB8::1@eth0") - */ - bool parsed = false; - std::string::size_type pos = source.find("@"); - if (pos == std::string::npos) { - /* no '@', try to parse that as a valid v4/v6 address */ - try { - config.sourceAddr = ComboAddress(source); - parsed = true; - } - catch (...) { - } - } - - if (parsed == false) { - /* try to parse as interface name, or v4/v6@itf */ - config.sourceItfName = source.substr(pos == std::string::npos ? 0 : pos + 1); - unsigned int itfIdx = if_nametoindex(config.sourceItfName.c_str()); - if (itfIdx != 0) { - if (pos == 0 || pos == std::string::npos) { - /* "eth0" or "@eth0" */ - config.sourceItf = itfIdx; - } - else { - /* "192.0.2.1@eth0" */ - config.sourceAddr = ComboAddress(source.substr(0, pos)); - config.sourceItf = itfIdx; - } -#ifdef SO_BINDTODEVICE - /* we need to retain CAP_NET_RAW to be able to set SO_BINDTODEVICE in the health checks */ - g_capabilitiesToRetain.insert("CAP_NET_RAW"); -#endif - } - else { - warnlog("Dismissing source %s because '%s' is not a valid interface name", source, config.sourceItfName); - } - } - } + handleNewServerSourceParameter(vars, config); std::string valueStr; if (getOptionalValue(vars, "sockets", valueStr) > 0) { @@ -551,11 +559,11 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) if (getOptionalValue(vars, "subjectAddr", valueStr) > 0) { try { - ComboAddress ca(valueStr); - config.d_tlsSubjectName = ca.toString(); + ComboAddress addr(valueStr); + config.d_tlsSubjectName = addr.toString(); config.d_tlsSubjectIsAddr = true; } - catch (const std::exception& e) { + catch (const std::exception&) { errlog("Error creating new server: downstream subjectAddr value must be a valid IP address"); return std::shared_ptr(); } @@ -605,8 +613,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) config.pools.insert(valueStr); } else if (getOptionalValue(vars, "pool", pools) > 0) { - for (auto& p : pools) { - config.pools.insert(p.second); + for (auto& pool : pools) { + config.pools.insert(pool.second); } } @@ -653,7 +661,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) ret->registerXsk(xskSockets); std::string mac; if (getOptionalValue(vars, "MACAddr", mac) > 0) { - auto* addr = &ret->d_config.destMACAddr[0]; + auto* addr = ret->d_config.destMACAddr.data(); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) sscanf(mac.c_str(), "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", addr, addr + 1, addr + 2, addr + 3, addr + 4, addr + 5); } else { @@ -703,8 +712,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) auto states = g_dstates.getCopy(); states.push_back(ret); - std::stable_sort(states.begin(), states.end(), [](const decltype(ret)& a, const decltype(ret)& b) { - return a->d_config.order < b->d_config.order; + std::stable_sort(states.begin(), states.end(), [](const decltype(ret)& lhs, const decltype(ret)& rhs) { + return lhs->d_config.order < rhs->d_config.order; }); g_dstates.setState(states); checkAllParametersConsumed("newServer", vars); @@ -719,7 +728,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) if (auto* rem = boost::get>(&var)) { server = *rem; } - else if (auto str = boost::get(&var)) { + else if (auto* str = boost::get(&var)) { const auto uuid = getUniqueID(*str); for (auto& state : states) { if (*state->d_config.id == uuid) { @@ -746,8 +755,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) server->stop(); }); - luaCtx.writeFunction("truncateTC", [](bool tc) { setLuaSideEffect(); g_truncateTC=tc; }); - luaCtx.writeFunction("fixupCase", [](bool fu) { setLuaSideEffect(); g_fixupCase=fu; }); + luaCtx.writeFunction("truncateTC", [](bool value) { setLuaSideEffect(); g_truncateTC = value; }); + luaCtx.writeFunction("fixupCase", [](bool value) { setLuaSideEffect(); g_fixupCase = value; }); luaCtx.writeFunction("addACL", [](const std::string& domain) { setLuaSideEffect(); @@ -828,8 +837,9 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) luaCtx.writeFunction("addLocal", [client](const std::string& addr, boost::optional vars) { setLuaSideEffect(); - if (client) + if (client) { return; + } if (!checkConfigurationTime("addLocal")) { return; @@ -884,13 +894,14 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) luaCtx.writeFunction("setACL", [](LuaTypeOrArrayOf inp) { setLuaSideEffect(); NetmaskGroup nmg; - if (auto str = boost::get(&inp)) { + if (auto* str = boost::get(&inp)) { nmg.addMask(*str); } - else - for (const auto& p : boost::get>(inp)) { - nmg.addMask(p.second); + else { + for (const auto& entry : boost::get>(inp)) { + nmg.addMask(entry.second); } + } g_ACL.setState(nmg); }); @@ -903,15 +914,17 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) throw std::runtime_error("Could not open '" + file + "': " + stringerror()); } - string::size_type pos; + string::size_type pos = 0; string line; while (getline(ifs, line)) { pos = line.find('#'); - if (pos != string::npos) + if (pos != string::npos) { line.resize(pos); + } boost::trim(line); - if (line.empty()) + if (line.empty()) { continue; + } nmg.addMask(line); } @@ -968,29 +981,31 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) ret << (fmt % "#" % "Name" % "Address" % "State" % "Qps" % "Qlim" % "Ord" % "Wt" % "Queries" % "Drops" % "Drate" % "Lat" % "Outstanding" % "Pools" % "TCP") << endl; } - uint64_t totQPS{0}, totQueries{0}, totDrops{0}; + uint64_t totQPS{0}; + uint64_t totQueries{0}; + uint64_t totDrops{0}; int counter = 0; auto states = g_dstates.getLocal(); - for (const auto& s : *states) { - string status = s->getStatus(); + for (const auto& backend : *states) { + string status = backend->getStatus(); string pools; - for (const auto& p : s->d_config.pools) { + for (const auto& pool : backend->d_config.pools) { if (!pools.empty()) { pools += " "; } - pools += p; + pools += pool; } - const std::string latency = (s->latencyUsec == 0.0 ? "-" : boost::str(latFmt % (s->latencyUsec / 1000.0))); - const std::string latencytcp = (s->latencyUsecTCP == 0.0 ? "-" : boost::str(latFmt % (s->latencyUsecTCP / 1000.0))); + const std::string latency = (backend->latencyUsec == 0.0 ? "-" : boost::str(latFmt % (backend->latencyUsec / 1000.0))); + const std::string latencytcp = (backend->latencyUsecTCP == 0.0 ? "-" : boost::str(latFmt % (backend->latencyUsecTCP / 1000.0))); if (showUUIDs) { - ret << (fmt % counter % s->getName() % s->d_config.remote.toStringWithPort() % status % s->queryLoad % s->qps.getRate() % s->d_config.order % s->d_config.d_weight % s->queries.load() % s->reuseds.load() % (s->dropRate) % latency % s->outstanding.load() % pools % *s->d_config.id % latencytcp) << endl; + ret << (fmt % counter % backend->getName() % backend->d_config.remote.toStringWithPort() % status % backend->queryLoad % backend->qps.getRate() % backend->d_config.order % backend->d_config.d_weight % backend->queries.load() % backend->reuseds.load() % (backend->dropRate) % latency % backend->outstanding.load() % pools % *backend->d_config.id % latencytcp) << endl; } else { - ret << (fmt % counter % s->getName() % s->d_config.remote.toStringWithPort() % status % s->queryLoad % s->qps.getRate() % s->d_config.order % s->d_config.d_weight % s->queries.load() % s->reuseds.load() % (s->dropRate) % latency % s->outstanding.load() % pools % latencytcp) << endl; + ret << (fmt % counter % backend->getName() % backend->d_config.remote.toStringWithPort() % status % backend->queryLoad % backend->qps.getRate() % backend->d_config.order % backend->d_config.d_weight % backend->queries.load() % backend->reuseds.load() % (backend->dropRate) % latency % backend->outstanding.load() % pools % latencytcp) << endl; } - totQPS += s->queryLoad; - totQueries += s->queries.load(); - totDrops += s->reuseds.load(); + totQPS += static_cast(backend->queryLoad); + totQueries += backend->queries.load(); + totDrops += backend->reuseds.load(); ++counter; } if (showUUIDs) { @@ -1016,8 +1031,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) setLuaNoSideEffect(); LuaArray> ret; int count = 1; - for (const auto& s : g_dstates.getCopy()) { - ret.emplace_back(count++, s); + for (const auto& backend : g_dstates.getCopy()) { + ret.emplace_back(count++, backend); } return ret; }); @@ -1027,12 +1042,12 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) return *poolServers; }); - luaCtx.writeFunction("getServer", [client](boost::variant i) { + luaCtx.writeFunction("getServer", [client](boost::variant identifier) { if (client) { return std::make_shared(ComboAddress()); } auto states = g_dstates.getCopy(); - if (auto str = boost::get(&i)) { + if (auto* str = boost::get(&identifier)) { const auto uuid = getUniqueID(*str); for (auto& state : states) { if (*state->d_config.id == uuid) { @@ -1040,7 +1055,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) } } } - else if (auto pos = boost::get(&i)) { + else if (auto* pos = boost::get(&identifier)) { return states.at(*pos); } @@ -1080,8 +1095,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) SBind(sock, local); SListen(sock, 5); auto launch = [sock, local]() { - thread t(dnsdistWebserverThread, sock, local); - t.detach(); + thread thr(dnsdistWebserverThread, sock, local); + thr.detach(); }; if (g_launchWork) { g_launchWork->push_back(launch); @@ -1226,13 +1241,14 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) #endif NetmaskGroup nmg; - if (auto str = boost::get(&inp)) { + if (auto* str = boost::get(&inp)) { nmg.addMask(*str); } - else - for (const auto& p : boost::get>(inp)) { - nmg.addMask(p.second); + else { + for (const auto& entry : boost::get>(inp)) { + nmg.addMask(entry.second); } + } g_consoleACL.setState(nmg); }); @@ -1307,8 +1323,9 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) g_outputBuffer = string("Unable to decode ") + key + " as Base64"; errlog("%s", g_outputBuffer); } - else + else { g_consoleKey = std::move(newkey); + } }); luaCtx.writeFunction("clearConsoleHistory", []() { @@ -1457,7 +1474,14 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) g_cacheCleaningDelay = delay; }); - luaCtx.writeFunction("setCacheCleaningPercentage", [](uint64_t percentage) { if (percentage < 100) g_cacheCleaningPercentage = percentage; else g_cacheCleaningPercentage = 100; }); + luaCtx.writeFunction("setCacheCleaningPercentage", [](uint64_t percentage) { + if (percentage < 100) { + g_cacheCleaningPercentage = percentage; + } + else { + g_cacheCleaningPercentage = 100; + } + }); luaCtx.writeFunction("setECSSourcePrefixV4", [](uint64_t prefix) { checkParameterBound("setECSSourcePrefixV4", prefix, std::numeric_limits::max()); @@ -1475,25 +1499,26 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) luaCtx.writeFunction("showDynBlocks", []() { setLuaNoSideEffect(); auto slow = g_dynblockNMG.getCopy(); - struct timespec now; + timespec now{}; gettime(&now); boost::format fmt("%-24s %8d %8d %-10s %-20s %-10s %s\n"); g_outputBuffer = (fmt % "What" % "Seconds" % "Blocks" % "Warning" % "Action" % "eBPF" % "Reason").str(); - for (const auto& e : slow) { - if (now < e.second.until) { - uint64_t counter = e.second.blocks; - if (g_defaultBPFFilter && e.second.bpf) { - counter += g_defaultBPFFilter->getHits(e.first.getNetwork()); + for (const auto& entry : slow) { + if (now < entry.second.until) { + uint64_t counter = entry.second.blocks; + if (g_defaultBPFFilter && entry.second.bpf) { + counter += g_defaultBPFFilter->getHits(entry.first.getNetwork()); } - g_outputBuffer += (fmt % e.first.toString() % (e.second.until.tv_sec - now.tv_sec) % counter % (e.second.warning ? "true" : "false") % DNSAction::typeToString(e.second.action != DNSAction::Action::None ? e.second.action : g_dynBlockAction) % (g_defaultBPFFilter && e.second.bpf ? "*" : "") % e.second.reason).str(); + g_outputBuffer += (fmt % entry.first.toString() % (entry.second.until.tv_sec - now.tv_sec) % counter % (entry.second.warning ? "true" : "false") % DNSAction::typeToString(entry.second.action != DNSAction::Action::None ? entry.second.action : g_dynBlockAction) % (g_defaultBPFFilter && entry.second.bpf ? "*" : "") % entry.second.reason).str(); } } auto slow2 = g_dynblockSMT.getCopy(); slow2.visit([&now, &fmt](const SuffixMatchTree& node) { if (now < node.d_value.until) { string dom("empty"); - if (!node.d_value.domain.empty()) + if (!node.d_value.domain.empty()) { dom = node.d_value.domain.toString(); + } g_outputBuffer += (fmt % dom % (node.d_value.until.tv_sec - now.tv_sec) % node.d_value.blocks % (node.d_value.warning ? "true" : "false") % DNSAction::typeToString(node.d_value.action != DNSAction::Action::None ? node.d_value.action : g_dynBlockAction) % "" % node.d_value.reason).str(); } }); @@ -1501,9 +1526,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) luaCtx.writeFunction("getDynamicBlocks", []() { setLuaNoSideEffect(); - struct timespec now - { - }; + timespec now{}; gettime(&now); LuaAssociativeTable entries; @@ -1527,9 +1550,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) luaCtx.writeFunction("getDynamicBlocksSMT", []() { setLuaNoSideEffect(); - struct timespec now - { - }; + timespec now{}; gettime(&now); LuaAssociativeTable entries; @@ -1561,24 +1582,24 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) #ifndef DISABLE_DEPRECATED_DYNBLOCK luaCtx.writeFunction("addDynBlocks", - [](const std::unordered_map& m, const std::string& msg, boost::optional seconds, boost::optional action) { - if (m.empty()) { + [](const std::unordered_map& addrs, const std::string& msg, boost::optional seconds, boost::optional action) { + if (addrs.empty()) { return; } setLuaSideEffect(); auto slow = g_dynblockNMG.getCopy(); - struct timespec until, now; + timespec now{}; gettime(&now); - until = now; + timespec until{now}; int actualSeconds = seconds ? *seconds : 10; until.tv_sec += actualSeconds; - for (const auto& capair : m) { + for (const auto& capair : addrs) { unsigned int count = 0; /* this legacy interface does not support ranges or ports, use DynBlockRulesGroup instead */ AddressAndPortRange requestor(capair.first, capair.first.isIPv4() ? 32 : 128, 0); - auto got = slow.lookup(requestor); + auto* got = slow.lookup(requestor); bool expired = false; - if (got) { + if (got != nullptr) { if (until < got->second.until) { // had a longer policy continue; @@ -1591,12 +1612,12 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) expired = true; } } - DynBlock db{msg, until, DNSName(), (action ? *action : DNSAction::Action::None)}; - db.blocks = count; - if (!got || expired) { + DynBlock dblock{msg, until, DNSName(), (action ? *action : DNSAction::Action::None)}; + dblock.blocks = count; + if (got == nullptr || expired) { warnlog("Inserting dynamic block for %s for %d seconds: %s", capair.first.toString(), actualSeconds, msg); } - slow.insert(requestor).second = std::move(db); + slow.insert(requestor).second = std::move(dblock); } g_dynblockNMG.setState(slow); }); @@ -1621,9 +1642,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) return; } setLuaSideEffect(); - struct timespec now - { - }; + timespec now{}; gettime(&now); unsigned int actualSeconds = seconds ? *seconds : 10; @@ -1668,9 +1687,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) AddressAndPortRange target(clientIPCA, clientIPMask ? *clientIPMask : (clientIPCA.isIPv4() ? 32 : 128), clientIPPortMask ? *clientIPPortMask : 0); unsigned int actualSeconds = seconds ? *seconds : 10; - struct timespec now - { - }; + timespec now{}; gettime(&now); auto slow = g_dynblockNMG.getCopy(); if (dnsdist::DynamicBlocks::addOrRefreshBlock(slow, now, target, msg, actualSeconds, action ? *action : DNSAction::Action::None, false, false)) { @@ -1679,7 +1696,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) }); luaCtx.writeFunction("setDynBlocksPurgeInterval", [](uint64_t interval) { - DynBlockMaintenance::s_expiredDynBlocksPurgeInterval = interval; + DynBlockMaintenance::s_expiredDynBlocksPurgeInterval = static_cast(interval); }); #endif /* DISABLE_DYNBLOCKS */ @@ -1970,11 +1987,11 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) } }); - luaCtx.writeFunction("unregisterDynBPFFilter", [](std::shared_ptr dbpf) { + luaCtx.writeFunction("unregisterDynBPFFilter", [](const std::shared_ptr& dbpf) { if (dbpf) { - for (auto it = g_dynBPFFilters.begin(); it != g_dynBPFFilters.end(); it++) { - if (*it == dbpf) { - g_dynBPFFilters.erase(it); + for (auto filterIt = g_dynBPFFilters.begin(); filterIt != g_dynBPFFilters.end(); filterIt++) { + if (*filterIt == dbpf) { + g_dynBPFFilters.erase(filterIt); break; } } @@ -1983,17 +2000,17 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) #ifndef DISABLE_DYNBLOCKS #ifndef DISABLE_DEPRECATED_DYNBLOCK - luaCtx.writeFunction("addBPFFilterDynBlocks", [](const std::unordered_map& m, std::shared_ptr dynbpf, boost::optional seconds, boost::optional msg) { + luaCtx.writeFunction("addBPFFilterDynBlocks", [](const std::unordered_map& addrs, const std::shared_ptr& dynbpf, boost::optional seconds, boost::optional msg) { if (!dynbpf) { return; } setLuaSideEffect(); - struct timespec until, now; + timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now); - until = now; + timespec until{now}; int actualSeconds = seconds ? *seconds : 10; until.tv_sec += actualSeconds; - for (const auto& capair : m) { + for (const auto& capair : addrs) { if (dynbpf->block(capair.first, until)) { warnlog("Inserting eBPF dynamic block for %s for %d seconds: %s", capair.first.toString(), actualSeconds, msg ? *msg : ""); } @@ -2029,14 +2046,16 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) return; } - struct stat st; - if (stat(dirname.c_str(), &st)) { + struct stat dirStat + { + }; + if (stat(dirname.c_str(), &dirStat) != 0) { errlog("The included directory %s does not exist!", dirname.c_str()); g_outputBuffer = "The included directory " + dirname + " does not exist!"; return; } - if (!S_ISDIR(st.st_mode)) { + if (!S_ISDIR(dirStat.st_mode)) { errlog("The included directory %s is not a directory!", dirname.c_str()); g_outputBuffer = "The included directory " + dirname + " is not a directory!"; return; @@ -2187,15 +2206,16 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) luaCtx.writeFunction("setTCPInternalPipeBufferSize", [](uint64_t size) { g_tcpInternalPipeBufferSize = size; }); luaCtx.writeFunction("setTCPFastOpenKey", [](const std::string& keyString) { setLuaSideEffect(); - uint32_t key[4] = {}; + std::array key{}; + // NOLINTNEXTLINE(readability-container-data-pointer) auto ret = sscanf(keyString.c_str(), "%" SCNx32 "-%" SCNx32 "-%" SCNx32 "-%" SCNx32, &key[0], &key[1], &key[2], &key[3]); if (ret != 4) { g_outputBuffer = "Invalid value passed to setTCPFastOpenKey()!\n"; return; } extern vector g_TCPFastOpenKey; - for (const auto i : key) { - g_TCPFastOpenKey.push_back(i); + for (const auto byte : key) { + g_TCPFastOpenKey.push_back(byte); } }); @@ -2215,11 +2235,11 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) g_snmpEnabled = true; g_snmpTrapsEnabled = enableTraps; - g_snmpAgent = new DNSDistSNMPAgent("dnsdist", daemonSocket ? *daemonSocket : std::string()); + g_snmpAgent = std::make_unique("dnsdist", daemonSocket ? *daemonSocket : std::string()); }); luaCtx.writeFunction("sendCustomTrap", [](const std::string& str) { - if (g_snmpAgent && g_snmpTrapsEnabled) { + if (g_snmpAgent != nullptr && g_snmpTrapsEnabled) { g_snmpAgent->sendCustomTrap(str); } }); @@ -2233,12 +2253,12 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) luaCtx.writeFunction("setServerPolicyLua", [](const string& name, ServerPolicy::policyfunc_t policy) { setLuaSideEffect(); - g_policy.setState(ServerPolicy{name, policy, true}); + g_policy.setState(ServerPolicy{name, std::move(policy), true}); }); luaCtx.writeFunction("setServerPolicyLuaFFI", [](const string& name, ServerPolicy::ffipolicyfunc_t policy) { setLuaSideEffect(); - auto pol = ServerPolicy(name, policy); + auto pol = ServerPolicy(name, std::move(policy)); g_policy.setState(std::move(pol)); }); @@ -2337,12 +2357,12 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) } setLuaSideEffect(); NetmaskGroup nmg; - if (auto str = boost::get(&inp)) { + if (auto* str = boost::get(&inp)) { nmg.addMask(*str); } else { - for (const auto& p : boost::get>(inp)) { - nmg.addMask(p.second); + for (const auto& entry : boost::get>(inp)) { + nmg.addMask(entry.second); } } g_proxyProtocolACL = std::move(nmg); @@ -2471,12 +2491,12 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) {"log_ftp", LOG_FTP}}; auto facilityStr = boost::get(facility); toLowerInPlace(facilityStr); - auto it = facilities.find(facilityStr); - if (it == facilities.end()) { + auto facilityIt = facilities.find(facilityStr); + if (facilityIt == facilities.end()) { g_outputBuffer = "Unknown facility '" + facilityStr + "' passed to setSyslogFacility()!\n"; return; } - setSyslogFacility(it->second); + setSyslogFacility(facilityIt->second); } else { setSyslogFacility(boost::get(facility)); @@ -2490,12 +2510,13 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) return result; } #if defined(HAVE_DNS_OVER_TLS) || defined(HAVE_DNS_OVER_HTTPS) - std::optional key, password; + std::optional key; + std::optional password; if (opts) { - if (opts->count("key")) { + if (opts->count("key") != 0) { key = boost::get((*opts)["key"]); } - if (opts->count("password")) { + if (opts->count("password") != 0) { password = boost::get((*opts)["password"]); } } @@ -2563,8 +2584,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) } else if (urls->type() == typeid(LuaArray)) { auto urlsVect = boost::get>(*urls); - for (const auto& p : urlsVect) { - frontend->d_urls.insert(p.second); + for (const auto& url : urlsVect) { + frontend->d_urls.insert(url.second); } } } @@ -3029,7 +3050,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) } }); - luaCtx.registerFunction::*)(boost::variant, LuaArray, LuaArray>> certFiles, boost::variant> keyFiles)>("loadNewCertificatesAndKeys", [](std::shared_ptr frontend, boost::variant, LuaArray, LuaArray>> certFiles, boost::variant> keyFiles) { + luaCtx.registerFunction::*)(boost::variant, LuaArray, LuaArray>> certFiles, boost::variant> keyFiles)>("loadNewCertificatesAndKeys", [](const std::shared_ptr& frontend, const boost::variant, LuaArray, LuaArray>>& certFiles, const boost::variant>& keyFiles) { #ifdef HAVE_DNS_OVER_HTTPS if (frontend != nullptr) { if (loadTLSCertificateAndKeys("DOHFrontend::loadNewCertificatesAndKeys", frontend->d_tlsContext.d_tlsConfig.d_certKeyPairs, certFiles, keyFiles)) { @@ -3039,19 +3060,19 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) #endif }); - luaCtx.registerFunction::*)()>("rotateTicketsKey", [](std::shared_ptr frontend) { + luaCtx.registerFunction::*)()>("rotateTicketsKey", [](const std::shared_ptr& frontend) { if (frontend != nullptr) { frontend->rotateTicketsKey(time(nullptr)); } }); - luaCtx.registerFunction::*)(const std::string&)>("loadTicketsKeys", [](std::shared_ptr frontend, const std::string& file) { + luaCtx.registerFunction::*)(const std::string&)>("loadTicketsKeys", [](const std::shared_ptr& frontend, const std::string& file) { if (frontend != nullptr) { frontend->loadTicketsKeys(file); } }); - luaCtx.registerFunction::*)(const LuaArray>&)>("setResponsesMap", [](std::shared_ptr frontend, const LuaArray>& map) { + luaCtx.registerFunction::*)(const LuaArray>&)>("setResponsesMap", [](const std::shared_ptr& frontend, const LuaArray>& map) { if (frontend != nullptr) { auto newMap = std::make_shared>>(); newMap->reserve(map.size()); @@ -3064,7 +3085,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) } }); - luaCtx.writeFunction("addTLSLocal", [client](const std::string& addr, boost::variant, LuaArray, LuaArray>> certFiles, LuaTypeOrArrayOf keyFiles, boost::optional vars) { + luaCtx.writeFunction("addTLSLocal", [client](const std::string& addr, const boost::variant, LuaArray, LuaArray>>& certFiles, const LuaTypeOrArrayOf& keyFiles, boost::optional vars) { if (client) { return; } @@ -3288,7 +3309,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck) frontend->setupTLS(); }); - luaCtx.registerFunction::*)(boost::variant, LuaArray, LuaArray>> certFiles, LuaTypeOrArrayOf keyFiles)>("loadNewCertificatesAndKeys", [](std::shared_ptr& frontend, boost::variant, LuaArray, LuaArray>> certFiles, LuaTypeOrArrayOf keyFiles) { + luaCtx.registerFunction::*)(const boost::variant, LuaArray, LuaArray>>&, const LuaTypeOrArrayOf&)>("loadNewCertificatesAndKeys", [](std::shared_ptr& frontend, const boost::variant, LuaArray, LuaArray>>& certFiles, const LuaTypeOrArrayOf& keyFiles) { #ifdef HAVE_DNS_OVER_TLS if (loadTLSCertificateAndKeys("TLSFrontend::loadNewCertificatesAndKeys", frontend->d_tlsConfig.d_certKeyPairs, certFiles, keyFiles)) { frontend->setupTLS(); @@ -3501,9 +3522,7 @@ vector> setupLua(LuaContext& luaCtx, bool client, bool if (configCheck) { throw std::runtime_error("Unable to read configuration file from " + config); } - else { - warnlog("Unable to read configuration from '%s'", config); - } + warnlog("Unable to read configuration from '%s'", config); } else { vinfolog("Read configuration from '%s'", config); diff --git a/pdns/dnsdistdist/dnsdist-snmp.cc b/pdns/dnsdistdist/dnsdist-snmp.cc index 6081d11f9ec5..34e9c7cdd385 100644 --- a/pdns/dnsdistdist/dnsdist-snmp.cc +++ b/pdns/dnsdistdist/dnsdist-snmp.cc @@ -5,7 +5,7 @@ bool g_snmpEnabled{false}; bool g_snmpTrapsEnabled{false}; -DNSDistSNMPAgent* g_snmpAgent{nullptr}; +std::unique_ptr g_snmpAgent{nullptr}; #ifdef HAVE_NET_SNMP @@ -15,46 +15,51 @@ DNSDistSNMPAgent* g_snmpAgent{nullptr}; #define DNSDIST_TRAPS_OID DNSDIST_OID, 10, 0 #define DNSDIST_TRAP_OBJECTS_OID DNSDIST_OID, 11 -static const oid queriesOID[] = {DNSDIST_STATS_OID, 1}; -static const oid responsesOID[] = {DNSDIST_STATS_OID, 2}; -static const oid servfailResponsesOID[] = {DNSDIST_STATS_OID, 3}; -static const oid aclDropsOID[] = {DNSDIST_STATS_OID, 4}; +using OIDStat = std::array; +using OIDTrap = std::array; +using OIDTrapObject = std::array; +using OIDStatTable = std::array; + +static const OIDStat queriesOID{DNSDIST_STATS_OID, 1}; +static const OIDStat responsesOID{DNSDIST_STATS_OID, 2}; +static const OIDStat servfailResponsesOID{DNSDIST_STATS_OID, 3}; +static const OIDStat aclDropsOID{DNSDIST_STATS_OID, 4}; // 5 was BlockFilter, removed in 1.2.0 -static const oid ruleDropOID[] = {DNSDIST_STATS_OID, 6}; -static const oid ruleNXDomainOID[] = {DNSDIST_STATS_OID, 7}; -static const oid ruleRefusedOID[] = {DNSDIST_STATS_OID, 8}; -static const oid selfAnsweredOID[] = {DNSDIST_STATS_OID, 9}; -static const oid downstreamTimeoutsOID[] = {DNSDIST_STATS_OID, 10}; -static const oid downstreamSendErrorsOID[] = {DNSDIST_STATS_OID, 11}; -static const oid truncFailOID[] = {DNSDIST_STATS_OID, 12}; -static const oid noPolicyOID[] = {DNSDIST_STATS_OID, 13}; -static const oid latency0_1OID[] = {DNSDIST_STATS_OID, 14}; -static const oid latency1_10OID[] = {DNSDIST_STATS_OID, 15}; -static const oid latency10_50OID[] = {DNSDIST_STATS_OID, 16}; -static const oid latency50_100OID[] = {DNSDIST_STATS_OID, 17}; -static const oid latency100_1000OID[] = {DNSDIST_STATS_OID, 18}; -static const oid latencySlowOID[] = {DNSDIST_STATS_OID, 19}; -static const oid latencyAvg100OID[] = {DNSDIST_STATS_OID, 20}; -static const oid latencyAvg1000OID[] = {DNSDIST_STATS_OID, 21}; -static const oid latencyAvg10000OID[] = {DNSDIST_STATS_OID, 22}; -static const oid latencyAvg1000000OID[] = {DNSDIST_STATS_OID, 23}; -static const oid uptimeOID[] = {DNSDIST_STATS_OID, 24}; -static const oid realMemoryUsageOID[] = {DNSDIST_STATS_OID, 25}; -static const oid nonCompliantQueriesOID[] = {DNSDIST_STATS_OID, 26}; -static const oid nonCompliantResponsesOID[] = {DNSDIST_STATS_OID, 27}; -static const oid rdQueriesOID[] = {DNSDIST_STATS_OID, 28}; -static const oid emptyQueriesOID[] = {DNSDIST_STATS_OID, 29}; -static const oid cacheHitsOID[] = {DNSDIST_STATS_OID, 30}; -static const oid cacheMissesOID[] = {DNSDIST_STATS_OID, 31}; -static const oid cpuUserMSecOID[] = {DNSDIST_STATS_OID, 32}; -static const oid cpuSysMSecOID[] = {DNSDIST_STATS_OID, 33}; -static const oid fdUsageOID[] = {DNSDIST_STATS_OID, 34}; -static const oid dynBlockedOID[] = {DNSDIST_STATS_OID, 35}; -static const oid dynBlockedNMGSizeOID[] = {DNSDIST_STATS_OID, 36}; -static const oid ruleServFailOID[] = {DNSDIST_STATS_OID, 37}; -static const oid securityStatusOID[] = {DNSDIST_STATS_OID, 38}; -static const oid specialMemoryUsageOID[] = {DNSDIST_STATS_OID, 39}; -static const oid ruleTruncatedOID[] = {DNSDIST_STATS_OID, 40}; +static const OIDStat ruleDropOID{DNSDIST_STATS_OID, 6}; +static const OIDStat ruleNXDomainOID{DNSDIST_STATS_OID, 7}; +static const OIDStat ruleRefusedOID{DNSDIST_STATS_OID, 8}; +static const OIDStat selfAnsweredOID{DNSDIST_STATS_OID, 9}; +static const OIDStat downstreamTimeoutsOID{DNSDIST_STATS_OID, 10}; +static const OIDStat downstreamSendErrorsOID{DNSDIST_STATS_OID, 11}; +static const OIDStat truncFailOID{DNSDIST_STATS_OID, 12}; +static const OIDStat noPolicyOID{DNSDIST_STATS_OID, 13}; +static const OIDStat latency0_1OID{DNSDIST_STATS_OID, 14}; +static const OIDStat latency1_10OID{DNSDIST_STATS_OID, 15}; +static const OIDStat latency10_50OID{DNSDIST_STATS_OID, 16}; +static const OIDStat latency50_100OID{DNSDIST_STATS_OID, 17}; +static const OIDStat latency100_1000OID{DNSDIST_STATS_OID, 18}; +static const OIDStat latencySlowOID{DNSDIST_STATS_OID, 19}; +static const OIDStat latencyAvg100OID{DNSDIST_STATS_OID, 20}; +static const OIDStat latencyAvg1000OID{DNSDIST_STATS_OID, 21}; +static const OIDStat latencyAvg10000OID{DNSDIST_STATS_OID, 22}; +static const OIDStat latencyAvg1000000OID{DNSDIST_STATS_OID, 23}; +static const OIDStat uptimeOID{DNSDIST_STATS_OID, 24}; +static const OIDStat realMemoryUsageOID{DNSDIST_STATS_OID, 25}; +static const OIDStat nonCompliantQueriesOID{DNSDIST_STATS_OID, 26}; +static const OIDStat nonCompliantResponsesOID{DNSDIST_STATS_OID, 27}; +static const OIDStat rdQueriesOID{DNSDIST_STATS_OID, 28}; +static const OIDStat emptyQueriesOID{DNSDIST_STATS_OID, 29}; +static const OIDStat cacheHitsOID{DNSDIST_STATS_OID, 30}; +static const OIDStat cacheMissesOID{DNSDIST_STATS_OID, 31}; +static const OIDStat cpuUserMSecOID{DNSDIST_STATS_OID, 32}; +static const OIDStat cpuSysMSecOID{DNSDIST_STATS_OID, 33}; +static const OIDStat fdUsageOID{DNSDIST_STATS_OID, 34}; +static const OIDStat dynBlockedOID{DNSDIST_STATS_OID, 35}; +static const OIDStat dynBlockedNMGSizeOID{DNSDIST_STATS_OID, 36}; +static const OIDStat ruleServFailOID{DNSDIST_STATS_OID, 37}; +static const OIDStat securityStatusOID{DNSDIST_STATS_OID, 38}; +static const OIDStat specialMemoryUsageOID{DNSDIST_STATS_OID, 39}; +static const OIDStat ruleTruncatedOID{DNSDIST_STATS_OID, 40}; static std::unordered_map s_statsMap; @@ -76,35 +81,36 @@ static int handleCounter64Stats(netsnmp_mib_handler* handler, return SNMP_ERR_GENERR; } - const auto& it = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]); - if (it == s_statsMap.end()) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): net-snmp API + const auto& stIt = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]); + if (stIt == s_statsMap.end()) { return SNMP_ERR_GENERR; } - if (const auto& val = std::get_if(&it->second)) { + if (const auto& val = std::get_if(&stIt->second)) { return DNSDistSNMPAgent::setCounter64Value(requests, (*val)->load()); } return SNMP_ERR_GENERR; } -static void registerCounter64Stat(const char* name, const oid statOID[], size_t statOIDLength, pdns::stat_t* ptr) +static void registerCounter64Stat(const char* name, const OIDStat& statOID, pdns::stat_t* ptr) { - if (statOIDLength != OID_LENGTH(queriesOID)) { + if (statOID.size() != OID_LENGTH(queriesOID)) { errlog("Invalid OID for SNMP Counter64 statistic %s", name); return; } - if (s_statsMap.find(statOID[statOIDLength - 1]) != s_statsMap.end()) { + if (s_statsMap.find(statOID.at(statOID.size() - 1)) != s_statsMap.end()) { errlog("OID for SNMP Counter64 statistic %s has already been registered", name); return; } - s_statsMap[statOID[statOIDLength - 1]] = ptr; + s_statsMap[statOID.at(statOID.size() - 1)] = ptr; netsnmp_register_scalar(netsnmp_create_handler_registration(name, handleCounter64Stats, - statOID, - statOIDLength, + statOID.data(), + statOID.size(), HANDLER_CAN_RONLY)); } @@ -121,12 +127,13 @@ static int handleFloatStats(netsnmp_mib_handler* handler, return SNMP_ERR_GENERR; } - const auto& it = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]); - if (it == s_statsMap.end()) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): net-snmp API + const auto& stIt = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]); + if (stIt == s_statsMap.end()) { return SNMP_ERR_GENERR; } - if (const auto& val = std::get_if(&it->second)) { + if (const auto& val = std::get_if(&stIt->second)) { std::string str(std::to_string(**val)); snmp_set_var_typed_value(requests->requestvb, ASN_OCTET_STR, @@ -138,23 +145,23 @@ static int handleFloatStats(netsnmp_mib_handler* handler, return SNMP_ERR_GENERR; } -static void registerFloatStat(const char* name, const oid statOID[], size_t statOIDLength, double* ptr) +static void registerFloatStat(const char* name, const OIDStat& statOID, double* ptr) { - if (statOIDLength != OID_LENGTH(queriesOID)) { + if (statOID.size() != OID_LENGTH(queriesOID)) { errlog("Invalid OID for SNMP Float statistic %s", name); return; } - if (s_statsMap.find(statOID[statOIDLength - 1]) != s_statsMap.end()) { + if (s_statsMap.find(statOID.at(statOID.size() - 1)) != s_statsMap.end()) { errlog("OID for SNMP Float statistic %s has already been registered", name); return; } - s_statsMap[statOID[statOIDLength - 1]] = ptr; + s_statsMap[statOID.at(statOID.size() - 1)] = ptr; netsnmp_register_scalar(netsnmp_create_handler_registration(name, handleFloatStats, - statOID, - statOIDLength, + statOID.data(), + statOID.size(), HANDLER_CAN_RONLY)); } @@ -171,71 +178,71 @@ static int handleGauge64Stats(netsnmp_mib_handler* handler, return SNMP_ERR_GENERR; } - const auto& it = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]); - if (it == s_statsMap.end()) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): net-snmp API + const auto& stIt = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]); + if (stIt == s_statsMap.end()) { return SNMP_ERR_GENERR; } std::string str; - uint64_t value = (*std::get_if(&it->second))(str); + uint64_t value = (*std::get_if(&stIt->second))(str); return DNSDistSNMPAgent::setCounter64Value(requests, value); } -static void registerGauge64Stat(const char* name, const oid statOID[], size_t statOIDLength, dnsdist::metrics::Stats::statfunction_t ptr) +static void registerGauge64Stat(const char* name, const OIDStat& statOID, const dnsdist::metrics::Stats::statfunction_t& ptr) { - if (statOIDLength != OID_LENGTH(queriesOID)) { + if (statOID.size() != OID_LENGTH(queriesOID)) { errlog("Invalid OID for SNMP Gauge64 statistic %s", name); return; } - if (s_statsMap.find(statOID[statOIDLength - 1]) != s_statsMap.end()) { + if (s_statsMap.find(statOID.at(statOID.size() - 1)) != s_statsMap.end()) { errlog("OID for SNMP Gauge64 statistic %s has already been registered", name); return; } - s_statsMap[statOID[statOIDLength - 1]] = ptr; + s_statsMap[statOID.at(statOID.size() - 1)] = ptr; netsnmp_register_scalar(netsnmp_create_handler_registration(name, handleGauge64Stats, - statOID, - statOIDLength, + statOID.data(), + statOID.size(), HANDLER_CAN_RONLY)); } /* column number definitions for table backendStatTable */ -#define COLUMN_BACKENDID 1 -#define COLUMN_BACKENDNAME 2 -#define COLUMN_BACKENDLATENCY 3 -#define COLUMN_BACKENDWEIGHT 4 -#define COLUMN_BACKENDOUTSTANDING 5 -#define COLUMN_BACKENDQPSLIMIT 6 -#define COLUMN_BACKENDREUSED 7 -#define COLUMN_BACKENDSTATE 8 -#define COLUMN_BACKENDADDRESS 9 -#define COLUMN_BACKENDPOOLS 10 -#define COLUMN_BACKENDQPS 11 -#define COLUMN_BACKENDQUERIES 12 -#define COLUMN_BACKENDORDER 13 - -static const oid backendStatTableOID[] = {DNSDIST_STATS_TABLE_OID}; -static const oid backendNameOID[] = {DNSDIST_STATS_TABLE_OID, 1, 2}; -static const oid backendStateOID[] = {DNSDIST_STATS_TABLE_OID, 1, 8}; -static const oid backendAddressOID[] = {DNSDIST_STATS_TABLE_OID, 1, 9}; - -static const oid socketFamilyOID[] = {DNSDIST_TRAP_OBJECTS_OID, 1, 0}; -static const oid socketProtocolOID[] = {DNSDIST_TRAP_OBJECTS_OID, 2, 0}; -static const oid fromAddressOID[] = {DNSDIST_TRAP_OBJECTS_OID, 3, 0}; -static const oid toAddressOID[] = {DNSDIST_TRAP_OBJECTS_OID, 4, 0}; -static const oid queryTypeOID[] = {DNSDIST_TRAP_OBJECTS_OID, 5, 0}; -static const oid querySizeOID[] = {DNSDIST_TRAP_OBJECTS_OID, 6, 0}; -static const oid queryIDOID[] = {DNSDIST_TRAP_OBJECTS_OID, 7, 0}; -static const oid qNameOID[] = {DNSDIST_TRAP_OBJECTS_OID, 8, 0}; -static const oid qClassOID[] = {DNSDIST_TRAP_OBJECTS_OID, 9, 0}; -static const oid qTypeOID[] = {DNSDIST_TRAP_OBJECTS_OID, 10, 0}; -static const oid trapReasonOID[] = {DNSDIST_TRAP_OBJECTS_OID, 11, 0}; - -static const oid backendStatusChangeTrapOID[] = {DNSDIST_TRAPS_OID, 1}; -static const oid actionTrapOID[] = {DNSDIST_TRAPS_OID, 2}; -static const oid customTrapOID[] = {DNSDIST_TRAPS_OID, 3}; +static constexpr unsigned int COLUMN_BACKENDNAME = 2; +static constexpr unsigned int COLUMN_BACKENDLATENCY = 3; +static constexpr unsigned int COLUMN_BACKENDWEIGHT = 4; +static constexpr unsigned int COLUMN_BACKENDOUTSTANDING = 5; +static constexpr unsigned int COLUMN_BACKENDQPSLIMIT = 6; +static constexpr unsigned int COLUMN_BACKENDREUSED = 7; +static constexpr unsigned int COLUMN_BACKENDSTATE = 8; +static constexpr unsigned int COLUMN_BACKENDADDRESS = 9; +static constexpr unsigned int COLUMN_BACKENDPOOLS = 10; +static constexpr unsigned int COLUMN_BACKENDQPS = 11; +static constexpr unsigned int COLUMN_BACKENDQUERIES = 12; +static constexpr unsigned int COLUMN_BACKENDORDER = 13; + +static const std::array backendStatTableOID{DNSDIST_STATS_TABLE_OID}; +static const OIDStatTable backendNameOID{DNSDIST_STATS_TABLE_OID, 1, 2}; +static const OIDStatTable backendStateOID{DNSDIST_STATS_TABLE_OID, 1, 8}; +static const OIDStatTable backendAddressOID{DNSDIST_STATS_TABLE_OID, 1, 9}; + +static const OIDTrapObject socketFamilyOID{DNSDIST_TRAP_OBJECTS_OID, 1, 0}; +static const OIDTrapObject socketProtocolOID{DNSDIST_TRAP_OBJECTS_OID, 2, 0}; +static const OIDTrapObject fromAddressOID{DNSDIST_TRAP_OBJECTS_OID, 3, 0}; +static const OIDTrapObject toAddressOID{DNSDIST_TRAP_OBJECTS_OID, 4, 0}; +static const OIDTrapObject queryTypeOID{DNSDIST_TRAP_OBJECTS_OID, 5, 0}; +static const OIDTrapObject querySizeOID{DNSDIST_TRAP_OBJECTS_OID, 6, 0}; +static const OIDTrapObject queryIDOID{DNSDIST_TRAP_OBJECTS_OID, 7, 0}; +static const OIDTrapObject qNameOID{DNSDIST_TRAP_OBJECTS_OID, 8, 0}; +static const OIDTrapObject qClassOID{DNSDIST_TRAP_OBJECTS_OID, 9, 0}; +static const OIDTrapObject qTypeOID{DNSDIST_TRAP_OBJECTS_OID, 10, 0}; +static const OIDTrapObject trapReasonOID{DNSDIST_TRAP_OBJECTS_OID, 11, 0}; + +static const OIDTrap backendStatusChangeTrapOID{DNSDIST_TRAPS_OID, 1}; +static const OIDTrap actionTrapOID{DNSDIST_TRAPS_OID, 2}; +static const OIDTrap customTrapOID{DNSDIST_TRAPS_OID, 3}; static servers_t s_servers; static size_t s_currentServerIdx = 0; @@ -246,11 +253,11 @@ static netsnmp_variable_list* backendStatTable_get_next_data_point(void** loop_c netsnmp_iterator_info* mydata) { if (s_currentServerIdx >= s_servers.size()) { - return NULL; + return nullptr; } *my_data_context = (void*)(s_servers[s_currentServerIdx]).get(); - snmp_set_var_typed_integer(put_index_data, ASN_UNSIGNED, s_currentServerIdx); + snmp_set_var_typed_integer(put_index_data, ASN_UNSIGNED, static_cast(s_currentServerIdx)); s_currentServerIdx++; return put_index_data; @@ -283,15 +290,15 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler, netsnmp_agent_request_info* reqinfo, netsnmp_request_info* requests) { - netsnmp_request_info* request; + netsnmp_request_info* request{nullptr}; switch (reqinfo->mode) { case MODE_GET: - for (request = requests; request; request = request->next) { + for (request = requests; request != nullptr; request = request->next) { netsnmp_table_request_info* table_info = netsnmp_extract_table_info(request); - const DownstreamState* server = (const DownstreamState*)netsnmp_extract_iterator_context(request); - - if (!server) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API + const auto* server = reinterpret_cast(netsnmp_extract_iterator_context(request)); + if (server == nullptr) { continue; } @@ -304,7 +311,7 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler, break; case COLUMN_BACKENDLATENCY: DNSDistSNMPAgent::setCounter64Value(request, - server->getRelevantLatencyUsec() / 1000.0); + static_cast(server->getRelevantLatencyUsec() / 1000.0)); break; case COLUMN_BACKENDWEIGHT: DNSDistSNMPAgent::setCounter64Value(request, @@ -339,11 +346,11 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler, } case COLUMN_BACKENDPOOLS: { std::string pools; - for (const auto& p : server->d_config.pools) { + for (const auto& pool : server->d_config.pools) { if (!pools.empty()) { pools += " "; } - pools += p; + pools += pool; } snmp_set_var_typed_value(request->requestvb, ASN_OCTET_STR, @@ -352,7 +359,7 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler, break; } case COLUMN_BACKENDQPS: - DNSDistSNMPAgent::setCounter64Value(request, server->queryLoad.load()); + DNSDistSNMPAgent::setCounter64Value(request, static_cast(server->queryLoad.load())); break; case COLUMN_BACKENDQUERIES: DNSDistSNMPAgent::setCounter64Value(request, server->queries.load()); @@ -384,26 +391,26 @@ bool DNSDistSNMPAgent::sendBackendStatusChangeTrap(const DownstreamState& dss) snmpTrapOID.data(), snmpTrapOID.size(), ASN_OBJECT_ID, - backendStatusChangeTrapOID, - OID_LENGTH(backendStatusChangeTrapOID) * sizeof(oid)); + backendStatusChangeTrapOID.data(), + backendStatusChangeTrapOID.size() * sizeof(oid)); snmp_varlist_add_variable(&varList, - backendNameOID, - OID_LENGTH(backendNameOID), + backendNameOID.data(), + backendNameOID.size(), ASN_OCTET_STR, dss.getName().c_str(), dss.getName().size()); snmp_varlist_add_variable(&varList, - backendAddressOID, - OID_LENGTH(backendAddressOID), + backendAddressOID.data(), + backendAddressOID.size(), ASN_OCTET_STR, backendAddress.c_str(), backendAddress.size()); snmp_varlist_add_variable(&varList, - backendStateOID, - OID_LENGTH(backendStateOID), + backendStateOID.data(), + backendStateOID.size(), ASN_OCTET_STR, backendStatus.c_str(), backendStatus.size()); @@ -423,12 +430,12 @@ bool DNSDistSNMPAgent::sendCustomTrap(const std::string& reason) snmpTrapOID.data(), snmpTrapOID.size(), ASN_OBJECT_ID, - customTrapOID, - OID_LENGTH(customTrapOID) * sizeof(oid)); + customTrapOID.data(), + customTrapOID.size() * sizeof(oid)); snmp_varlist_add_variable(&varList, - trapReasonOID, - OID_LENGTH(trapReasonOID), + trapReasonOID.data(), + trapReasonOID.size(), ASN_OCTET_STR, reason.c_str(), reason.size()); @@ -439,19 +446,19 @@ bool DNSDistSNMPAgent::sendCustomTrap(const std::string& reason) #endif /* HAVE_NET_SNMP */ } -bool DNSDistSNMPAgent::sendDNSTrap(const DNSQuestion& dq, const std::string& reason) +bool DNSDistSNMPAgent::sendDNSTrap(const DNSQuestion& dnsQuestion, const std::string& reason) { #ifdef HAVE_NET_SNMP - std::string local = dq.ids.origDest.toString(); - std::string remote = dq.ids.origRemote.toString(); - std::string qname = dq.ids.qname.toStringNoDot(); - const uint32_t socketFamily = dq.ids.origRemote.isIPv4() ? 1 : 2; - const uint32_t socketProtocol = dq.overTCP() ? 2 : 1; - const uint32_t queryType = dq.getHeader()->qr ? 2 : 1; - const uint32_t querySize = (uint32_t)dq.getData().size(); - const uint32_t queryID = (uint32_t)ntohs(dq.getHeader()->id); - const uint32_t qType = (uint32_t)dq.ids.qtype; - const uint32_t qClass = (uint32_t)dq.ids.qclass; + std::string local = dnsQuestion.ids.origDest.toString(); + std::string remote = dnsQuestion.ids.origRemote.toString(); + std::string qname = dnsQuestion.ids.qname.toStringNoDot(); + const uint32_t socketFamily = dnsQuestion.ids.origRemote.isIPv4() ? 1 : 2; + const uint32_t socketProtocol = dnsQuestion.overTCP() ? 2 : 1; + const uint32_t queryType = dnsQuestion.getHeader()->qr ? 2 : 1; + const auto querySize = static_cast(dnsQuestion.getData().size()); + const auto queryID = static_cast(ntohs(dnsQuestion.getHeader()->id)); + const auto qType = static_cast(dnsQuestion.ids.qtype); + const auto qClass = static_cast(dnsQuestion.ids.qclass); netsnmp_variable_list* varList = nullptr; @@ -459,82 +466,89 @@ bool DNSDistSNMPAgent::sendDNSTrap(const DNSQuestion& dq, const std::string& rea snmpTrapOID.data(), snmpTrapOID.size(), ASN_OBJECT_ID, - actionTrapOID, - OID_LENGTH(actionTrapOID) * sizeof(oid)); + actionTrapOID.data(), + actionTrapOID.size() * sizeof(oid)); snmp_varlist_add_variable(&varList, - socketFamilyOID, - OID_LENGTH(socketFamilyOID), + socketFamilyOID.data(), + socketFamilyOID.size(), ASN_INTEGER, + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API reinterpret_cast(&socketFamily), sizeof(socketFamily)); snmp_varlist_add_variable(&varList, - socketProtocolOID, - OID_LENGTH(socketProtocolOID), + socketProtocolOID.data(), + socketProtocolOID.size(), ASN_INTEGER, + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API reinterpret_cast(&socketProtocol), sizeof(socketProtocol)); snmp_varlist_add_variable(&varList, - fromAddressOID, - OID_LENGTH(fromAddressOID), + fromAddressOID.data(), + fromAddressOID.size(), ASN_OCTET_STR, remote.c_str(), remote.size()); snmp_varlist_add_variable(&varList, - toAddressOID, - OID_LENGTH(toAddressOID), + toAddressOID.data(), + toAddressOID.size(), ASN_OCTET_STR, local.c_str(), local.size()); snmp_varlist_add_variable(&varList, - queryTypeOID, - OID_LENGTH(queryTypeOID), + queryTypeOID.data(), + queryTypeOID.size(), ASN_INTEGER, + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API reinterpret_cast(&queryType), sizeof(queryType)); snmp_varlist_add_variable(&varList, - querySizeOID, - OID_LENGTH(querySizeOID), + querySizeOID.data(), + querySizeOID.size(), ASN_UNSIGNED, + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API reinterpret_cast(&querySize), sizeof(querySize)); snmp_varlist_add_variable(&varList, - queryIDOID, - OID_LENGTH(queryIDOID), + queryIDOID.data(), + queryIDOID.size(), ASN_UNSIGNED, + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API reinterpret_cast(&queryID), sizeof(queryID)); snmp_varlist_add_variable(&varList, - qNameOID, - OID_LENGTH(qNameOID), + qNameOID.data(), + qNameOID.size(), ASN_OCTET_STR, qname.c_str(), qname.size()); snmp_varlist_add_variable(&varList, - qClassOID, - OID_LENGTH(qClassOID), + qClassOID.data(), + qClassOID.size(), ASN_UNSIGNED, + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API reinterpret_cast(&qClass), sizeof(qClass)); snmp_varlist_add_variable(&varList, - qTypeOID, - OID_LENGTH(qTypeOID), + qTypeOID.data(), + qTypeOID.size(), ASN_UNSIGNED, + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API reinterpret_cast(&qType), sizeof(qType)); snmp_varlist_add_variable(&varList, - trapReasonOID, - OID_LENGTH(trapReasonOID), + trapReasonOID.data(), + trapReasonOID.size(), ASN_OCTET_STR, reason.c_str(), reason.size()); @@ -550,61 +564,63 @@ DNSDistSNMPAgent::DNSDistSNMPAgent(const std::string& name, const std::string& d { #ifdef HAVE_NET_SNMP - registerCounter64Stat("queries", queriesOID, OID_LENGTH(queriesOID), &dnsdist::metrics::g_stats.queries); - registerCounter64Stat("responses", responsesOID, OID_LENGTH(responsesOID), &dnsdist::metrics::g_stats.responses); - registerCounter64Stat("servfailResponses", servfailResponsesOID, OID_LENGTH(servfailResponsesOID), &dnsdist::metrics::g_stats.servfailResponses); - registerCounter64Stat("aclDrops", aclDropsOID, OID_LENGTH(aclDropsOID), &dnsdist::metrics::g_stats.aclDrops); - registerCounter64Stat("ruleDrop", ruleDropOID, OID_LENGTH(ruleDropOID), &dnsdist::metrics::g_stats.ruleDrop); - registerCounter64Stat("ruleNXDomain", ruleNXDomainOID, OID_LENGTH(ruleNXDomainOID), &dnsdist::metrics::g_stats.ruleNXDomain); - registerCounter64Stat("ruleRefused", ruleRefusedOID, OID_LENGTH(ruleRefusedOID), &dnsdist::metrics::g_stats.ruleRefused); - registerCounter64Stat("ruleServFail", ruleServFailOID, OID_LENGTH(ruleServFailOID), &dnsdist::metrics::g_stats.ruleServFail); - registerCounter64Stat("ruleTruncated", ruleTruncatedOID, OID_LENGTH(ruleTruncatedOID), &dnsdist::metrics::g_stats.ruleTruncated); - registerCounter64Stat("selfAnswered", selfAnsweredOID, OID_LENGTH(selfAnsweredOID), &dnsdist::metrics::g_stats.selfAnswered); - registerCounter64Stat("downstreamTimeouts", downstreamTimeoutsOID, OID_LENGTH(downstreamTimeoutsOID), &dnsdist::metrics::g_stats.downstreamTimeouts); - registerCounter64Stat("downstreamSendErrors", downstreamSendErrorsOID, OID_LENGTH(downstreamSendErrorsOID), &dnsdist::metrics::g_stats.downstreamSendErrors); - registerCounter64Stat("truncFail", truncFailOID, OID_LENGTH(truncFailOID), &dnsdist::metrics::g_stats.truncFail); - registerCounter64Stat("noPolicy", noPolicyOID, OID_LENGTH(noPolicyOID), &dnsdist::metrics::g_stats.noPolicy); - registerCounter64Stat("latency0_1", latency0_1OID, OID_LENGTH(latency0_1OID), &dnsdist::metrics::g_stats.latency0_1); - registerCounter64Stat("latency1_10", latency1_10OID, OID_LENGTH(latency1_10OID), &dnsdist::metrics::g_stats.latency1_10); - registerCounter64Stat("latency10_50", latency10_50OID, OID_LENGTH(latency10_50OID), &dnsdist::metrics::g_stats.latency10_50); - registerCounter64Stat("latency50_100", latency50_100OID, OID_LENGTH(latency50_100OID), &dnsdist::metrics::g_stats.latency50_100); - registerCounter64Stat("latency100_1000", latency100_1000OID, OID_LENGTH(latency100_1000OID), &dnsdist::metrics::g_stats.latency100_1000); - registerCounter64Stat("latencySlow", latencySlowOID, OID_LENGTH(latencySlowOID), &dnsdist::metrics::g_stats.latencySlow); - registerCounter64Stat("nonCompliantQueries", nonCompliantQueriesOID, OID_LENGTH(nonCompliantQueriesOID), &dnsdist::metrics::g_stats.nonCompliantQueries); - registerCounter64Stat("nonCompliantResponses", nonCompliantResponsesOID, OID_LENGTH(nonCompliantResponsesOID), &dnsdist::metrics::g_stats.nonCompliantResponses); - registerCounter64Stat("rdQueries", rdQueriesOID, OID_LENGTH(rdQueriesOID), &dnsdist::metrics::g_stats.rdQueries); - registerCounter64Stat("emptyQueries", emptyQueriesOID, OID_LENGTH(emptyQueriesOID), &dnsdist::metrics::g_stats.emptyQueries); - registerCounter64Stat("cacheHits", cacheHitsOID, OID_LENGTH(cacheHitsOID), &dnsdist::metrics::g_stats.cacheHits); - registerCounter64Stat("cacheMisses", cacheMissesOID, OID_LENGTH(cacheMissesOID), &dnsdist::metrics::g_stats.cacheMisses); - registerCounter64Stat("dynBlocked", dynBlockedOID, OID_LENGTH(dynBlockedOID), &dnsdist::metrics::g_stats.dynBlocked); - registerFloatStat("latencyAvg100", latencyAvg100OID, OID_LENGTH(latencyAvg100OID), &dnsdist::metrics::g_stats.latencyAvg100); - registerFloatStat("latencyAvg1000", latencyAvg1000OID, OID_LENGTH(latencyAvg1000OID), &dnsdist::metrics::g_stats.latencyAvg1000); - registerFloatStat("latencyAvg10000", latencyAvg10000OID, OID_LENGTH(latencyAvg10000OID), &dnsdist::metrics::g_stats.latencyAvg10000); - registerFloatStat("latencyAvg1000000", latencyAvg1000000OID, OID_LENGTH(latencyAvg1000000OID), &dnsdist::metrics::g_stats.latencyAvg1000000); - registerGauge64Stat("uptime", uptimeOID, OID_LENGTH(uptimeOID), &uptimeOfProcess); - registerGauge64Stat("specialMemoryUsage", specialMemoryUsageOID, OID_LENGTH(specialMemoryUsageOID), &getSpecialMemoryUsage); - registerGauge64Stat("cpuUserMSec", cpuUserMSecOID, OID_LENGTH(cpuUserMSecOID), &getCPUTimeUser); - registerGauge64Stat("cpuSysMSec", cpuSysMSecOID, OID_LENGTH(cpuSysMSecOID), &getCPUTimeSystem); - registerGauge64Stat("fdUsage", fdUsageOID, OID_LENGTH(fdUsageOID), &getOpenFileDescriptors); - registerGauge64Stat("dynBlockedNMGSize", dynBlockedNMGSizeOID, OID_LENGTH(dynBlockedNMGSizeOID), [](const std::string&) { return g_dynblockNMG.getLocal()->size(); }); - registerGauge64Stat("securityStatus", securityStatusOID, OID_LENGTH(securityStatusOID), [](const std::string&) { return dnsdist::metrics::g_stats.securityStatus.load(); }); - registerGauge64Stat("realMemoryUsage", realMemoryUsageOID, OID_LENGTH(realMemoryUsageOID), &getRealMemoryUsage); - - netsnmp_table_registration_info* table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info); + registerCounter64Stat("queries", queriesOID, &dnsdist::metrics::g_stats.queries); + registerCounter64Stat("responses", responsesOID, &dnsdist::metrics::g_stats.responses); + registerCounter64Stat("servfailResponses", servfailResponsesOID, &dnsdist::metrics::g_stats.servfailResponses); + registerCounter64Stat("aclDrops", aclDropsOID, &dnsdist::metrics::g_stats.aclDrops); + registerCounter64Stat("ruleDrop", ruleDropOID, &dnsdist::metrics::g_stats.ruleDrop); + registerCounter64Stat("ruleNXDomain", ruleNXDomainOID, &dnsdist::metrics::g_stats.ruleNXDomain); + registerCounter64Stat("ruleRefused", ruleRefusedOID, &dnsdist::metrics::g_stats.ruleRefused); + registerCounter64Stat("ruleServFail", ruleServFailOID, &dnsdist::metrics::g_stats.ruleServFail); + registerCounter64Stat("ruleTruncated", ruleTruncatedOID, &dnsdist::metrics::g_stats.ruleTruncated); + registerCounter64Stat("selfAnswered", selfAnsweredOID, &dnsdist::metrics::g_stats.selfAnswered); + registerCounter64Stat("downstreamTimeouts", downstreamTimeoutsOID, &dnsdist::metrics::g_stats.downstreamTimeouts); + registerCounter64Stat("downstreamSendErrors", downstreamSendErrorsOID, &dnsdist::metrics::g_stats.downstreamSendErrors); + registerCounter64Stat("truncFail", truncFailOID, &dnsdist::metrics::g_stats.truncFail); + registerCounter64Stat("noPolicy", noPolicyOID, &dnsdist::metrics::g_stats.noPolicy); + registerCounter64Stat("latency0_1", latency0_1OID, &dnsdist::metrics::g_stats.latency0_1); + registerCounter64Stat("latency1_10", latency1_10OID, &dnsdist::metrics::g_stats.latency1_10); + registerCounter64Stat("latency10_50", latency10_50OID, &dnsdist::metrics::g_stats.latency10_50); + registerCounter64Stat("latency50_100", latency50_100OID, &dnsdist::metrics::g_stats.latency50_100); + registerCounter64Stat("latency100_1000", latency100_1000OID, &dnsdist::metrics::g_stats.latency100_1000); + registerCounter64Stat("latencySlow", latencySlowOID, &dnsdist::metrics::g_stats.latencySlow); + registerCounter64Stat("nonCompliantQueries", nonCompliantQueriesOID, &dnsdist::metrics::g_stats.nonCompliantQueries); + registerCounter64Stat("nonCompliantResponses", nonCompliantResponsesOID, &dnsdist::metrics::g_stats.nonCompliantResponses); + registerCounter64Stat("rdQueries", rdQueriesOID, &dnsdist::metrics::g_stats.rdQueries); + registerCounter64Stat("emptyQueries", emptyQueriesOID, &dnsdist::metrics::g_stats.emptyQueries); + registerCounter64Stat("cacheHits", cacheHitsOID, &dnsdist::metrics::g_stats.cacheHits); + registerCounter64Stat("cacheMisses", cacheMissesOID, &dnsdist::metrics::g_stats.cacheMisses); + registerCounter64Stat("dynBlocked", dynBlockedOID, &dnsdist::metrics::g_stats.dynBlocked); + registerFloatStat("latencyAvg100", latencyAvg100OID, &dnsdist::metrics::g_stats.latencyAvg100); + registerFloatStat("latencyAvg1000", latencyAvg1000OID, &dnsdist::metrics::g_stats.latencyAvg1000); + registerFloatStat("latencyAvg10000", latencyAvg10000OID, &dnsdist::metrics::g_stats.latencyAvg10000); + registerFloatStat("latencyAvg1000000", latencyAvg1000000OID, &dnsdist::metrics::g_stats.latencyAvg1000000); + registerGauge64Stat("uptime", uptimeOID, &uptimeOfProcess); + registerGauge64Stat("specialMemoryUsage", specialMemoryUsageOID, &getSpecialMemoryUsage); + registerGauge64Stat("cpuUserMSec", cpuUserMSecOID, &getCPUTimeUser); + registerGauge64Stat("cpuSysMSec", cpuSysMSecOID, &getCPUTimeSystem); + registerGauge64Stat("fdUsage", fdUsageOID, &getOpenFileDescriptors); + registerGauge64Stat("dynBlockedNMGSize", dynBlockedNMGSizeOID, [](const std::string&) { return g_dynblockNMG.getLocal()->size(); }); + registerGauge64Stat("securityStatus", securityStatusOID, [](const std::string&) { return dnsdist::metrics::g_stats.securityStatus.load(); }); + registerGauge64Stat("realMemoryUsage", realMemoryUsageOID, &getRealMemoryUsage); + + // NOLINTNEXTLINE(cppcoreguidelines-owning-memory): net-snmp API + auto* table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info); netsnmp_table_helper_add_indexes(table_info, ASN_GAUGE, /* index: backendId */ 0); table_info->min_column = COLUMN_BACKENDNAME; table_info->max_column = COLUMN_BACKENDORDER; - netsnmp_iterator_info* iinfo = SNMP_MALLOC_TYPEDEF(netsnmp_iterator_info); + // NOLINTNEXTLINE(cppcoreguidelines-owning-memory): net-snmp API + auto* iinfo = SNMP_MALLOC_TYPEDEF(netsnmp_iterator_info); iinfo->get_first_data_point = backendStatTable_get_first_data_point; iinfo->get_next_data_point = backendStatTable_get_next_data_point; iinfo->table_reginfo = table_info; netsnmp_register_table_iterator(netsnmp_create_handler_registration("backendStatTable", backendStatTable_handler, - backendStatTableOID, - OID_LENGTH(backendStatTableOID), + backendStatTableOID.data(), + backendStatTableOID.size(), HANDLER_CAN_RONLY), iinfo); diff --git a/pdns/dnsdistdist/dnsdist.hh b/pdns/dnsdistdist/dnsdist.hh index 064e0e867881..5f3bb816288f 100644 --- a/pdns/dnsdistdist/dnsdist.hh +++ b/pdns/dnsdistdist/dnsdist.hh @@ -1248,7 +1248,7 @@ bool checkDNSCryptQuery(const ClientState& cs, PacketBuffer& query, std::unique_ extern bool g_snmpEnabled; extern bool g_snmpTrapsEnabled; -extern DNSDistSNMPAgent* g_snmpAgent; +extern std::unique_ptr g_snmpAgent; extern bool g_addEDNSToSelfGeneratedResponses; extern std::set g_capabilitiesToRetain; diff --git a/pdns/dnsdistdist/test-dnsdistlbpolicies_cc.cc b/pdns/dnsdistdist/test-dnsdistlbpolicies_cc.cc index bcb73b26529c..fb74a16264e9 100644 --- a/pdns/dnsdistdist/test-dnsdistlbpolicies_cc.cc +++ b/pdns/dnsdistdist/test-dnsdistlbpolicies_cc.cc @@ -19,7 +19,7 @@ LockGuarded g_lua{LuaContext()}; bool g_snmpEnabled{false}; bool g_snmpTrapsEnabled{false}; -DNSDistSNMPAgent* g_snmpAgent{nullptr}; +std::unique_ptr g_snmpAgent{nullptr}; #if BENCH_POLICIES bool g_verbose{true}; From e289a3ec91d9e431a95a61213de54f155d67bbb7 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Tue, 5 Mar 2024 10:50:35 +0100 Subject: [PATCH 18/25] dnsdist: Delint dnsdist-protocols.cc --- pdns/dnsdistdist/dnsdist-protocols.cc | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-protocols.cc b/pdns/dnsdistdist/dnsdist-protocols.cc index 886e7ee42064..35da4711f415 100644 --- a/pdns/dnsdistdist/dnsdist-protocols.cc +++ b/pdns/dnsdistdist/dnsdist-protocols.cc @@ -47,14 +47,14 @@ const std::array Protocol::s_prettyN "DNS over QUIC", "DNS over HTTP/3"}; -Protocol::Protocol(const std::string& s) +Protocol::Protocol(const std::string& protocol) { - const auto& it = std::find(s_names.begin(), s_names.end(), s); - if (it == s_names.end()) { - throw std::runtime_error("Unknown protocol name: '" + s + "'"); + const auto& namesIt = std::find(s_names.begin(), s_names.end(), protocol); + if (namesIt == s_names.end()) { + throw std::runtime_error("Unknown protocol name: '" + protocol + "'"); } - auto index = std::distance(s_names.begin(), it); + auto index = std::distance(s_names.begin(), namesIt); d_protocol = static_cast(index); } From 8c1a1a0acc0256b5278aad7cdec02b5940bbc40d Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Tue, 5 Mar 2024 10:51:19 +0100 Subject: [PATCH 19/25] dnsdist: Delint dnsdist-lua-vars.cc --- pdns/dnsdistdist/dnsdist-lua-vars.cc | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-lua-vars.cc b/pdns/dnsdistdist/dnsdist-lua-vars.cc index e237204220f1..9fc3f521b5c7 100644 --- a/pdns/dnsdistdist/dnsdist-lua-vars.cc +++ b/pdns/dnsdistdist/dnsdist-lua-vars.cc @@ -41,11 +41,11 @@ void setupLuaVars(LuaContext& luaCtx) luaCtx.writeVariable("DNSRCode", LuaAssociativeTable{{"NOERROR", RCode::NoError}, {"FORMERR", RCode::FormErr}, {"SERVFAIL", RCode::ServFail}, {"NXDOMAIN", RCode::NXDomain}, {"NOTIMP", RCode::NotImp}, {"REFUSED", RCode::Refused}, {"YXDOMAIN", RCode::YXDomain}, {"YXRRSET", RCode::YXRRSet}, {"NXRRSET", RCode::NXRRSet}, {"NOTAUTH", RCode::NotAuth}, {"NOTZONE", RCode::NotZone}, {"BADVERS", ERCode::BADVERS}, {"BADSIG", ERCode::BADSIG}, {"BADKEY", ERCode::BADKEY}, {"BADTIME", ERCode::BADTIME}, {"BADMODE", ERCode::BADMODE}, {"BADNAME", ERCode::BADNAME}, {"BADALG", ERCode::BADALG}, {"BADTRUNC", ERCode::BADTRUNC}, {"BADCOOKIE", ERCode::BADCOOKIE}}); - LuaAssociativeTable dd; - for (const auto& n : QType::names) { - dd[n.first] = n.second; + LuaAssociativeTable dnsqtypes; + for (const auto& name : QType::names) { + dnsqtypes[name.first] = name.second; } - luaCtx.writeVariable("DNSQType", dd); + luaCtx.writeVariable("DNSQType", dnsqtypes); #ifdef HAVE_DNSCRYPT luaCtx.writeVariable("DNSCryptExchangeVersion", LuaAssociativeTable{ From 34b2ed52e56b7ace76bc899630d5fcf59e637195 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Wed, 6 Mar 2024 12:09:41 +0100 Subject: [PATCH 20/25] dnsdist: Fix formatting issues --- .../dnsdist-lua-bindings-dnsquestion.cc | 24 +++++++++++++++---- pdns/dnsdistdist/dnsdist-lua-bindings.cc | 8 +++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc b/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc index 6003f5c5e84b..9297dbccad81 100644 --- a/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc +++ b/pdns/dnsdistdist/dnsdist-lua-bindings-dnsquestion.cc @@ -42,7 +42,11 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) luaCtx.registerMember( "qclass", [](const DNSQuestion& dnsQuestion) -> uint16_t { return dnsQuestion.ids.qclass; }, [](DNSQuestion& dnsQuestion, uint16_t newClass) { (void)newClass; }); luaCtx.registerMember( - "rcode", [](const DNSQuestion& dnsQuestion) -> int { return static_cast(dnsQuestion.getHeader()->rcode); }, [](DNSQuestion& dnsQuestion, int newRCode) { + "rcode", + [](const DNSQuestion& dnsQuestion) -> int { + return static_cast(dnsQuestion.getHeader()->rcode); + }, + [](DNSQuestion& dnsQuestion, int newRCode) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [newRCode](dnsheader& header) { header.rcode = static_cast(newRCode); return true; @@ -52,7 +56,11 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) "remoteaddr", [](const DNSQuestion& dnsQuestion) -> ComboAddress { return dnsQuestion.ids.origRemote; }, [](DNSQuestion& dnsQuestion, const ComboAddress newRemote) { (void)newRemote; }); /* DNSDist DNSQuestion */ luaCtx.registerMember( - "dh", [](const DNSQuestion& dnsQuestion) -> dnsheader* { return dnsQuestion.getMutableHeader(); }, [](DNSQuestion& dnsQuestion, const dnsheader* dnsHeader) { + "dh", + [](const DNSQuestion& dnsQuestion) -> dnsheader* { + return dnsQuestion.getMutableHeader(); + }, + [](DNSQuestion& dnsQuestion, const dnsheader* dnsHeader) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [&dnsHeader](dnsheader& header) { header = *dnsHeader; return true; @@ -376,7 +384,11 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) luaCtx.registerMember( "qclass", [](const DNSResponse& dnsQuestion) -> uint16_t { return dnsQuestion.ids.qclass; }, [](DNSResponse& dnsQuestion, uint16_t newClass) { (void)newClass; }); luaCtx.registerMember( - "rcode", [](const DNSResponse& dnsQuestion) -> int { return static_cast(dnsQuestion.getHeader()->rcode); }, [](DNSResponse& dnsQuestion, int newRCode) { + "rcode", + [](const DNSResponse& dnsQuestion) -> int { + return static_cast(dnsQuestion.getHeader()->rcode); + }, + [](DNSResponse& dnsQuestion, int newRCode) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [newRCode](dnsheader& header) { header.rcode = static_cast(newRCode); return true; @@ -385,7 +397,11 @@ void setupLuaBindingsDNSQuestion(LuaContext& luaCtx) luaCtx.registerMember( "remoteaddr", [](const DNSResponse& dnsQuestion) -> ComboAddress { return dnsQuestion.ids.origRemote; }, [](DNSResponse& dnsQuestion, const ComboAddress newRemote) { (void)newRemote; }); luaCtx.registerMember( - "dh", [](const DNSResponse& dnsResponse) -> dnsheader* { return dnsResponse.getMutableHeader(); }, [](DNSResponse& dnsResponse, const dnsheader* dnsHeader) { + "dh", + [](const DNSResponse& dnsResponse) -> dnsheader* { + return dnsResponse.getMutableHeader(); + }, + [](DNSResponse& dnsResponse, const dnsheader* dnsHeader) { dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsResponse.getMutableData(), [&dnsHeader](dnsheader& header) { header = *dnsHeader; return true; diff --git a/pdns/dnsdistdist/dnsdist-lua-bindings.cc b/pdns/dnsdistdist/dnsdist-lua-bindings.cc index ba63b54692a1..21afaf5dd787 100644 --- a/pdns/dnsdistdist/dnsdist-lua-bindings.cc +++ b/pdns/dnsdistdist/dnsdist-lua-bindings.cc @@ -283,10 +283,12 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) luaCtx.registerFunction("__tostring", [](const DNSNameSet& dns) { return dns.toString(); }); luaCtx.registerFunction("add", [](DNSNameSet& dns, DNSName& name) { dns.insert(name); }); luaCtx.registerFunction("check", [](DNSNameSet& dns, DNSName& name) { return dns.find(name) != dns.end(); }); + // clang-format off luaCtx.registerFunction("delete", (size_t (DNSNameSet::*)(const DNSName&)) &DNSNameSet::erase); luaCtx.registerFunction("size", (size_t (DNSNameSet::*)() const) &DNSNameSet::size); luaCtx.registerFunction("clear", (void (DNSNameSet::*)()) &DNSNameSet::clear); luaCtx.registerFunction("empty", (bool (DNSNameSet::*)() const) &DNSNameSet::empty); + // clang-format on #endif /* DISABLE_DNSNAME_BINDINGS */ #ifndef DISABLE_SUFFIX_MATCH_BINDINGS @@ -346,7 +348,9 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } }); + // clang-format off luaCtx.registerFunction("check", (bool (SuffixMatchNode::*)(const DNSName&) const) &SuffixMatchNode::check); + // clang-format on luaCtx.registerFunction (SuffixMatchNode::*)(const DNSName&) const>("getBestMatch", [](const SuffixMatchNode& smn, const DNSName& needle) { boost::optional result{boost::none}; auto res = smn.getBestMatch(needle); @@ -381,7 +385,9 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) luaCtx.registerFunction("isIPv4", &Netmask::isIPv4); luaCtx.registerFunction("isIpv6", &Netmask::isIPv6); luaCtx.registerFunction("isIPv6", &Netmask::isIPv6); + // clang-format off luaCtx.registerFunction("match", (bool (Netmask::*)(const string&) const) &Netmask::match); + // clang-format on luaCtx.registerFunction("toString", &Netmask::toString); luaCtx.registerFunction("__tostring", &Netmask::toString); luaCtx.registerEqFunction(&Netmask::operator==); @@ -405,7 +411,9 @@ void setupLuaBindings(LuaContext& luaCtx, bool client, bool configCheck) } }); + // clang-format off luaCtx.registerFunction("match", (bool (NetmaskGroup::*)(const ComboAddress&) const) &NetmaskGroup::match); + // clang-format on luaCtx.registerFunction("size", &NetmaskGroup::size); luaCtx.registerFunction("clear", &NetmaskGroup::clear); luaCtx.registerFunction("toString", [](const NetmaskGroup& nmg) { return "NetmaskGroup " + nmg.toString(); }); From 94403f9fbc40bd91235119bba90ea0a7f292356b Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Wed, 6 Mar 2024 12:33:34 +0100 Subject: [PATCH 21/25] dnsdist: Delint dnsdist-ecs.cc --- pdns/dnsdistdist/dnsdist-ecs.cc | 628 ++++++++++++++++---------------- pdns/dnsdistdist/dnsdist-ecs.hh | 14 +- 2 files changed, 326 insertions(+), 316 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-ecs.cc b/pdns/dnsdistdist/dnsdist-ecs.cc index 5fa61c5b1992..78ab5e14b184 100644 --- a/pdns/dnsdistdist/dnsdist-ecs.cc +++ b/pdns/dnsdistdist/dnsdist-ecs.cc @@ -45,50 +45,48 @@ bool g_addEDNSToSelfGeneratedResponses{true}; int rewriteResponseWithoutEDNS(const PacketBuffer& initialPacket, PacketBuffer& newContent) { assert(initialPacket.size() >= sizeof(dnsheader)); - const dnsheader_aligned dh(initialPacket.data()); + const dnsheader_aligned dnsHeader(initialPacket.data()); - if (ntohs(dh->arcount) == 0) { + if (ntohs(dnsHeader->arcount) == 0) { return ENOENT; } - if (ntohs(dh->qdcount) == 0) { + if (ntohs(dnsHeader->qdcount) == 0) { return ENOENT; } - PacketReader pr(std::string_view(reinterpret_cast(initialPacket.data()), initialPacket.size())); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + PacketReader packetReader(std::string_view(reinterpret_cast(initialPacket.data()), initialPacket.size())); size_t idx = 0; - DNSName rrname; - uint16_t qdcount = ntohs(dh->qdcount); - uint16_t ancount = ntohs(dh->ancount); - uint16_t nscount = ntohs(dh->nscount); - uint16_t arcount = ntohs(dh->arcount); - uint16_t rrtype; - uint16_t rrclass; + uint16_t qdcount = ntohs(dnsHeader->qdcount); + uint16_t ancount = ntohs(dnsHeader->ancount); + uint16_t nscount = ntohs(dnsHeader->nscount); + uint16_t arcount = ntohs(dnsHeader->arcount); string blob; - struct dnsrecordheader ah; - - rrname = pr.getName(); - rrtype = pr.get16BitInt(); - rrclass = pr.get16BitInt(); - - GenericDNSPacketWriter pw(newContent, rrname, rrtype, rrclass, dh->opcode); - pw.getHeader()->id = dh->id; - pw.getHeader()->qr = dh->qr; - pw.getHeader()->aa = dh->aa; - pw.getHeader()->tc = dh->tc; - pw.getHeader()->rd = dh->rd; - pw.getHeader()->ra = dh->ra; - pw.getHeader()->ad = dh->ad; - pw.getHeader()->cd = dh->cd; - pw.getHeader()->rcode = dh->rcode; + dnsrecordheader recordHeader{}; + + auto rrname = packetReader.getName(); + auto rrtype = packetReader.get16BitInt(); + auto rrclass = packetReader.get16BitInt(); + + GenericDNSPacketWriter packetWriter(newContent, rrname, rrtype, rrclass, dnsHeader->opcode); + packetWriter.getHeader()->id = dnsHeader->id; + packetWriter.getHeader()->qr = dnsHeader->qr; + packetWriter.getHeader()->aa = dnsHeader->aa; + packetWriter.getHeader()->tc = dnsHeader->tc; + packetWriter.getHeader()->rd = dnsHeader->rd; + packetWriter.getHeader()->ra = dnsHeader->ra; + packetWriter.getHeader()->ad = dnsHeader->ad; + packetWriter.getHeader()->cd = dnsHeader->cd; + packetWriter.getHeader()->rcode = dnsHeader->rcode; /* consume remaining qd if any */ if (qdcount > 1) { for (idx = 1; idx < qdcount; idx++) { - rrname = pr.getName(); - rrtype = pr.get16BitInt(); - rrclass = pr.get16BitInt(); + rrname = packetReader.getName(); + rrtype = packetReader.get16BitInt(); + rrclass = packetReader.get16BitInt(); (void)rrtype; (void)rrclass; } @@ -96,38 +94,38 @@ int rewriteResponseWithoutEDNS(const PacketBuffer& initialPacket, PacketBuffer& /* copy AN and NS */ for (idx = 0; idx < ancount; idx++) { - rrname = pr.getName(); - pr.getDnsrecordheader(ah); + rrname = packetReader.getName(); + packetReader.getDnsrecordheader(recordHeader); - pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::ANSWER, true); - pr.xfrBlob(blob); - pw.xfrBlob(blob); + packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ANSWER, true); + packetReader.xfrBlob(blob); + packetWriter.xfrBlob(blob); } for (idx = 0; idx < nscount; idx++) { - rrname = pr.getName(); - pr.getDnsrecordheader(ah); + rrname = packetReader.getName(); + packetReader.getDnsrecordheader(recordHeader); - pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::AUTHORITY, true); - pr.xfrBlob(blob); - pw.xfrBlob(blob); + packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::AUTHORITY, true); + packetReader.xfrBlob(blob); + packetWriter.xfrBlob(blob); } /* consume AR, looking for OPT */ for (idx = 0; idx < arcount; idx++) { - rrname = pr.getName(); - pr.getDnsrecordheader(ah); + rrname = packetReader.getName(); + packetReader.getDnsrecordheader(recordHeader); - if (ah.d_type != QType::OPT) { - pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::ADDITIONAL, true); - pr.xfrBlob(blob); - pw.xfrBlob(blob); + if (recordHeader.d_type != QType::OPT) { + packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ADDITIONAL, true); + packetReader.xfrBlob(blob); + packetWriter.xfrBlob(blob); } else { - pr.skip(ah.d_clen); + packetReader.skip(recordHeader.d_clen); } } - pw.commit(); + packetWriter.commit(); return 0; } @@ -156,53 +154,51 @@ static bool addOrReplaceEDNSOption(std::vector> bool slowRewriteEDNSOptionInQueryWithRecords(const PacketBuffer& initialPacket, PacketBuffer& newContent, bool& ednsAdded, uint16_t optionToReplace, bool& optionAdded, bool overrideExisting, const string& newOptionContent) { assert(initialPacket.size() >= sizeof(dnsheader)); - const dnsheader_aligned dh(initialPacket.data()); + const dnsheader_aligned dnsHeader(initialPacket.data()); - if (ntohs(dh->qdcount) == 0) { + if (ntohs(dnsHeader->qdcount) == 0) { return false; } - if (ntohs(dh->ancount) == 0 && ntohs(dh->nscount) == 0 && ntohs(dh->arcount) == 0) { - throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + " should not be called for queries that have no records"); + if (ntohs(dnsHeader->ancount) == 0 && ntohs(dnsHeader->nscount) == 0 && ntohs(dnsHeader->arcount) == 0) { + throw std::runtime_error("slowRewriteEDNSOptionInQueryWithRecords should not be called for queries that have no records"); } optionAdded = false; ednsAdded = true; - PacketReader pr(std::string_view(reinterpret_cast(initialPacket.data()), initialPacket.size())); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + PacketReader packetReader(std::string_view(reinterpret_cast(initialPacket.data()), initialPacket.size())); size_t idx = 0; - DNSName rrname; - uint16_t qdcount = ntohs(dh->qdcount); - uint16_t ancount = ntohs(dh->ancount); - uint16_t nscount = ntohs(dh->nscount); - uint16_t arcount = ntohs(dh->arcount); - uint16_t rrtype; - uint16_t rrclass; + uint16_t qdcount = ntohs(dnsHeader->qdcount); + uint16_t ancount = ntohs(dnsHeader->ancount); + uint16_t nscount = ntohs(dnsHeader->nscount); + uint16_t arcount = ntohs(dnsHeader->arcount); string blob; - struct dnsrecordheader ah; - - rrname = pr.getName(); - rrtype = pr.get16BitInt(); - rrclass = pr.get16BitInt(); - - GenericDNSPacketWriter pw(newContent, rrname, rrtype, rrclass, dh->opcode); - pw.getHeader()->id = dh->id; - pw.getHeader()->qr = dh->qr; - pw.getHeader()->aa = dh->aa; - pw.getHeader()->tc = dh->tc; - pw.getHeader()->rd = dh->rd; - pw.getHeader()->ra = dh->ra; - pw.getHeader()->ad = dh->ad; - pw.getHeader()->cd = dh->cd; - pw.getHeader()->rcode = dh->rcode; + dnsrecordheader recordHeader{}; + + auto rrname = packetReader.getName(); + auto rrtype = packetReader.get16BitInt(); + auto rrclass = packetReader.get16BitInt(); + + GenericDNSPacketWriter packetWriter(newContent, rrname, rrtype, rrclass, dnsHeader->opcode); + packetWriter.getHeader()->id = dnsHeader->id; + packetWriter.getHeader()->qr = dnsHeader->qr; + packetWriter.getHeader()->aa = dnsHeader->aa; + packetWriter.getHeader()->tc = dnsHeader->tc; + packetWriter.getHeader()->rd = dnsHeader->rd; + packetWriter.getHeader()->ra = dnsHeader->ra; + packetWriter.getHeader()->ad = dnsHeader->ad; + packetWriter.getHeader()->cd = dnsHeader->cd; + packetWriter.getHeader()->rcode = dnsHeader->rcode; /* consume remaining qd if any */ if (qdcount > 1) { for (idx = 1; idx < qdcount; idx++) { - rrname = pr.getName(); - rrtype = pr.get16BitInt(); - rrclass = pr.get16BitInt(); + rrname = packetReader.getName(); + rrtype = packetReader.get16BitInt(); + rrclass = packetReader.get16BitInt(); (void)rrtype; (void)rrclass; } @@ -210,60 +206,60 @@ bool slowRewriteEDNSOptionInQueryWithRecords(const PacketBuffer& initialPacket, /* copy AN and NS */ for (idx = 0; idx < ancount; idx++) { - rrname = pr.getName(); - pr.getDnsrecordheader(ah); + rrname = packetReader.getName(); + packetReader.getDnsrecordheader(recordHeader); - pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::ANSWER, true); - pr.xfrBlob(blob); - pw.xfrBlob(blob); + packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ANSWER, true); + packetReader.xfrBlob(blob); + packetWriter.xfrBlob(blob); } for (idx = 0; idx < nscount; idx++) { - rrname = pr.getName(); - pr.getDnsrecordheader(ah); + rrname = packetReader.getName(); + packetReader.getDnsrecordheader(recordHeader); - pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::AUTHORITY, true); - pr.xfrBlob(blob); - pw.xfrBlob(blob); + packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::AUTHORITY, true); + packetReader.xfrBlob(blob); + packetWriter.xfrBlob(blob); } /* consume AR, looking for OPT */ for (idx = 0; idx < arcount; idx++) { - rrname = pr.getName(); - pr.getDnsrecordheader(ah); + rrname = packetReader.getName(); + packetReader.getDnsrecordheader(recordHeader); - if (ah.d_type != QType::OPT) { - pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::ADDITIONAL, true); - pr.xfrBlob(blob); - pw.xfrBlob(blob); + if (recordHeader.d_type != QType::OPT) { + packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ADDITIONAL, true); + packetReader.xfrBlob(blob); + packetWriter.xfrBlob(blob); } else { ednsAdded = false; - pr.xfrBlob(blob); + packetReader.xfrBlob(blob); std::vector> options; getEDNSOptionsFromContent(blob, options); /* getDnsrecordheader() has helpfully converted the TTL for us, which we do not want in that case */ - uint32_t ttl = htonl(ah.d_ttl); - EDNS0Record edns0; + uint32_t ttl = htonl(recordHeader.d_ttl); + EDNS0Record edns0{}; static_assert(sizeof(edns0) == sizeof(ttl), "sizeof(EDNS0Record) must match sizeof(uint32_t) AKA RR TTL size"); memcpy(&edns0, &ttl, sizeof(edns0)); /* addOrReplaceEDNSOption will set it to false if there is already an existing option */ optionAdded = true; addOrReplaceEDNSOption(options, optionToReplace, optionAdded, overrideExisting, newOptionContent); - pw.addOpt(ah.d_class, edns0.extRCode, edns0.extFlags, options, edns0.version); + packetWriter.addOpt(recordHeader.d_class, edns0.extRCode, edns0.extFlags, options, edns0.version); } } if (ednsAdded) { - pw.addOpt(g_EdnsUDPPayloadSize, 0, 0, {{optionToReplace, std::string(&newOptionContent.at(EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE), newOptionContent.size() - (EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE))}}, 0); + packetWriter.addOpt(g_EdnsUDPPayloadSize, 0, 0, {{optionToReplace, std::string(&newOptionContent.at(EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE), newOptionContent.size() - (EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE))}}, 0); optionAdded = true; } - pw.commit(); + packetWriter.commit(); return true; } @@ -274,30 +270,31 @@ static bool slowParseEDNSOptions(const PacketBuffer& packet, EDNSOptionViewMap& return false; } - const dnsheader_aligned dh(packet.data()); + const dnsheader_aligned dnsHeader(packet.data()); - if (ntohs(dh->qdcount) == 0) { + if (ntohs(dnsHeader->qdcount) == 0) { return false; } - if (ntohs(dh->arcount) == 0) { + if (ntohs(dnsHeader->arcount) == 0) { throw std::runtime_error("slowParseEDNSOptions() should not be called for queries that have no EDNS"); } try { - uint64_t numrecords = ntohs(dh->ancount) + ntohs(dh->nscount) + ntohs(dh->arcount); - DNSPacketMangler dpm(const_cast(reinterpret_cast(&packet.at(0))), packet.size()); - uint64_t n; - for (n = 0; n < ntohs(dh->qdcount); ++n) { + uint64_t numrecords = ntohs(dnsHeader->ancount) + ntohs(dnsHeader->nscount) + ntohs(dnsHeader->arcount); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-type-const-cast) + DNSPacketMangler dpm(const_cast(reinterpret_cast(packet.data())), packet.size()); + uint64_t index{}; + for (index = 0; index < ntohs(dnsHeader->qdcount); ++index) { dpm.skipDomainName(); /* type and class */ dpm.skipBytes(4); } - for (n = 0; n < numrecords; ++n) { + for (index = 0; index < numrecords; ++index) { dpm.skipDomainName(); - uint8_t section = n < ntohs(dh->ancount) ? 1 : (n < (ntohs(dh->ancount) + ntohs(dh->nscount)) ? 2 : 3); + uint8_t section = index < ntohs(dnsHeader->ancount) ? 1 : (index < (ntohs(dnsHeader->ancount) + ntohs(dnsHeader->nscount)) ? 2 : 3); uint16_t dnstype = dpm.get16BitInt(); dpm.get16BitInt(); dpm.skipBytes(4); /* TTL */ @@ -309,11 +306,10 @@ static bool slowParseEDNSOptions(const PacketBuffer& packet, EDNSOptionViewMap& } /* if we survive this call, we can parse it safely */ dpm.skipRData(); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) return getEDNSOptions(reinterpret_cast(&packet.at(offset)), packet.size() - offset, options) == 0; } - else { - dpm.skipRData(); - } + dpm.skipRData(); } } catch (...) { @@ -325,52 +321,53 @@ static bool slowParseEDNSOptions(const PacketBuffer& packet, EDNSOptionViewMap& int locateEDNSOptRR(const PacketBuffer& packet, uint16_t* optStart, size_t* optLen, bool* last) { - assert(optStart != NULL); - assert(optLen != NULL); - assert(last != NULL); - const dnsheader_aligned dh(packet.data()); + assert(optStart != nullptr); + assert(optLen != nullptr); + assert(last != nullptr); + const dnsheader_aligned dnsHeader(packet.data()); - if (ntohs(dh->arcount) == 0) { + if (ntohs(dnsHeader->arcount) == 0) { return ENOENT; } - PacketReader pr(std::string_view(reinterpret_cast(packet.data()), packet.size())); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + PacketReader packetReader(std::string_view(reinterpret_cast(packet.data()), packet.size())); size_t idx = 0; DNSName rrname; - uint16_t qdcount = ntohs(dh->qdcount); - uint16_t ancount = ntohs(dh->ancount); - uint16_t nscount = ntohs(dh->nscount); - uint16_t arcount = ntohs(dh->arcount); - uint16_t rrtype; - uint16_t rrclass; - struct dnsrecordheader ah; + uint16_t qdcount = ntohs(dnsHeader->qdcount); + uint16_t ancount = ntohs(dnsHeader->ancount); + uint16_t nscount = ntohs(dnsHeader->nscount); + uint16_t arcount = ntohs(dnsHeader->arcount); + uint16_t rrtype{}; + uint16_t rrclass{}; + dnsrecordheader recordHeader{}; /* consume qd */ for (idx = 0; idx < qdcount; idx++) { - rrname = pr.getName(); - rrtype = pr.get16BitInt(); - rrclass = pr.get16BitInt(); + rrname = packetReader.getName(); + rrtype = packetReader.get16BitInt(); + rrclass = packetReader.get16BitInt(); (void)rrtype; (void)rrclass; } /* consume AN and NS */ for (idx = 0; idx < ancount + nscount; idx++) { - rrname = pr.getName(); - pr.getDnsrecordheader(ah); - pr.skip(ah.d_clen); + rrname = packetReader.getName(); + packetReader.getDnsrecordheader(recordHeader); + packetReader.skip(recordHeader.d_clen); } /* consume AR, looking for OPT */ for (idx = 0; idx < arcount; idx++) { - uint16_t start = pr.getPosition(); - rrname = pr.getName(); - pr.getDnsrecordheader(ah); + uint16_t start = packetReader.getPosition(); + rrname = packetReader.getName(); + packetReader.getDnsrecordheader(recordHeader); - if (ah.d_type == QType::OPT) { + if (recordHeader.d_type == QType::OPT) { *optStart = start; - *optLen = (pr.getPosition() - start) + ah.d_clen; + *optLen = (packetReader.getPosition() - start) + recordHeader.d_clen; if (packet.size() < (*optStart + *optLen)) { throw std::range_error("Opt record overflow"); @@ -384,7 +381,7 @@ int locateEDNSOptRR(const PacketBuffer& packet, uint16_t* optStart, size_t* optL } return 0; } - pr.skip(ah.d_clen); + packetReader.skip(recordHeader.d_clen); } return ENOENT; @@ -395,21 +392,22 @@ int getEDNSOptionsStart(const PacketBuffer& packet, const size_t offset, uint16_ { assert(optRDPosition != nullptr); assert(remaining != nullptr); - const dnsheader_aligned dh(packet.data()); + const dnsheader_aligned dnsHeader(packet.data()); if (offset >= packet.size()) { return ENOENT; } - if (ntohs(dh->qdcount) != 1 || ntohs(dh->ancount) != 0 || ntohs(dh->arcount) != 1 || ntohs(dh->nscount) != 0) { + if (ntohs(dnsHeader->qdcount) != 1 || ntohs(dnsHeader->ancount) != 0 || ntohs(dnsHeader->arcount) != 1 || ntohs(dnsHeader->nscount) != 0) { return ENOENT; } size_t pos = sizeof(dnsheader) + offset; pos += DNS_TYPE_SIZE + DNS_CLASS_SIZE; - if (pos >= packet.size()) + if (pos >= packet.size()) { return ENOENT; + } if ((pos + /* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE) >= packet.size()) { return ENOENT; @@ -448,26 +446,28 @@ void generateECSOption(const ComboAddress& source, string& res, uint16_t ECSPref bool generateOptRR(const std::string& optRData, PacketBuffer& res, size_t maximumSize, uint16_t udpPayloadSize, uint8_t ednsrcode, bool dnssecOK) { const uint8_t name = 0; - dnsrecordheader dh; - EDNS0Record edns0; + dnsrecordheader dnsHeader{}; + EDNS0Record edns0{}; edns0.extRCode = ednsrcode; edns0.version = 0; edns0.extFlags = dnssecOK ? htons(EDNS_HEADER_FLAG_DO) : 0; - if ((maximumSize - res.size()) < (sizeof(name) + sizeof(dh) + optRData.length())) { + if ((maximumSize - res.size()) < (sizeof(name) + sizeof(dnsHeader) + optRData.length())) { return false; } - dh.d_type = htons(QType::OPT); - dh.d_class = htons(udpPayloadSize); - static_assert(sizeof(EDNS0Record) == sizeof(dh.d_ttl), "sizeof(EDNS0Record) must match sizeof(dnsrecordheader.d_ttl)"); - memcpy(&dh.d_ttl, &edns0, sizeof edns0); - dh.d_clen = htons(static_cast(optRData.length())); + dnsHeader.d_type = htons(QType::OPT); + dnsHeader.d_class = htons(udpPayloadSize); + static_assert(sizeof(EDNS0Record) == sizeof(dnsHeader.d_ttl), "sizeof(EDNS0Record) must match sizeof(dnsrecordheader.d_ttl)"); + memcpy(&dnsHeader.d_ttl, &edns0, sizeof edns0); + dnsHeader.d_clen = htons(static_cast(optRData.length())); - res.reserve(res.size() + sizeof(name) + sizeof(dh) + optRData.length()); + res.reserve(res.size() + sizeof(name) + sizeof(dnsHeader) + optRData.length()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-bounds-pointer-arithmetic) res.insert(res.end(), reinterpret_cast(&name), reinterpret_cast(&name) + sizeof(name)); - res.insert(res.end(), reinterpret_cast(&dh), reinterpret_cast(&dh) + sizeof(dh)); - res.insert(res.end(), reinterpret_cast(optRData.data()), reinterpret_cast(optRData.data()) + optRData.length()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-bounds-pointer-arithmetic) + res.insert(res.end(), reinterpret_cast(&dnsHeader), reinterpret_cast(&dnsHeader) + sizeof(dnsHeader)); + res.insert(res.end(), optRData.begin(), optRData.end()); return true; } @@ -514,31 +514,32 @@ static bool replaceEDNSClientSubnetOption(PacketBuffer& packet, size_t maximumSi /* This function looks for an OPT RR, return true if a valid one was found (even if there was no options) and false otherwise. */ -bool parseEDNSOptions(const DNSQuestion& dq) +bool parseEDNSOptions(const DNSQuestion& dnsQuestion) { - const auto dh = dq.getHeader(); - if (dq.ednsOptions != nullptr) { + const auto dnsHeader = dnsQuestion.getHeader(); + if (dnsQuestion.ednsOptions != nullptr) { return true; } - // dq.ednsOptions is mutable - dq.ednsOptions = std::make_unique(); + // dnsQuestion.ednsOptions is mutable + dnsQuestion.ednsOptions = std::make_unique(); - if (ntohs(dh->arcount) == 0) { + if (ntohs(dnsHeader->arcount) == 0) { /* nothing in additional so no EDNS */ return false; } - if (ntohs(dh->ancount) != 0 || ntohs(dh->nscount) != 0 || ntohs(dh->arcount) > 1) { - return slowParseEDNSOptions(dq.getData(), *dq.ednsOptions); + if (ntohs(dnsHeader->ancount) != 0 || ntohs(dnsHeader->nscount) != 0 || ntohs(dnsHeader->arcount) > 1) { + return slowParseEDNSOptions(dnsQuestion.getData(), *dnsQuestion.ednsOptions); } size_t remaining = 0; - uint16_t optRDPosition; - int res = getEDNSOptionsStart(dq.getData(), dq.ids.qname.wirelength(), &optRDPosition, &remaining); + uint16_t optRDPosition{}; + int res = getEDNSOptionsStart(dnsQuestion.getData(), dnsQuestion.ids.qname.wirelength(), &optRDPosition, &remaining); if (res == 0) { - res = getEDNSOptions(reinterpret_cast(&dq.getData().at(optRDPosition)), remaining, *dq.ednsOptions); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + res = getEDNSOptions(reinterpret_cast(&dnsQuestion.getData().at(optRDPosition)), remaining, *dnsQuestion.ednsOptions); return (res == 0); } @@ -553,6 +554,7 @@ static bool addECSToExistingOPT(PacketBuffer& packet, size_t maximumSize, const uint16_t oldRDLen = (packet.at(optRDLenPosition) * 256) + packet.at(optRDLenPosition + 1); if (packet.size() != (optRDLenPosition + sizeof(uint16_t) + oldRDLen)) { /* we are supposed to be the last record, do we have some trailing data to remove? */ + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) uint32_t realPacketLen = getDNSPacketLength(reinterpret_cast(packet.data()), packet.size()); packet.resize(realPacketLen); } @@ -593,9 +595,9 @@ bool handleEDNSClientSubnet(PacketBuffer& packet, const size_t maximumSize, cons { assert(qnameWireLength <= packet.size()); - const dnsheader_aligned dh(packet.data()); + const dnsheader_aligned dnsHeader(packet.data()); - if (ntohs(dh->ancount) != 0 || ntohs(dh->nscount) != 0 || (ntohs(dh->arcount) != 0 && ntohs(dh->arcount) != 1)) { + if (ntohs(dnsHeader->ancount) != 0 || ntohs(dnsHeader->nscount) != 0 || (ntohs(dnsHeader->arcount) != 0 && ntohs(dnsHeader->arcount) != 1)) { PacketBuffer newContent; newContent.reserve(packet.size()); @@ -623,11 +625,12 @@ bool handleEDNSClientSubnet(PacketBuffer& packet, const size_t maximumSize, cons /* Careful, this code assumes that ANCOUNT == 0 && NSCOUNT == 0 */ size_t minimumPacketSize = sizeof(dnsheader) + qnameWireLength + sizeof(uint16_t) + sizeof(uint16_t); if (packet.size() > minimumPacketSize) { - if (ntohs(dh->arcount) == 0) { + if (ntohs(dnsHeader->arcount) == 0) { /* well now.. */ packet.resize(minimumPacketSize); } else { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) uint32_t realPacketLen = getDNSPacketLength(reinterpret_cast(packet.data()), packet.size()); packet.resize(realPacketLen); } @@ -638,7 +641,7 @@ bool handleEDNSClientSubnet(PacketBuffer& packet, const size_t maximumSize, cons size_t ecsOptionStartPosition = 0; size_t ecsOptionSize = 0; - + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) res = getEDNSOption(reinterpret_cast(&packet.at(optRDPosition)), remaining, EDNSOptionCode::ECS, &ecsOptionStartPosition, &ecsOptionSize); if (res == 0) { @@ -649,47 +652,42 @@ bool handleEDNSClientSubnet(PacketBuffer& packet, const size_t maximumSize, cons return replaceEDNSClientSubnetOption(packet, maximumSize, optRDPosition + ecsOptionStartPosition, ecsOptionSize, optRDPosition, newECSOption); } - else { - /* we have an EDNS OPT RR but no existing ECS option */ - return addECSToExistingOPT(packet, maximumSize, newECSOption, optRDPosition, ecsAdded); - } - return true; + /* we have an EDNS OPT RR but no existing ECS option */ + return addECSToExistingOPT(packet, maximumSize, newECSOption, optRDPosition, ecsAdded); } -bool handleEDNSClientSubnet(DNSQuestion& dq, bool& ednsAdded, bool& ecsAdded) +bool handleEDNSClientSubnet(DNSQuestion& dnsQuestion, bool& ednsAdded, bool& ecsAdded) { string newECSOption; - generateECSOption(dq.ecs ? dq.ecs->getNetwork() : dq.ids.origRemote, newECSOption, dq.ecs ? dq.ecs->getBits() : dq.ecsPrefixLength); + generateECSOption(dnsQuestion.ecs ? dnsQuestion.ecs->getNetwork() : dnsQuestion.ids.origRemote, newECSOption, dnsQuestion.ecs ? dnsQuestion.ecs->getBits() : dnsQuestion.ecsPrefixLength); - return handleEDNSClientSubnet(dq.getMutableData(), dq.getMaximumSize(), dq.ids.qname.wirelength(), ednsAdded, ecsAdded, dq.ecsOverride, newECSOption); + return handleEDNSClientSubnet(dnsQuestion.getMutableData(), dnsQuestion.getMaximumSize(), dnsQuestion.ids.qname.wirelength(), ednsAdded, ecsAdded, dnsQuestion.ecsOverride, newECSOption); } static int removeEDNSOptionFromOptions(unsigned char* optionsStart, const uint16_t optionsLen, const uint16_t optionCodeToRemove, uint16_t* newOptionsLen) { - unsigned char* p = optionsStart; + const pdns::views::UnsignedCharView view(optionsStart, optionsLen); size_t pos = 0; - while ((pos + 4) <= optionsLen) { - unsigned char* optionBegin = p; - const uint16_t optionCode = 0x100 * p[0] + p[1]; - p += sizeof(optionCode); + while ((pos + 4) <= view.size()) { + size_t optionBeginPos = pos; + const uint16_t optionCode = 0x100 * view.at(pos) + view.at(pos + 1); pos += sizeof(optionCode); - const uint16_t optionLen = 0x100 * p[0] + p[1]; - p += sizeof(optionLen); + const uint16_t optionLen = 0x100 * view.at(pos) + view.at(pos + 1); pos += sizeof(optionLen); - if ((pos + optionLen) > optionsLen) { + if ((pos + optionLen) > view.size()) { return EINVAL; } if (optionCode == optionCodeToRemove) { - if (pos + optionLen < optionsLen) { + if (pos + optionLen < view.size()) { /* move remaining options over the removed one, if any */ - memmove(optionBegin, p + optionLen, optionsLen - (pos + optionLen)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + memmove(optionsStart + optionBeginPos, optionsStart + pos + optionLen, optionsLen - (pos + optionLen)); } *newOptionsLen = optionsLen - (sizeof(optionCode) + sizeof(optionLen) + optionLen); return 0; } - p += optionLen; pos += optionLen; } return ENOENT; @@ -700,21 +698,26 @@ int removeEDNSOptionFromOPT(char* optStart, size_t* optLen, const uint16_t optio if (*optLen < optRecordMinimumSize) { return EINVAL; } - const unsigned char* end = (const unsigned char*)optStart + *optLen; - unsigned char* p = (unsigned char*)optStart + 9; - unsigned char* rdLenPtr = p; - uint16_t rdLen = (0x100 * p[0] + p[1]); - p += sizeof(rdLen); - if (p + rdLen != end) { + const pdns::views::UnsignedCharView view(optStart, *optLen); + /* skip the root label, qtype, qclass and TTL */ + size_t position = 9; + uint16_t rdLen = (0x100 * view.at(position) + view.at(position + 1)); + position += sizeof(rdLen); + if (position + rdLen != view.size()) { return EINVAL; } uint16_t newRdLen = 0; - int res = removeEDNSOptionFromOptions(p, rdLen, optionCodeToRemove, &newRdLen); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-bounds-pointer-arithmetic) + int res = removeEDNSOptionFromOptions(reinterpret_cast(optStart + position), rdLen, optionCodeToRemove, &newRdLen); if (res != 0) { return res; } *optLen -= (rdLen - newRdLen); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-bounds-pointer-arithmetic) + auto* rdLenPtr = reinterpret_cast(optStart + 9); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) rdLenPtr[0] = newRdLen / 0x100; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) rdLenPtr[1] = newRdLen % 0x100; return 0; } @@ -724,27 +727,27 @@ bool isEDNSOptionInOpt(const PacketBuffer& packet, const size_t optStart, const if (optLen < optRecordMinimumSize) { return false; } - size_t p = optStart + 9; - uint16_t rdLen = (0x100 * static_cast(packet.at(p)) + static_cast(packet.at(p + 1))); - p += sizeof(rdLen); + size_t position = optStart + 9; + uint16_t rdLen = (0x100 * static_cast(packet.at(position)) + static_cast(packet.at(position + 1))); + position += sizeof(rdLen); if (rdLen > (optLen - optRecordMinimumSize)) { return false; } - size_t rdEnd = p + rdLen; - while ((p + 4) <= rdEnd) { - const uint16_t optionCode = 0x100 * static_cast(packet.at(p)) + static_cast(packet.at(p + 1)); - p += sizeof(optionCode); - const uint16_t optionLen = 0x100 * static_cast(packet.at(p)) + static_cast(packet.at(p + 1)); - p += sizeof(optionLen); + size_t rdEnd = position + rdLen; + while ((position + 4) <= rdEnd) { + const uint16_t optionCode = 0x100 * static_cast(packet.at(position)) + static_cast(packet.at(position + 1)); + position += sizeof(optionCode); + const uint16_t optionLen = 0x100 * static_cast(packet.at(position)) + static_cast(packet.at(position + 1)); + position += sizeof(optionLen); - if ((p + optionLen) > rdEnd) { + if ((position + optionLen) > rdEnd) { return false; } if (optionCode == optionCodeToFind) { if (optContentStart != nullptr) { - *optContentStart = p; + *optContentStart = position; } if (optContentLen != nullptr) { @@ -753,7 +756,7 @@ bool isEDNSOptionInOpt(const PacketBuffer& packet, const size_t optStart, const return true; } - p += optionLen; + position += optionLen; } return false; } @@ -761,48 +764,51 @@ bool isEDNSOptionInOpt(const PacketBuffer& packet, const size_t optStart, const int rewriteResponseWithoutEDNSOption(const PacketBuffer& initialPacket, const uint16_t optionCodeToSkip, PacketBuffer& newContent) { assert(initialPacket.size() >= sizeof(dnsheader)); - const dnsheader_aligned dh(initialPacket.data()); + const dnsheader_aligned dnsHeader(initialPacket.data()); - if (ntohs(dh->arcount) == 0) + if (ntohs(dnsHeader->arcount) == 0) { return ENOENT; + } - if (ntohs(dh->qdcount) == 0) + if (ntohs(dnsHeader->qdcount) == 0) { return ENOENT; + } - PacketReader pr(std::string_view(reinterpret_cast(initialPacket.data()), initialPacket.size())); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + PacketReader packetReader(std::string_view(reinterpret_cast(initialPacket.data()), initialPacket.size())); size_t idx = 0; DNSName rrname; - uint16_t qdcount = ntohs(dh->qdcount); - uint16_t ancount = ntohs(dh->ancount); - uint16_t nscount = ntohs(dh->nscount); - uint16_t arcount = ntohs(dh->arcount); - uint16_t rrtype; - uint16_t rrclass; + uint16_t qdcount = ntohs(dnsHeader->qdcount); + uint16_t ancount = ntohs(dnsHeader->ancount); + uint16_t nscount = ntohs(dnsHeader->nscount); + uint16_t arcount = ntohs(dnsHeader->arcount); + uint16_t rrtype = 0; + uint16_t rrclass = 0; string blob; - struct dnsrecordheader ah; - - rrname = pr.getName(); - rrtype = pr.get16BitInt(); - rrclass = pr.get16BitInt(); - - GenericDNSPacketWriter pw(newContent, rrname, rrtype, rrclass, dh->opcode); - pw.getHeader()->id = dh->id; - pw.getHeader()->qr = dh->qr; - pw.getHeader()->aa = dh->aa; - pw.getHeader()->tc = dh->tc; - pw.getHeader()->rd = dh->rd; - pw.getHeader()->ra = dh->ra; - pw.getHeader()->ad = dh->ad; - pw.getHeader()->cd = dh->cd; - pw.getHeader()->rcode = dh->rcode; + dnsrecordheader recordHeader{}; + + rrname = packetReader.getName(); + rrtype = packetReader.get16BitInt(); + rrclass = packetReader.get16BitInt(); + + GenericDNSPacketWriter packetWriter(newContent, rrname, rrtype, rrclass, dnsHeader->opcode); + packetWriter.getHeader()->id = dnsHeader->id; + packetWriter.getHeader()->qr = dnsHeader->qr; + packetWriter.getHeader()->aa = dnsHeader->aa; + packetWriter.getHeader()->tc = dnsHeader->tc; + packetWriter.getHeader()->rd = dnsHeader->rd; + packetWriter.getHeader()->ra = dnsHeader->ra; + packetWriter.getHeader()->ad = dnsHeader->ad; + packetWriter.getHeader()->cd = dnsHeader->cd; + packetWriter.getHeader()->rcode = dnsHeader->rcode; /* consume remaining qd if any */ if (qdcount > 1) { for (idx = 1; idx < qdcount; idx++) { - rrname = pr.getName(); - rrtype = pr.get16BitInt(); - rrclass = pr.get16BitInt(); + rrname = packetReader.getName(); + rrtype = packetReader.get16BitInt(); + rrclass = packetReader.get16BitInt(); (void)rrtype; (void)rrclass; } @@ -810,49 +816,50 @@ int rewriteResponseWithoutEDNSOption(const PacketBuffer& initialPacket, const ui /* copy AN and NS */ for (idx = 0; idx < ancount; idx++) { - rrname = pr.getName(); - pr.getDnsrecordheader(ah); + rrname = packetReader.getName(); + packetReader.getDnsrecordheader(recordHeader); - pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::ANSWER, true); - pr.xfrBlob(blob); - pw.xfrBlob(blob); + packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ANSWER, true); + packetReader.xfrBlob(blob); + packetWriter.xfrBlob(blob); } for (idx = 0; idx < nscount; idx++) { - rrname = pr.getName(); - pr.getDnsrecordheader(ah); + rrname = packetReader.getName(); + packetReader.getDnsrecordheader(recordHeader); - pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::AUTHORITY, true); - pr.xfrBlob(blob); - pw.xfrBlob(blob); + packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::AUTHORITY, true); + packetReader.xfrBlob(blob); + packetWriter.xfrBlob(blob); } /* consume AR, looking for OPT */ for (idx = 0; idx < arcount; idx++) { - rrname = pr.getName(); - pr.getDnsrecordheader(ah); + rrname = packetReader.getName(); + packetReader.getDnsrecordheader(recordHeader); - if (ah.d_type != QType::OPT) { - pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::ADDITIONAL, true); - pr.xfrBlob(blob); - pw.xfrBlob(blob); + if (recordHeader.d_type != QType::OPT) { + packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ADDITIONAL, true); + packetReader.xfrBlob(blob); + packetWriter.xfrBlob(blob); } else { - pw.startRecord(rrname, ah.d_type, ah.d_ttl, ah.d_class, DNSResourceRecord::ADDITIONAL, false); - pr.xfrBlob(blob); + packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ADDITIONAL, false); + packetReader.xfrBlob(blob); uint16_t rdLen = blob.length(); - removeEDNSOptionFromOptions((unsigned char*)blob.c_str(), rdLen, optionCodeToSkip, &rdLen); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + removeEDNSOptionFromOptions(reinterpret_cast(blob.data()), rdLen, optionCodeToSkip, &rdLen); /* xfrBlob(string, size) completely ignores size.. */ if (rdLen > 0) { blob.resize((size_t)rdLen); - pw.xfrBlob(blob); + packetWriter.xfrBlob(blob); } else { - pw.commit(); + packetWriter.commit(); } } } - pw.commit(); + packetWriter.commit(); return 0; } @@ -875,15 +882,15 @@ bool addEDNS(PacketBuffer& packet, size_t maximumSize, bool dnssecOK, uint16_t p This function keeps the existing header and DNSSECOK bit (if any) but wipes anything else, generating a NXD or NODATA answer with a SOA record in the additional section (or optionally the authority section for a full cacheable NXDOMAIN/NODATA). */ -bool setNegativeAndAdditionalSOA(DNSQuestion& dq, bool nxd, const DNSName& zone, uint32_t ttl, const DNSName& mname, const DNSName& rname, uint32_t serial, uint32_t refresh, uint32_t retry, uint32_t expire, uint32_t minimum, bool soaInAuthoritySection) +bool setNegativeAndAdditionalSOA(DNSQuestion& dnsQuestion, bool nxd, const DNSName& zone, uint32_t ttl, const DNSName& mname, const DNSName& rname, uint32_t serial, uint32_t refresh, uint32_t retry, uint32_t expire, uint32_t minimum, bool soaInAuthoritySection) { - auto& packet = dq.getMutableData(); - auto dh = dq.getHeader(); - if (ntohs(dh->qdcount) != 1) { + auto& packet = dnsQuestion.getMutableData(); + auto dnsHeader = dnsQuestion.getHeader(); + if (ntohs(dnsHeader->qdcount) != 1) { return false; } - size_t queryPartSize = sizeof(dnsheader) + dq.ids.qname.wirelength() + DNS_TYPE_SIZE + DNS_CLASS_SIZE; + size_t queryPartSize = sizeof(dnsheader) + dnsQuestion.ids.qname.wirelength() + DNS_TYPE_SIZE + DNS_CLASS_SIZE; if (packet.size() < queryPartSize) { /* something is already wrong, don't build on flawed foundations */ return false; @@ -898,10 +905,11 @@ bool setNegativeAndAdditionalSOA(DNSQuestion& dq, bool nxd, const DNSName& zone, if (g_addEDNSToSelfGeneratedResponses) { uint16_t payloadSize = 0; - uint16_t z = 0; - hadEDNS = getEDNSUDPPayloadSizeAndZ(reinterpret_cast(packet.data()), packet.size(), &payloadSize, &z); + uint16_t zValue = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + hadEDNS = getEDNSUDPPayloadSizeAndZ(reinterpret_cast(packet.data()), packet.size(), &payloadSize, &zValue); if (hadEDNS) { - dnssecOK = z & EDNS_HEADER_FLAG_DO; + dnssecOK = (zValue & EDNS_HEADER_FLAG_DO) != 0; } } @@ -932,16 +940,25 @@ bool setNegativeAndAdditionalSOA(DNSQuestion& dq, bool nxd, const DNSName& zone, std::string soa; soa.reserve(soaSize); soa.append(zone.toDNSString()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) soa.append(reinterpret_cast(&qtype), sizeof(qtype)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) soa.append(reinterpret_cast(&qclass), sizeof(qclass)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) soa.append(reinterpret_cast(&ttl), sizeof(ttl)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) soa.append(reinterpret_cast(&rdLength), sizeof(rdLength)); soa.append(mname.toDNSString()); soa.append(rname.toDNSString()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) soa.append(reinterpret_cast(&serial), sizeof(serial)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) soa.append(reinterpret_cast(&refresh), sizeof(refresh)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) soa.append(reinterpret_cast(&retry), sizeof(retry)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) soa.append(reinterpret_cast(&expire), sizeof(expire)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) soa.append(reinterpret_cast(&minimum), sizeof(minimum)); if (soa.size() != soaSize) { @@ -965,20 +982,20 @@ bool setNegativeAndAdditionalSOA(DNSQuestion& dq, bool nxd, const DNSName& zone, if (hadEDNS) { /* now we need to add a new OPT record */ - return addEDNS(packet, dq.getMaximumSize(), dnssecOK, g_PayloadSizeSelfGenAnswers, dq.ednsRCode); + return addEDNS(packet, dnsQuestion.getMaximumSize(), dnssecOK, g_PayloadSizeSelfGenAnswers, dnsQuestion.ednsRCode); } return true; } -bool addEDNSToQueryTurnedResponse(DNSQuestion& dq) +bool addEDNSToQueryTurnedResponse(DNSQuestion& dnsQuestion) { - uint16_t optRDPosition; + uint16_t optRDPosition{}; /* remaining is at least the size of the rdlen + the options if any + the following records if any */ size_t remaining = 0; - auto& packet = dq.getMutableData(); - int res = getEDNSOptionsStart(packet, dq.ids.qname.wirelength(), &optRDPosition, &remaining); + auto& packet = dnsQuestion.getMutableData(); + int res = getEDNSOptionsStart(packet, dnsQuestion.ids.qname.wirelength(), &optRDPosition, &remaining); if (res != 0) { /* if the initial query did not have EDNS0, we are done */ @@ -991,12 +1008,11 @@ bool addEDNSToQueryTurnedResponse(DNSQuestion& dq) return false; } - uint8_t* optRDLen = &packet.at(optRDPosition); - uint8_t* optPtr = (optRDLen - (/* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE + /* Z */ 2)); + const size_t optPosition = (optRDPosition - (/* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE + /* Z */ 2)); - const uint8_t* zPtr = optPtr + /* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE; - uint16_t z = 0x100 * (*zPtr) + *(zPtr + 1); - bool dnssecOK = z & EDNS_HEADER_FLAG_DO; + size_t zPosition = optPosition + /* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE; + uint16_t zValue = 0x100 * packet.at(zPosition) + packet.at(zPosition + 1); + bool dnssecOK = (zValue & EDNS_HEADER_FLAG_DO) != 0; /* remove the existing OPT record, and everything else that follows (any SIG or TSIG would be useless anyway) */ packet.resize(packet.size() - existingOptLen); @@ -1007,7 +1023,7 @@ bool addEDNSToQueryTurnedResponse(DNSQuestion& dq) if (g_addEDNSToSelfGeneratedResponses) { /* now we need to add a new OPT record */ - return addEDNS(packet, dq.getMaximumSize(), dnssecOK, g_PayloadSizeSelfGenAnswers, dq.ednsRCode); + return addEDNS(packet, dnsQuestion.getMaximumSize(), dnssecOK, g_PayloadSizeSelfGenAnswers, dnsQuestion.ednsRCode); } /* otherwise we are just fine */ @@ -1015,26 +1031,25 @@ bool addEDNSToQueryTurnedResponse(DNSQuestion& dq) } // goal in life - if you send us a reasonably normal packet, we'll get Z for you, otherwise 0 -int getEDNSZ(const DNSQuestion& dq) +int getEDNSZ(const DNSQuestion& dnsQuestion) { try { - const auto& dh = dq.getHeader(); - if (ntohs(dh->qdcount) != 1 || dh->ancount != 0 || ntohs(dh->arcount) != 1 || dh->nscount != 0) { + const auto& dnsHeader = dnsQuestion.getHeader(); + if (ntohs(dnsHeader->qdcount) != 1 || dnsHeader->ancount != 0 || ntohs(dnsHeader->arcount) != 1 || dnsHeader->nscount != 0) { return 0; } - if (dq.getData().size() <= sizeof(dnsheader)) { + if (dnsQuestion.getData().size() <= sizeof(dnsheader)) { return 0; } - size_t pos = sizeof(dnsheader) + dq.ids.qname.wirelength() + DNS_TYPE_SIZE + DNS_CLASS_SIZE; + size_t pos = sizeof(dnsheader) + dnsQuestion.ids.qname.wirelength() + DNS_TYPE_SIZE + DNS_CLASS_SIZE; - if (dq.getData().size() <= (pos + /* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE)) { + if (dnsQuestion.getData().size() <= (pos + /* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE)) { return 0; } - auto& packet = dq.getData(); - + const auto& packet = dnsQuestion.getData(); if (packet.at(pos) != 0) { /* not root, so not a valid OPT record */ return 0; @@ -1050,30 +1065,25 @@ int getEDNSZ(const DNSQuestion& dq) return 0; } - const uint8_t* z = &packet.at(pos + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE); - return 0x100 * (*z) + *(z + 1); + return 0x100 * packet.at(pos + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE) + packet.at(pos + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE + 1); } catch (...) { return 0; } } -bool queryHasEDNS(const DNSQuestion& dq) +bool queryHasEDNS(const DNSQuestion& dnsQuestion) { - uint16_t optRDPosition; + uint16_t optRDPosition = 0; size_t ecsRemaining = 0; - int res = getEDNSOptionsStart(dq.getData(), dq.ids.qname.wirelength(), &optRDPosition, &ecsRemaining); - if (res == 0) { - return true; - } - - return false; + int res = getEDNSOptionsStart(dnsQuestion.getData(), dnsQuestion.ids.qname.wirelength(), &optRDPosition, &ecsRemaining); + return res == 0; } bool getEDNS0Record(const PacketBuffer& packet, EDNS0Record& edns0) { - uint16_t optStart; + uint16_t optStart = 0; size_t optLen = 0; bool last = false; int res = locateEDNSOptRR(packet, &optStart, &optLen, &last); @@ -1097,41 +1107,41 @@ bool getEDNS0Record(const PacketBuffer& packet, EDNS0Record& edns0) return true; } -bool setEDNSOption(DNSQuestion& dq, uint16_t ednsCode, const std::string& ednsData) +bool setEDNSOption(DNSQuestion& dnsQuestion, uint16_t ednsCode, const std::string& ednsData) { std::string optRData; generateEDNSOption(ednsCode, ednsData, optRData); - if (dq.getHeader()->arcount) { + if (dnsQuestion.getHeader()->arcount != 0) { bool ednsAdded = false; bool optionAdded = false; PacketBuffer newContent; - newContent.reserve(dq.getData().size()); + newContent.reserve(dnsQuestion.getData().size()); - if (!slowRewriteEDNSOptionInQueryWithRecords(dq.getData(), newContent, ednsAdded, ednsCode, optionAdded, true, optRData)) { + if (!slowRewriteEDNSOptionInQueryWithRecords(dnsQuestion.getData(), newContent, ednsAdded, ednsCode, optionAdded, true, optRData)) { return false; } - if (newContent.size() > dq.getMaximumSize()) { + if (newContent.size() > dnsQuestion.getMaximumSize()) { return false; } - dq.getMutableData() = std::move(newContent); - if (!dq.ids.ednsAdded && ednsAdded) { - dq.ids.ednsAdded = true; + dnsQuestion.getMutableData() = std::move(newContent); + if (!dnsQuestion.ids.ednsAdded && ednsAdded) { + dnsQuestion.ids.ednsAdded = true; } return true; } - auto& data = dq.getMutableData(); - if (generateOptRR(optRData, data, dq.getMaximumSize(), g_EdnsUDPPayloadSize, 0, false)) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [](dnsheader& header) { + auto& data = dnsQuestion.getMutableData(); + if (generateOptRR(optRData, data, dnsQuestion.getMaximumSize(), g_EdnsUDPPayloadSize, 0, false)) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [](dnsheader& header) { header.arcount = htons(1); return true; }); // make sure that any EDNS sent by the backend is removed before forwarding the response to the client - dq.ids.ednsAdded = true; + dnsQuestion.ids.ednsAdded = true; } return true; @@ -1146,7 +1156,7 @@ bool setInternalQueryRCode(InternalQueryState& state, PacketBuffer& buffer, uint return false; } - EDNS0Record edns0; + EDNS0Record edns0{}; bool hadEDNS = false; if (clearAnswers) { hadEDNS = getEDNS0Record(buffer, edns0); @@ -1170,8 +1180,8 @@ bool setInternalQueryRCode(InternalQueryState& state, PacketBuffer& buffer, uint if (clearAnswers) { buffer.resize(sizeof(dnsheader) + qnameLength + sizeof(uint16_t) + sizeof(uint16_t)); if (hadEDNS) { - DNSQuestion dq(state, buffer); - if (!addEDNS(buffer, dq.getMaximumSize(), edns0.extFlags & htons(EDNS_HEADER_FLAG_DO), g_PayloadSizeSelfGenAnswers, 0)) { + DNSQuestion dnsQuestion(state, buffer); + if (!addEDNS(buffer, dnsQuestion.getMaximumSize(), (edns0.extFlags & htons(EDNS_HEADER_FLAG_DO)) != 0, g_PayloadSizeSelfGenAnswers, 0)) { return false; } } diff --git a/pdns/dnsdistdist/dnsdist-ecs.hh b/pdns/dnsdistdist/dnsdist-ecs.hh index 3af754d8af42..94eccc1a1d7b 100644 --- a/pdns/dnsdistdist/dnsdist-ecs.hh +++ b/pdns/dnsdistdist/dnsdist-ecs.hh @@ -44,19 +44,19 @@ int rewriteResponseWithoutEDNSOption(const PacketBuffer& initialPacket, const ui int getEDNSOptionsStart(const PacketBuffer& packet, const size_t offset, uint16_t* optRDPosition, size_t* remaining); bool isEDNSOptionInOpt(const PacketBuffer& packet, const size_t optStart, const size_t optLen, const uint16_t optionCodeToFind, size_t* optContentStart = nullptr, uint16_t* optContentLen = nullptr); bool addEDNS(PacketBuffer& packet, size_t maximumSize, bool dnssecOK, uint16_t payloadSize, uint8_t ednsrcode); -bool addEDNSToQueryTurnedResponse(DNSQuestion& dq); -bool setNegativeAndAdditionalSOA(DNSQuestion& dq, bool nxd, const DNSName& zone, uint32_t ttl, const DNSName& mname, const DNSName& rname, uint32_t serial, uint32_t refresh, uint32_t retry, uint32_t expire, uint32_t minimum, bool soaInAuthoritySection); +bool addEDNSToQueryTurnedResponse(DNSQuestion& dnsQuestion); +bool setNegativeAndAdditionalSOA(DNSQuestion& dnsQuestion, bool nxd, const DNSName& zone, uint32_t ttl, const DNSName& mname, const DNSName& rname, uint32_t serial, uint32_t refresh, uint32_t retry, uint32_t expire, uint32_t minimum, bool soaInAuthoritySection); -bool handleEDNSClientSubnet(DNSQuestion& dq, bool& ednsAdded, bool& ecsAdded); +bool handleEDNSClientSubnet(DNSQuestion& dnsQuestion, bool& ednsAdded, bool& ecsAdded); bool handleEDNSClientSubnet(PacketBuffer& packet, size_t maximumSize, size_t qnameWireLength, bool& ednsAdded, bool& ecsAdded, bool overrideExisting, const string& newECSOption); -bool parseEDNSOptions(const DNSQuestion& dq); +bool parseEDNSOptions(const DNSQuestion& dnsQuestion); -int getEDNSZ(const DNSQuestion& dq); -bool queryHasEDNS(const DNSQuestion& dq); +int getEDNSZ(const DNSQuestion& dnsQuestion); +bool queryHasEDNS(const DNSQuestion& dnsQuestion); bool getEDNS0Record(const PacketBuffer& packet, EDNS0Record& edns0); -bool setEDNSOption(DNSQuestion& dq, uint16_t ednsCode, const std::string& data); +bool setEDNSOption(DNSQuestion& dnsQuestion, uint16_t ednsCode, const std::string& data); struct InternalQueryState; namespace dnsdist From cf8f0fe366893b4a138922692a27f297a8a4aca2 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Wed, 6 Mar 2024 15:09:07 +0100 Subject: [PATCH 22/25] dnsdist: Delint dnsdist-web.cc --- pdns/dnsdistdist/dnsdist-web.cc | 300 +++++++++++++++++--------------- pdns/dnsdistdist/dnsdist-web.hh | 2 +- pdns/dnsdistdist/incfiles | 2 +- 3 files changed, 161 insertions(+), 143 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-web.cc b/pdns/dnsdistdist/dnsdist-web.cc index 7462c43bf11d..12bedb622e7a 100644 --- a/pdns/dnsdistdist/dnsdist-web.cc +++ b/pdns/dnsdistdist/dnsdist-web.cc @@ -99,20 +99,25 @@ std::string getWebserverConfig() class WebClientConnection { public: - WebClientConnection(const ComboAddress& client, int fd) : - d_client(client), d_socket(fd) + WebClientConnection(const ComboAddress& client, int socketDesc) : + d_client(client), d_socket(socketDesc) { if (!s_connManager.registerConnection()) { throw std::runtime_error("Too many concurrent web client connections"); } } - WebClientConnection(WebClientConnection&& rhs) : + WebClientConnection(WebClientConnection&& rhs) noexcept : d_client(rhs.d_client), d_socket(std::move(rhs.d_socket)) { } - WebClientConnection(const WebClientConnection&) = delete; WebClientConnection& operator=(const WebClientConnection&) = delete; + WebClientConnection& operator=(WebClientConnection&& rhs) noexcept + { + d_client = rhs.d_client; + d_socket = std::move(rhs.d_socket); + return *this; + } ~WebClientConnection() { @@ -121,12 +126,12 @@ class WebClientConnection } } - const Socket& getSocket() const + [[nodiscard]] const Socket& getSocket() const { return d_socket; } - const ComboAddress& getClient() const + [[nodiscard]] const ComboAddress& getClient() const { return d_client; } @@ -291,12 +296,12 @@ static bool checkWebPassword(const YaHTTP::Request& req, const std::unique_ptr basicStr{'b', 'a', 's', 'i', 'c', ' ', '\0'}; 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); + if (header != req.headers.end() && toLower(header->second).find(basicStr.data()) == 0) { + string cookie = header->second.substr(basicStr.size() - 1); string plain; B64Decode(cookie, plain); @@ -412,25 +417,26 @@ static void addSecurityHeaders(YaHTTP::Response& resp, const boost::optionalfind(h.first); + const auto& custom = customHeaders->find(header.first); if (custom != customHeaders->end()) { continue; } } - resp.headers[h.first] = h.second; + resp.headers[header.first] = header.second; } } static void addCustomHeaders(YaHTTP::Response& resp, const boost::optional>& customHeaders) { - if (!customHeaders) + if (!customHeaders) { return; + } - for (const auto& c : *customHeaders) { - if (!c.second.empty()) { - resp.headers[c.first] = c.second; + for (const auto& custom : *customHeaders) { + if (!custom.second.empty()) { + resp.headers[custom.first] = custom.second; } } } @@ -443,15 +449,15 @@ static json11::Json::array someResponseRulesToJson(GlobalStateHolder>* int num = 0; auto localResponseRules = someResponseRules->getLocal(); responseRules.reserve(localResponseRules->size()); - for (const auto& a : *localResponseRules) { - responseRules.push_back(Json::object{ + for (const auto& rule : *localResponseRules) { + responseRules.emplace_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()}, + {"creationOrder", static_cast(rule.d_creationOrder)}, + {"uuid", boost::uuids::to_string(rule.d_id)}, + {"name", rule.d_name}, + {"matches", static_cast(rule.d_rule->d_matches)}, + {"rule", rule.d_rule->toString()}, + {"action", rule.d_action->toString()}, }); } return responseRules; @@ -463,8 +469,8 @@ static void addRulesToPrometheusOutput(std::ostringstream& output, GlobalStateHo { 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"; + std::string identifier = !entry.d_name.empty() ? entry.d_name : boost::uuids::to_string(entry.d_id); + output << "dnsdist_rule_hits{id=\"" << identifier << "\"} " << entry.d_rule->d_matches << "\n"; } } @@ -626,7 +632,7 @@ static void handlePrometheus(const YaHTTP::Request& req, YaHTTP::Response& resp) boost::replace_all(serverName, ".", "_"); - const std::string label = boost::str(boost::format("{server=\"%1%\",address=\"%2%\"}") + const std::string label = boost::str(boost::format(R"({server="%1%",address="%2%"})") % serverName % state->d_config.remote.toStringWithPort()); output << statesbase << "status" << label << " " << (state->isUp() ? "1" : "0") << "\n"; @@ -704,19 +710,22 @@ static void handlePrometheus(const YaHTTP::Request& req, YaHTTP::Response& resp) std::map frontendDuplicates; for (const auto& front : g_frontends) { - if (front->udpFD == -1 && front->tcpFD == -1) + if (front->udpFD == -1 && front->tcpFD == -1) { continue; + } const string frontName = front->local.toStringWithPort(); const string proto = front->getType(); - const string fullName = frontName + "_" + proto; + string fullName = frontName; + fullName += "_"; + fullName += 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%\"} ") + const std::string label = boost::str(boost::format(R"({frontend="%1%",proto="%2%",thread="%3%"} )") % frontName % proto % threadNumber); output << frontsbase << "queries" << label << front->queries.load() << "\n"; @@ -738,11 +747,11 @@ static void handlePrometheus(const YaHTTP::Request& req, YaHTTP::Response& resp) 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"; + output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",tls="tls10"} )" << front->tls10queries.load() << "\n"; + output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",tls="tls11"} )" << front->tls11queries.load() << "\n"; + output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",tls="tls12"} )" << front->tls12queries.load() << "\n"; + output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",tls="tls13"} )" << front->tls13queries.load() << "\n"; + output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",tls="unknown"} )" << front->tlsUnknownqueries.load() << "\n"; const TLSErrorCounters* errorCounters = nullptr; if (front->tlsFrontend != nullptr) { @@ -753,14 +762,14 @@ static void handlePrometheus(const YaHTTP::Request& req, YaHTTP::Response& resp) } 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 << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",error="dhKeyTooSmall"} )" << errorCounters->d_dhKeyTooSmall << "\n"; + output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",error="inappropriateFallBack"} )" << errorCounters->d_inappropriateFallBack << "\n"; + output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",error="noSharedCipher"} )" << errorCounters->d_noSharedCipher << "\n"; + output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",error="unknownCipherType"} )" << errorCounters->d_unknownCipherType << "\n"; + output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",error="unknownKeyExchangeType"} )" << errorCounters->d_unknownKeyExchangeType << "\n"; + output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",error="unknownProtocol"} )" << errorCounters->d_unknownProtocol << "\n"; + output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",error="unsupportedEC"} )" << errorCounters->d_unsupportedEC << "\n"; + output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << R"(",error="unsupportedProtocol"} )" << errorCounters->d_unsupportedProtocol << "\n"; } } } @@ -794,7 +803,7 @@ static void handlePrometheus(const YaHTTP::Request& req, YaHTTP::Response& resp) threadNumber = dupPair.first->second; ++(dupPair.first->second); } - const std::string addrlabel = boost::str(boost::format("frontend=\"%1%\",thread=\"%2%\"") % frontName % threadNumber); + const std::string addrlabel = boost::str(boost::format(R"(frontend="%1%",thread="%2%")") % frontName % threadNumber); const std::string label = "{" + addrlabel + "} "; output << frontsbase << "http_connects" << label << doh->d_httpconnects << "\n"; @@ -810,18 +819,18 @@ static void handlePrometheus(const YaHTTP::Request& req, YaHTTP::Response& resp) 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"; + output << frontsbase << R"(doh_version_status_responses{httpversion="1",status="200",)" << addrlabel << "} " << doh->d_http1Stats.d_nb200Responses << "\n"; + output << frontsbase << R"(doh_version_status_responses{httpversion="1",status="400",)" << addrlabel << "} " << doh->d_http1Stats.d_nb400Responses << "\n"; + output << frontsbase << R"(doh_version_status_responses{httpversion="1",status="403",)" << addrlabel << "} " << doh->d_http1Stats.d_nb403Responses << "\n"; + output << frontsbase << R"(doh_version_status_responses{httpversion="1",status="500",)" << addrlabel << "} " << doh->d_http1Stats.d_nb500Responses << "\n"; + output << frontsbase << R"(doh_version_status_responses{httpversion="1",status="502",)" << addrlabel << "} " << doh->d_http1Stats.d_nb502Responses << "\n"; + output << frontsbase << R"(doh_version_status_responses{httpversion="1",status="other",)" << addrlabel << "} " << doh->d_http1Stats.d_nbOtherResponses << "\n"; + output << frontsbase << R"(doh_version_status_responses{httpversion="2",status="200",)" << addrlabel << "} " << doh->d_http2Stats.d_nb200Responses << "\n"; + output << frontsbase << R"(doh_version_status_responses{httpversion="2",status="400",)" << addrlabel << "} " << doh->d_http2Stats.d_nb400Responses << "\n"; + output << frontsbase << R"(doh_version_status_responses{httpversion="2",status="403",)" << addrlabel << "} " << doh->d_http2Stats.d_nb403Responses << "\n"; + output << frontsbase << R"(doh_version_status_responses{httpversion="2",status="500",)" << addrlabel << "} " << doh->d_http2Stats.d_nb500Responses << "\n"; + output << frontsbase << R"(doh_version_status_responses{httpversion="2",status="502",)" << addrlabel << "} " << doh->d_http2Stats.d_nb502Responses << "\n"; + output << frontsbase << R"(doh_version_status_responses{httpversion="2",status="other",)" << addrlabel << "} " << doh->d_http2Stats.d_nbOtherResponses << "\n"; } #endif /* HAVE_DNS_OVER_HTTPS */ @@ -973,7 +982,7 @@ static void handleJSONStats(const YaHTTP::Request& req, YaHTTP::Response& resp) Json::object obj; #ifndef DISABLE_DYNBLOCKS auto nmg = g_dynblockNMG.getLocal(); - struct timespec now; + timespec now{}; gettime(&now); for (const auto& entry : *nmg) { if (!(now < entry.second.until)) { @@ -1018,7 +1027,7 @@ static void handleJSONStats(const YaHTTP::Request& req, YaHTTP::Response& resp) else if (command == "ebpfblocklist") { Json::object obj; #ifdef HAVE_EBPF - struct timespec now; + timespec now{}; gettime(&now); for (const auto& dynbpf : g_dynBPFFilters) { std::vector> addrStats = dynbpf->getAddrStats(); @@ -1057,73 +1066,73 @@ static void handleJSONStats(const YaHTTP::Request& req, YaHTTP::Response& resp) } #endif /* DISABLE_BUILTIN_HTML */ -static void addServerToJSON(Json::array& servers, int id, const std::shared_ptr& a) +static void addServerToJSON(Json::array& servers, int identifier, const std::shared_ptr& backend) { string status; - if (a->d_config.availability == DownstreamState::Availability::Up) { + if (backend->d_config.availability == DownstreamState::Availability::Up) { status = "UP"; } - else if (a->d_config.availability == DownstreamState::Availability::Down) { + else if (backend->d_config.availability == DownstreamState::Availability::Down) { status = "DOWN"; } else { - status = (a->upStatus ? "up" : "down"); + status = (backend->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); + pools.reserve(backend->d_config.pools.size()); + for (const auto& pool : backend->d_config.pools) { + pools.emplace_back(pool); } Json::object server{ - {"id", id}, - {"name", a->getName()}, - {"address", a->d_config.remote.toStringWithPort()}, + {"id", identifier}, + {"name", backend->getName()}, + {"address", backend->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}, + {"protocol", backend->getProtocol().toPrettyString()}, + {"qps", (double)backend->queryLoad}, + {"qpsLimit", (double)backend->qps.getRate()}, + {"outstanding", (double)backend->outstanding}, + {"reuseds", (double)backend->reuseds}, + {"weight", (double)backend->d_config.d_weight}, + {"order", (double)backend->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}}; + {"latency", (double)(backend->latencyUsec / 1000.0)}, + {"queries", (double)backend->queries}, + {"responses", (double)backend->responses}, + {"nonCompliantResponses", (double)backend->nonCompliantResponses}, + {"sendErrors", (double)backend->sendErrors}, + {"tcpDiedSendingQuery", (double)backend->tcpDiedSendingQuery}, + {"tcpDiedReadingResponse", (double)backend->tcpDiedReadingResponse}, + {"tcpGaveUp", (double)backend->tcpGaveUp}, + {"tcpConnectTimeouts", (double)backend->tcpConnectTimeouts}, + {"tcpReadTimeouts", (double)backend->tcpReadTimeouts}, + {"tcpWriteTimeouts", (double)backend->tcpWriteTimeouts}, + {"tcpCurrentConnections", (double)backend->tcpCurrentConnections}, + {"tcpMaxConcurrentConnections", (double)backend->tcpMaxConcurrentConnections}, + {"tcpTooManyConcurrentConnections", (double)backend->tcpTooManyConcurrentConnections}, + {"tcpNewConnections", (double)backend->tcpNewConnections}, + {"tcpReusedConnections", (double)backend->tcpReusedConnections}, + {"tcpAvgQueriesPerConnection", (double)backend->tcpAvgQueriesPerConnection}, + {"tcpAvgConnectionDuration", (double)backend->tcpAvgConnectionDuration}, + {"tlsResumptions", (double)backend->tlsResumptions}, + {"tcpLatency", (double)(backend->latencyUsecTCP / 1000.0)}, + {"healthCheckFailures", (double)(backend->d_healthCheckMetrics.d_failures)}, + {"healthCheckFailuresParsing", (double)(backend->d_healthCheckMetrics.d_parseErrors)}, + {"healthCheckFailuresTimeout", (double)(backend->d_healthCheckMetrics.d_timeOuts)}, + {"healthCheckFailuresNetwork", (double)(backend->d_healthCheckMetrics.d_networkErrors)}, + {"healthCheckFailuresMismatch", (double)(backend->d_healthCheckMetrics.d_mismatchErrors)}, + {"healthCheckFailuresInvalid", (double)(backend->d_healthCheckMetrics.d_invalidResponseErrors)}, + {"dropRate", (double)backend->dropRate}}; /* sending a latency for a DOWN server doesn't make sense */ - if (a->d_config.availability == DownstreamState::Availability::Down) { + if (backend->d_config.availability == DownstreamState::Availability::Down) { server["latency"] = nullptr; server["tcpLatency"] = nullptr; } - servers.push_back(std::move(server)); + servers.emplace_back(std::move(server)); } static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp) @@ -1137,8 +1146,8 @@ static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp) { auto localServers = g_dstates.getLocal(); servers.reserve(localServers->size()); - for (const auto& a : *localServers) { - addServerToJSON(servers, num++, a); + for (const auto& server : *localServers) { + addServerToJSON(servers, num++, server); } } @@ -1146,8 +1155,9 @@ static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp) num = 0; frontends.reserve(g_frontends.size()); for (const auto& front : g_frontends) { - if (front->udpFD == -1 && front->tcpFD == -1) + if (front->udpFD == -1 && front->tcpFD == -1) { continue; + } Json::object frontend{ {"id", num++}, {"address", front->local.toStringWithPort()}, @@ -1193,7 +1203,7 @@ static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp) frontend["tlsHandshakeFailuresUnsupportedEC"] = (double)errorCounters->d_unsupportedEC; frontend["tlsHandshakeFailuresUnsupportedProtocol"] = (double)errorCounters->d_unsupportedProtocol; } - frontends.push_back(std::move(frontend)); + frontends.emplace_back(std::move(frontend)); } Json::array dohs; @@ -1251,7 +1261,7 @@ static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp) {"cacheInsertCollisions", (double)(cache ? cache->getInsertCollisions() : 0)}, {"cacheTTLTooShorts", (double)(cache ? cache->getTTLTooShorts() : 0)}, {"cacheCleanupCount", (double)(cache ? cache->getCleanupCount() : 0)}}; - pools.push_back(std::move(entry)); + pools.emplace_back(std::move(entry)); } } @@ -1262,17 +1272,17 @@ static void handleStats(const YaHTTP::Request& req, YaHTTP::Response& resp) auto localRules = g_ruleactions.getLocal(); num = 0; rules.reserve(localRules->size()); - for (const auto& a : *localRules) { + for (const auto& lrule : *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)); + {"creationOrder", (double)lrule.d_creationOrder}, + {"uuid", boost::uuids::to_string(lrule.d_id)}, + {"name", lrule.d_name}, + {"matches", (double)lrule.d_rule->d_matches}, + {"rule", lrule.d_rule->toString()}, + {"action", lrule.d_action->toString()}, + {"action-stats", lrule.d_action->getStats()}}; + rules.emplace_back(std::move(rule)); } } auto responseRules = someResponseRulesToJson(&g_respruleactions); @@ -1365,8 +1375,8 @@ static void handlePoolStats(const YaHTTP::Request& req, YaHTTP::Response& resp) Json::array servers; int num = 0; - for (const auto& a : *pool->getServers()) { - addServerToJSON(servers, num, a.second); + for (const auto& server : *pool->getServers()) { + addServerToJSON(servers, num, server.second); num++; } @@ -1623,6 +1633,7 @@ static void addRingEntryToList(const struct timespec& now, Json::array& list, co }; if constexpr (!response) { #if defined(DNSDIST_RINGS_WITH_MACADDRESS) + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) tmp.emplace("mac", entry.hasmac ? std::string(reinterpret_cast(entry.macaddress.data()), entry.macaddress.size()) : std::string()); #endif } @@ -1635,7 +1646,7 @@ static void addRingEntryToList(const struct timespec& now, Json::array& list, co auto server = entry.ds.toStringWithPort(); tmp.emplace("backend", server != "0.0.0.0:0" ? std::move(server) : "Cache"); } - list.push_back(std::move(tmp)); + list.emplace_back(std::move(tmp)); } static void handleRings(const YaHTTP::Request& req, YaHTTP::Response& resp) @@ -1733,12 +1744,18 @@ static void redirectToIndex(const YaHTTP::Request& req, YaHTTP::Response& resp) static void handleBuiltInFiles(const YaHTTP::Request& req, YaHTTP::Response& resp) { - if (req.url.path.empty() || !s_urlmap.count(req.url.path.c_str() + 1)) { + if (req.url.path.empty()) { + resp.status = 404; + return; + } + const auto url = std::string_view(req.url.path).substr(1); + auto urlMapIt = s_urlmap.find(url); + if (urlMapIt == s_urlmap.end()) { resp.status = 404; return; } - resp.body.assign(s_urlmap.at(req.url.path.c_str() + 1)); + resp.body.assign(urlMapIt->second); vector parts; stringtok(parts, req.url.path, "."); @@ -1749,10 +1766,10 @@ static void handleBuiltInFiles(const YaHTTP::Request& req, YaHTTP::Response& res {"png", "image/png"}, }; - const auto& it = contentTypeMap.find(parts.back()); - if (it != contentTypeMap.end()) { + const auto& contentTypeIt = contentTypeMap.find(parts.back()); + if (contentTypeIt != contentTypeMap.end()) { const string charset = "; charset=utf-8"; - resp.headers["Content-Type"] = it->second + charset; + resp.headers["Content-Type"] = contentTypeIt->second + charset; } resp.status = 200; @@ -1798,14 +1815,15 @@ static void connectionThread(WebClientConnection&& conn) YaHTTP::Request req; bool finished = false; + std::string buf; yarl.initialize(&req); while (!finished) { - int bytes; - char buf[1024]; - bytes = read(conn.getSocket().getHandle(), buf, sizeof(buf)); + ssize_t bytes{0}; + buf.resize(1024); + bytes = read(conn.getSocket().getHandle(), buf.data(), buf.size()); if (bytes > 0) { - string data = string(buf, bytes); - finished = yarl.feed(data); + buf.resize(static_cast(bytes)); + finished = yarl.feed(buf); } else { // read error OR EOF @@ -1837,7 +1855,7 @@ static void connectionThread(WebClientConnection&& conn) resp.status = 200; } else if (!handleAuthorization(req)) { - YaHTTP::strstr_map_t::iterator header = req.headers.find("authorization"); + auto 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()); } @@ -1849,9 +1867,9 @@ static void connectionThread(WebClientConnection&& conn) resp.status = 405; } else { - const auto it = s_webHandlers.find(req.url.path); - if (it != s_webHandlers.end()) { - it->second(req, resp); + const auto webHandlersIt = s_webHandlers.find(req.url.path); + if (webHandlersIt != s_webHandlers.end()) { + webHandlersIt->second(req, resp); } else { resp.status = 404; @@ -1899,7 +1917,7 @@ void setWebserverACL(const std::string& acl) g_webserverConfig.lock()->acl = std::move(newACL); } -void setWebserverCustomHeaders(const boost::optional> customHeaders) +void setWebserverCustomHeaders(const boost::optional>& customHeaders) { g_webserverConfig.lock()->customHeaders = customHeaders; } @@ -1939,19 +1957,19 @@ void dnsdistWebserverThread(int sock, const ComboAddress& local) for (;;) { try { ComboAddress remote(local); - int fd = SAccept(sock, remote); + int fileDesc = SAccept(sock, remote); if (!isClientAllowedByACL(remote)) { vinfolog("Connection to webserver from client %s is not allowed, closing", remote.toStringWithPort()); - close(fd); + close(fileDesc); continue; } - WebClientConnection conn(remote, fd); + WebClientConnection conn(remote, fileDesc); vinfolog("Got a connection to the webserver from %s", remote.toStringWithPort()); - std::thread t(connectionThread, std::move(conn)); - t.detach(); + std::thread connThr(connectionThread, std::move(conn)); + connThr.detach(); } catch (const std::exception& e) { vinfolog("Had an error accepting new webserver connection: %s", e.what()); diff --git a/pdns/dnsdistdist/dnsdist-web.hh b/pdns/dnsdistdist/dnsdist-web.hh index 7325025823d7..d707e464c52e 100644 --- a/pdns/dnsdistdist/dnsdist-web.hh +++ b/pdns/dnsdistdist/dnsdist-web.hh @@ -6,7 +6,7 @@ void setWebserverAPIKey(std::unique_ptr&& apiKey); void setWebserverPassword(std::unique_ptr&& password); void setWebserverACL(const std::string& acl); -void setWebserverCustomHeaders(const boost::optional > customHeaders); +void setWebserverCustomHeaders(const boost::optional >& customHeaders); void setWebserverAPIRequiresAuthentication(bool); void setWebserverDashboardRequiresAuthentication(bool); void setWebserverStatsRequireAuthentication(bool); diff --git a/pdns/dnsdistdist/incfiles b/pdns/dnsdistdist/incfiles index 9f96afe59a71..372baf36222b 100755 --- a/pdns/dnsdistdist/incfiles +++ b/pdns/dnsdistdist/incfiles @@ -16,7 +16,7 @@ do echo "};" done -echo "static const map s_urlmap={" +echo "static const map> s_urlmap={" for a in $(find ${DIR}html -type f | grep -v \~ | sort) do b=$(echo $a | sed s:${DIR}html/::g) From 28e599d1831a517765471d407132acd49c9f3b47 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Wed, 6 Mar 2024 16:46:29 +0100 Subject: [PATCH 23/25] dnsdist: Delint dnsdist-xpf.cc --- pdns/dnsdistdist/dnsdist-xpf.cc | 16 ++++++++++------ pdns/dnsdistdist/dnsdist-xpf.hh | 2 +- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-xpf.cc b/pdns/dnsdistdist/dnsdist-xpf.cc index 305bf0433e48..df560ac38da0 100644 --- a/pdns/dnsdistdist/dnsdist-xpf.cc +++ b/pdns/dnsdistdist/dnsdist-xpf.cc @@ -26,36 +26,40 @@ #include "dnsparser.hh" #include "xpf.hh" -bool addXPF(DNSQuestion& dq, uint16_t optionCode) +bool addXPF(DNSQuestion& dnsQuestion, uint16_t optionCode) { - std::string payload = generateXPFPayload(dq.overTCP(), dq.ids.origRemote, dq.ids.origDest); + std::string payload = generateXPFPayload(dnsQuestion.overTCP(), dnsQuestion.ids.origRemote, dnsQuestion.ids.origDest); uint8_t root = '\0'; - dnsrecordheader drh; + dnsrecordheader drh{}; drh.d_type = htons(optionCode); drh.d_class = htons(QClass::IN); drh.d_ttl = 0; drh.d_clen = htons(payload.size()); size_t recordHeaderLen = sizeof(root) + sizeof(drh); - if (!dq.hasRoomFor(payload.size() + recordHeaderLen)) { + if (!dnsQuestion.hasRoomFor(payload.size() + recordHeaderLen)) { return false; } size_t xpfSize = sizeof(root) + sizeof(drh) + payload.size(); - auto& data = dq.getMutableData(); + auto& data = dnsQuestion.getMutableData(); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) uint32_t realPacketLen = getDNSPacketLength(reinterpret_cast(data.data()), data.size()); data.resize(realPacketLen + xpfSize); size_t pos = realPacketLen; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) memcpy(reinterpret_cast(&data.at(pos)), &root, sizeof(root)); pos += sizeof(root); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) memcpy(reinterpret_cast(&data.at(pos)), &drh, sizeof(drh)); pos += sizeof(drh); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) memcpy(reinterpret_cast(&data.at(pos)), payload.data(), payload.size()); pos += payload.size(); (void)pos; - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [](dnsheader& header) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [](dnsheader& header) { header.arcount = htons(ntohs(header.arcount) + 1); return true; }); diff --git a/pdns/dnsdistdist/dnsdist-xpf.hh b/pdns/dnsdistdist/dnsdist-xpf.hh index 30de2234c0db..a3de71029ea4 100644 --- a/pdns/dnsdistdist/dnsdist-xpf.hh +++ b/pdns/dnsdistdist/dnsdist-xpf.hh @@ -23,4 +23,4 @@ #include "dnsdist.hh" -bool addXPF(DNSQuestion& dq, uint16_t optionCode); +bool addXPF(DNSQuestion& dnsQuestion, uint16_t optionCode); From 73cab2dfcf99ea269a42941f18d62479ba750cb1 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Wed, 6 Mar 2024 16:47:07 +0100 Subject: [PATCH 24/25] dnsdist: Delint dnsdist.cc --- pdns/dnsdistdist/dnsdist.cc | 575 ++++++++++++++++++------------------ pdns/dnsdistdist/dnsdist.hh | 6 +- 2 files changed, 295 insertions(+), 286 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist.cc b/pdns/dnsdistdist/dnsdist.cc index 089f7ef00751..0606d270c291 100644 --- a/pdns/dnsdistdist/dnsdist.cc +++ b/pdns/dnsdistdist/dnsdist.cc @@ -163,25 +163,28 @@ static constexpr size_t s_maxUDPResponsePacketSize{4096U}; static size_t const s_initialUDPPacketBufferSize = s_maxUDPResponsePacketSize + DNSCRYPT_MAX_RESPONSE_PADDING_AND_MAC_SIZE; static_assert(s_initialUDPPacketBufferSize <= UINT16_MAX, "Packet size should fit in a uint16_t"); -static ssize_t sendfromto(int sock, const void* data, size_t len, int flags, const ComboAddress& from, const ComboAddress& to) +static ssize_t sendfromto(int sock, const void* data, size_t len, int flags, const ComboAddress& from, const ComboAddress& dest) { if (from.sin4.sin_family == 0) { - return sendto(sock, data, len, flags, reinterpret_cast(&to), to.getSocklen()); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + return sendto(sock, data, len, flags, reinterpret_cast(&dest), dest.getSocklen()); } - struct msghdr msgh; - struct iovec iov; + msghdr msgh{}; + iovec iov{}; cmsgbuf_aligned cbuf; /* Set up iov and msgh structures. */ memset(&msgh, 0, sizeof(struct msghdr)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast): it's the API iov.iov_base = const_cast(data); iov.iov_len = len; msgh.msg_iov = &iov; msgh.msg_iovlen = 1; - msgh.msg_name = (struct sockaddr*)&to; - msgh.msg_namelen = to.getSocklen(); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-type-const-cast) + msgh.msg_name = const_cast(reinterpret_cast(&dest)); + msgh.msg_namelen = dest.getSocklen(); - if (from.sin4.sin_family) { + if (from.sin4.sin_family != 0) { addCMsgSrcAddr(&msgh, &cbuf, &from, 0); } else { @@ -195,10 +198,11 @@ static void truncateTC(PacketBuffer& packet, size_t maximumSize, unsigned int qn try { bool hadEDNS = false; uint16_t payloadSize = 0; - uint16_t z = 0; + uint16_t zValue = 0; if (g_addEDNSToSelfGeneratedResponses) { - hadEDNS = getEDNSUDPPayloadSizeAndZ(reinterpret_cast(packet.data()), packet.size(), &payloadSize, &z); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + hadEDNS = getEDNSUDPPayloadSizeAndZ(reinterpret_cast(packet.data()), packet.size(), &payloadSize, &zValue); } packet.resize(static_cast(sizeof(dnsheader) + qnameWireLength + DNS_TYPE_SIZE + DNS_CLASS_SIZE)); @@ -210,7 +214,7 @@ static void truncateTC(PacketBuffer& packet, size_t maximumSize, unsigned int qn }); if (hadEDNS) { - addEDNS(packet, maximumSize, z & EDNS_HEADER_FLAG_DO, payloadSize, 0); + addEDNS(packet, maximumSize, (zValue & EDNS_HEADER_FLAG_DO) != 0, payloadSize, 0); } } catch (...) { @@ -221,7 +225,7 @@ static void truncateTC(PacketBuffer& packet, size_t maximumSize, unsigned int qn #ifndef DISABLE_DELAY_PIPE struct DelayedPacket { - int fd; + int fd{-1}; PacketBuffer packet; ComboAddress destination; ComboAddress origDest; @@ -230,7 +234,7 @@ struct DelayedPacket ssize_t res = sendfromto(fd, packet.data(), packet.size(), 0, origDest, destination); if (res == -1) { int err = errno; - vinfolog("Error sending delayed response to %s: %s", destination.toStringWithPort(), strerror(err)); + vinfolog("Error sending delayed response to %s: %s", destination.toStringWithPort(), stringerror(err)); } } }; @@ -243,15 +247,17 @@ std::string DNSQuestion::getTrailingData() const // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) const auto* message = reinterpret_cast(this->getData().data()); const uint16_t messageLen = getDNSPacketLength(message, this->getData().size()); - return std::string(message + messageLen, this->getData().size() - messageLen); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + return {message + messageLen, this->getData().size() - messageLen}; } bool DNSQuestion::setTrailingData(const std::string& tail) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) const char* message = reinterpret_cast(this->data.data()); const uint16_t messageLen = getDNSPacketLength(message, this->data.size()); this->data.resize(messageLen); - if (tail.size() > 0) { + if (!tail.empty()) { if (!hasRoomFor(tail.size())) { return false; } @@ -294,7 +300,7 @@ static void doLatencyStats(dnsdist::Protocol protocol, double udiff) ++dnsdist::metrics::g_stats.latencySlow; } - dnsdist::metrics::g_stats.latencySum += udiff / 1000; + dnsdist::metrics::g_stats.latencySum += static_cast(udiff) / 1000; ++dnsdist::metrics::g_stats.latencyCount; doAvg(dnsdist::metrics::g_stats.latencyAvg100, udiff, 100); @@ -340,8 +346,8 @@ bool responseContentMatches(const PacketBuffer& response, const DNSName& qname, return false; } - const dnsheader_aligned dh(response.data()); - if (dh->qr == 0) { + const dnsheader_aligned dnsHeader(response.data()); + if (dnsHeader->qr == 0) { ++dnsdist::metrics::g_stats.nonCompliantResponses; if (remote) { ++remote->nonCompliantResponses; @@ -349,28 +355,28 @@ bool responseContentMatches(const PacketBuffer& response, const DNSName& qname, return false; } - if (dh->qdcount == 0) { - if ((dh->rcode != RCode::NoError && dh->rcode != RCode::NXDomain) || g_allowEmptyResponse) { + if (dnsHeader->qdcount == 0) { + if ((dnsHeader->rcode != RCode::NoError && dnsHeader->rcode != RCode::NXDomain) || g_allowEmptyResponse) { return true; } - else { - ++dnsdist::metrics::g_stats.nonCompliantResponses; - if (remote) { - ++remote->nonCompliantResponses; - } - return false; + + ++dnsdist::metrics::g_stats.nonCompliantResponses; + if (remote) { + ++remote->nonCompliantResponses; } + return false; } - uint16_t rqtype, rqclass; + uint16_t rqtype{}; + uint16_t rqclass{}; DNSName rqname; try { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) rqname = DNSName(reinterpret_cast(response.data()), response.size(), sizeof(dnsheader), false, &rqtype, &rqclass); } catch (const std::exception& e) { - if (remote && response.size() > 0 && static_cast(response.size()) > sizeof(dnsheader)) { - infolog("Backend %s sent us a response with id %d that did not parse: %s", remote->d_config.remote.toStringWithPort(), ntohs(dh->id), e.what()); + if (remote && !response.empty() && static_cast(response.size()) > sizeof(dnsheader)) { + infolog("Backend %s sent us a response with id %d that did not parse: %s", remote->d_config.remote.toStringWithPort(), ntohs(dnsHeader->id), e.what()); } ++dnsdist::metrics::g_stats.nonCompliantResponses; if (remote) { @@ -379,19 +385,15 @@ bool responseContentMatches(const PacketBuffer& response, const DNSName& qname, return false; } - if (rqtype != qtype || rqclass != qclass || rqname != qname) { - return false; - } - - return true; + return rqtype == qtype && rqclass == qclass && rqname == qname; } -static void restoreFlags(struct dnsheader* dh, uint16_t origFlags) +static void restoreFlags(struct dnsheader* dnsHeader, uint16_t origFlags) { static const uint16_t rdMask = 1 << FLAGS_RD_OFFSET; static const uint16_t cdMask = 1 << FLAGS_CD_OFFSET; static const uint16_t restoreFlagsMask = UINT16_MAX & ~(rdMask | cdMask); - uint16_t* flags = getFlagsFromDNSHeader(dh); + uint16_t* flags = getFlagsFromDNSHeader(dnsHeader); /* clear the flags we are about to restore */ *flags &= restoreFlagsMask; /* only keep the flags we want to restore */ @@ -433,14 +435,14 @@ static bool fixUpResponse(PacketBuffer& response, const DNSName& qname, uint16_t } if (ednsAdded || ecsAdded) { - uint16_t optStart; + uint16_t optStart{}; size_t optLen = 0; bool last = false; int res = locateEDNSOptRR(response, &optStart, &optLen, &last); if (res == 0) { - if (zeroScope) { // this finds if an EDNS Client Subnet scope was set, and if it is 0 + if (zeroScope != nullptr) { // this finds if an EDNS Client Subnet scope was set, and if it is 0 size_t optContentStart = 0; uint16_t optContentLen = 0; /* we need at least 4 bytes after the option length (family: 2, source prefix-length: 1, scope prefix-length: 1) */ @@ -482,6 +484,7 @@ static bool fixUpResponse(PacketBuffer& response, const DNSName& qname, uint16_t /* nothing after the OPT RR, we can simply remove the ECS option */ size_t existingOptLen = optLen; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) removeEDNSOptionFromOPT(reinterpret_cast(&response.at(optStart)), &optLen, EDNSOptionCode::ECS); response.resize(response.size() - (existingOptLen - optLen)); } @@ -517,14 +520,14 @@ static bool encryptResponse(PacketBuffer& response, size_t maximumSize, bool tcp } #endif /* HAVE_DNSCRYPT */ -static bool applyRulesToResponse(const std::vector& respRuleActions, DNSResponse& dr) +static bool applyRulesToResponse(const std::vector& respRuleActions, DNSResponse& dnsResponse) { DNSResponseAction::Action action = DNSResponseAction::Action::None; std::string ruleresult; - for (const auto& lr : respRuleActions) { - if (lr.d_rule->matches(&dr)) { - ++lr.d_rule->d_matches; - action = (*lr.d_action)(&dr, &ruleresult); + for (const auto& rrule : respRuleActions) { + if (rrule.d_rule->matches(&dnsResponse)) { + ++rrule.d_rule->d_matches; + action = (*rrule.d_action)(&dnsResponse, &ruleresult); switch (action) { case DNSResponseAction::Action::Allow: return true; @@ -536,27 +539,27 @@ static bool applyRulesToResponse(const std::vector& r return true; break; case DNSResponseAction::Action::ServFail: - dnsdist::PacketMangling::editDNSHeaderFromPacket(dr.getMutableData(), [](dnsheader& header) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsResponse.getMutableData(), [](dnsheader& header) { header.rcode = RCode::ServFail; return true; }); return true; break; case DNSResponseAction::Action::Truncate: - if (!dr.overTCP()) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dr.getMutableData(), [](dnsheader& header) { + if (!dnsResponse.overTCP()) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsResponse.getMutableData(), [](dnsheader& header) { header.tc = true; header.qr = true; return true; }); - truncateTC(dr.getMutableData(), dr.getMaximumSize(), dr.ids.qname.wirelength()); + truncateTC(dnsResponse.getMutableData(), dnsResponse.getMaximumSize(), dnsResponse.ids.qname.wirelength()); ++dnsdist::metrics::g_stats.ruleTruncated; return true; } break; /* non-terminal actions follow */ case DNSResponseAction::Action::Delay: - pdns::checked_stoi_into(dr.ids.delayMsec, ruleresult); // sorry + pdns::checked_stoi_into(dnsResponse.ids.delayMsec, ruleresult); // sorry break; case DNSResponseAction::Action::None: break; @@ -604,8 +607,8 @@ bool processResponseAfterRules(PacketBuffer& response, const std::vector 0) { std::string result; - LimitTTLResponseAction ac(0, dnsResponse.ids.ttlCap, {}); - ac(&dnsResponse, &result); + LimitTTLResponseAction lrac(0, dnsResponse.ids.ttlCap, {}); + lrac(&dnsResponse, &result); } if (dnsResponse.ids.d_extendedError) { @@ -647,13 +650,13 @@ static size_t getInitialUDPPacketBufferSize(bool expectProxyProtocol) return s_initialUDPPacketBufferSize + g_proxyProtocolMaximumSize; } -static size_t getMaximumIncomingPacketSize(const ClientState& cs) +static size_t getMaximumIncomingPacketSize(const ClientState& clientState) { - if (cs.dnscryptCtx) { - return getInitialUDPPacketBufferSize(cs.d_enableProxyProtocol); + if (clientState.dnscryptCtx) { + return getInitialUDPPacketBufferSize(clientState.d_enableProxyProtocol); } - if (!cs.d_enableProxyProtocol || g_proxyProtocolACL.empty()) { + if (!clientState.d_enableProxyProtocol || g_proxyProtocolACL.empty()) { return s_udpIncomingBufferSize; } @@ -664,11 +667,12 @@ bool sendUDPResponse(int origFD, const PacketBuffer& response, const int delayMs { #ifndef DISABLE_DELAY_PIPE if (delayMsec > 0 && g_delay != nullptr) { - DelayedPacket dp{origFD, response, origRemote, origDest}; - g_delay->submit(dp, delayMsec); + DelayedPacket delayed{origFD, response, origRemote, origDest}; + g_delay->submit(delayed, delayMsec); return true; } #endif /* DISABLE_DELAY_PIPE */ + // NOLINTNEXTLINE(readability-suspicious-call-argument) ssize_t res = sendfromto(origFD, response.data(), response.size(), 0, origDest, origRemote); if (res == -1) { int err = errno; @@ -686,9 +690,9 @@ void handleResponseSent(const InternalQueryState& ids, double udiff, const Combo void handleResponseSent(const DNSName& qname, const QType& qtype, double udiff, const ComboAddress& client, const ComboAddress& backend, unsigned int size, const dnsheader& cleartextDH, dnsdist::Protocol outgoingProtocol, dnsdist::Protocol incomingProtocol, bool fromBackend) { if (g_rings.shouldRecordResponses()) { - struct timespec ts; - gettime(&ts); - g_rings.insertResponse(ts, client, qname, qtype, static_cast(udiff), size, cleartextDH, backend, outgoingProtocol); + timespec now{}; + gettime(&now); + g_rings.insertResponse(now, client, qname, qtype, static_cast(udiff), size, cleartextDH, backend, outgoingProtocol); } switch (cleartextDH.rcode) { @@ -709,66 +713,66 @@ void handleResponseSent(const DNSName& qname, const QType& qtype, double udiff, doLatencyStats(incomingProtocol, udiff); } -static void handleResponseForUDPClient(InternalQueryState& ids, PacketBuffer& response, const std::vector& respRuleActions, const std::vector& cacheInsertedRespRuleActions, const std::shared_ptr& ds, bool isAsync, bool selfGenerated) +static void handleResponseForUDPClient(InternalQueryState& ids, PacketBuffer& response, const std::vector& respRuleActions, const std::vector& cacheInsertedRespRuleActions, const std::shared_ptr& backend, bool isAsync, bool selfGenerated) { - DNSResponse dr(ids, response, ds); + DNSResponse dnsResponse(ids, response, backend); if (ids.udpPayloadSize > 0 && response.size() > ids.udpPayloadSize) { vinfolog("Got a response of size %d while the initial UDP payload size was %d, truncating", response.size(), ids.udpPayloadSize); - truncateTC(dr.getMutableData(), dr.getMaximumSize(), dr.ids.qname.wirelength()); - dnsdist::PacketMangling::editDNSHeaderFromPacket(dr.getMutableData(), [](dnsheader& header) { + truncateTC(dnsResponse.getMutableData(), dnsResponse.getMaximumSize(), dnsResponse.ids.qname.wirelength()); + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsResponse.getMutableData(), [](dnsheader& header) { header.tc = true; return true; }); } - else if (dr.getHeader()->tc && g_truncateTC) { - truncateTC(response, dr.getMaximumSize(), dr.ids.qname.wirelength()); + else if (dnsResponse.getHeader()->tc && g_truncateTC) { + truncateTC(response, dnsResponse.getMaximumSize(), dnsResponse.ids.qname.wirelength()); } /* when the answer is encrypted in place, we need to get a copy of the original header before encryption to fill the ring buffer */ - dnsheader cleartextDH; - memcpy(&cleartextDH, dr.getHeader().get(), sizeof(cleartextDH)); + dnsheader cleartextDH{}; + memcpy(&cleartextDH, dnsResponse.getHeader().get(), sizeof(cleartextDH)); if (!isAsync) { - if (!processResponse(response, respRuleActions, cacheInsertedRespRuleActions, dr, ids.cs && ids.cs->muted)) { + if (!processResponse(response, respRuleActions, cacheInsertedRespRuleActions, dnsResponse, ids.cs != nullptr && ids.cs->muted)) { return; } - if (dr.isAsynchronous()) { + if (dnsResponse.isAsynchronous()) { return; } } ++dnsdist::metrics::g_stats.responses; - if (ids.cs) { + if (ids.cs != nullptr) { ++ids.cs->responses; } bool muted = true; if (ids.cs != nullptr && !ids.cs->muted && !ids.isXSK()) { - sendUDPResponse(ids.cs->udpFD, response, dr.ids.delayMsec, ids.hopLocal, ids.hopRemote); + sendUDPResponse(ids.cs->udpFD, response, dnsResponse.ids.delayMsec, ids.hopLocal, ids.hopRemote); muted = false; } if (!selfGenerated) { double udiff = ids.queryRealTime.udiff(); if (!muted) { - vinfolog("Got answer from %s, relayed to %s (UDP), took %f us", ds->d_config.remote.toStringWithPort(), ids.origRemote.toStringWithPort(), udiff); + vinfolog("Got answer from %s, relayed to %s (UDP), took %f us", backend->d_config.remote.toStringWithPort(), ids.origRemote.toStringWithPort(), udiff); } else { if (!ids.isXSK()) { - vinfolog("Got answer from %s, NOT relayed to %s (UDP) since that frontend is muted, took %f us", ds->d_config.remote.toStringWithPort(), ids.origRemote.toStringWithPort(), udiff); + vinfolog("Got answer from %s, NOT relayed to %s (UDP) since that frontend is muted, took %f us", backend->d_config.remote.toStringWithPort(), ids.origRemote.toStringWithPort(), udiff); } else { - vinfolog("Got answer from %s, relayed to %s (UDP via XSK), took %f us", ds->d_config.remote.toStringWithPort(), ids.origRemote.toStringWithPort(), udiff); + vinfolog("Got answer from %s, relayed to %s (UDP via XSK), took %f us", backend->d_config.remote.toStringWithPort(), ids.origRemote.toStringWithPort(), udiff); } } - handleResponseSent(ids, udiff, dr.ids.origRemote, ds->d_config.remote, response.size(), cleartextDH, ds->getProtocol(), true); + handleResponseSent(ids, udiff, dnsResponse.ids.origRemote, backend->d_config.remote, response.size(), cleartextDH, backend->getProtocol(), true); } else { - handleResponseSent(ids, 0., dr.ids.origRemote, ComboAddress(), response.size(), cleartextDH, dnsdist::Protocol::DoUDP, false); + handleResponseSent(ids, 0., dnsResponse.ids.origRemote, ComboAddress(), response.size(), cleartextDH, dnsdist::Protocol::DoUDP, false); } } @@ -845,11 +849,11 @@ void responderThread(std::shared_ptr dss) break; } - for (const auto& fd : sockets) { + for (const auto& sockDesc : sockets) { /* allocate one more byte so we can detect truncation */ // NOLINTNEXTLINE(bugprone-use-after-move): resizing a vector has no preconditions so it is valid to do so after moving it response.resize(initialBufferSize + 1); - ssize_t got = recv(fd, response.data(), response.size(), 0); + ssize_t got = recv(sockDesc, response.data(), response.size(), 0); if (got == 0 && dss->isStopped()) { break; @@ -868,7 +872,7 @@ void responderThread(std::shared_ptr dss) continue; } - if (!ids->isXSK() && fd != ids->backendFD) { + if (!ids->isXSK() && sockDesc != ids->backendFD) { dss->restoreState(queryId, std::move(*ids)); continue; } @@ -912,7 +916,7 @@ void responderThread(std::shared_ptr dss) LockGuarded g_lua{LuaContext()}; ComboAddress g_serverControl{"127.0.0.1:5199"}; -static void spoofResponseFromString(DNSQuestion& dq, const string& spoofContent, bool raw) +static void spoofResponseFromString(DNSQuestion& dnsQuestion, const string& spoofContent, bool raw) { string result; @@ -920,7 +924,7 @@ static void spoofResponseFromString(DNSQuestion& dq, const string& spoofContent, std::vector raws; stringtok(raws, spoofContent, ","); SpoofAction tempSpoofAction(raws, std::nullopt); - tempSpoofAction(&dq, &result); + tempSpoofAction(&dnsQuestion, &result); } else { std::vector addrs; @@ -930,35 +934,35 @@ static void spoofResponseFromString(DNSQuestion& dq, const string& spoofContent, try { ComboAddress spoofAddr(spoofContent); SpoofAction tempSpoofAction({spoofAddr}); - tempSpoofAction(&dq, &result); + tempSpoofAction(&dnsQuestion, &result); } catch (const PDNSException& e) { DNSName cname(spoofContent); SpoofAction tempSpoofAction(cname); // CNAME then - tempSpoofAction(&dq, &result); + tempSpoofAction(&dnsQuestion, &result); } } else { std::vector cas; for (const auto& addr : addrs) { try { - cas.push_back(ComboAddress(addr)); + cas.emplace_back(addr); } catch (...) { } } SpoofAction tempSpoofAction(cas); - tempSpoofAction(&dq, &result); + tempSpoofAction(&dnsQuestion, &result); } } } -static void spoofPacketFromString(DNSQuestion& dq, const string& spoofContent) +static void spoofPacketFromString(DNSQuestion& dnsQuestion, const string& spoofContent) { string result; SpoofAction tempSpoofAction(spoofContent.c_str(), spoofContent.size()); - tempSpoofAction(&dq, &result); + tempSpoofAction(&dnsQuestion, &result); } bool processRulesResult(const DNSAction::Action& action, DNSQuestion& dnsQuestion, std::string& ruleresult, bool& drop) @@ -1052,23 +1056,23 @@ bool processRulesResult(const DNSAction::Action& action, DNSQuestion& dnsQuestio return false; } -static bool applyRulesToQuery(LocalHolders& holders, DNSQuestion& dq, const struct timespec& now) +static bool applyRulesToQuery(LocalHolders& holders, DNSQuestion& dnsQuestion, const struct timespec& now) { if (g_rings.shouldRecordQueries()) { - g_rings.insertQuery(now, dq.ids.origRemote, dq.ids.qname, dq.ids.qtype, dq.getData().size(), *dq.getHeader(), dq.getProtocol()); + g_rings.insertQuery(now, dnsQuestion.ids.origRemote, dnsQuestion.ids.qname, dnsQuestion.ids.qtype, dnsQuestion.getData().size(), *dnsQuestion.getHeader(), dnsQuestion.getProtocol()); } if (g_qcount.enabled) { - string qname = dq.ids.qname.toLogString(); + string qname = dnsQuestion.ids.qname.toLogString(); bool countQuery{true}; if (g_qcount.filter) { auto lock = g_lua.lock(); - std::tie(countQuery, qname) = g_qcount.filter(&dq); + std::tie(countQuery, qname) = g_qcount.filter(&dnsQuestion); } if (countQuery) { auto records = g_qcount.records.write_lock(); - if (!records->count(qname)) { + if (records->count(qname) == 0) { (*records)[qname] = 0; } (*records)[qname]++; @@ -1076,8 +1080,8 @@ static bool applyRulesToQuery(LocalHolders& holders, DNSQuestion& dq, const stru } #ifndef DISABLE_DYNBLOCKS - auto setRCode = [&dq](uint8_t rcode) { - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [rcode](dnsheader& header) { + auto setRCode = [&dnsQuestion](uint8_t rcode) { + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [rcode](dnsheader& header) { header.rcode = rcode; header.qr = true; return true; @@ -1085,7 +1089,7 @@ static bool applyRulesToQuery(LocalHolders& holders, DNSQuestion& dq, const stru }; /* the Dynamic Block mechanism supports address and port ranges, so we need to pass the full address and port */ - if (auto got = holders.dynNMGBlock->lookup(AddressAndPortRange(dq.ids.origRemote, dq.ids.origRemote.isIPv4() ? 32 : 128, 16))) { + if (auto* got = holders.dynNMGBlock->lookup(AddressAndPortRange(dnsQuestion.ids.origRemote, dnsQuestion.ids.origRemote.isIPv4() ? 32 : 128, 16))) { auto updateBlockStats = [&got]() { ++dnsdist::metrics::g_stats.dynBlocked; got->second.blocks++; @@ -1103,24 +1107,24 @@ static bool applyRulesToQuery(LocalHolders& holders, DNSQuestion& dq, const stru break; case DNSAction::Action::Nxdomain: - vinfolog("Query from %s turned into NXDomain because of dynamic block", dq.ids.origRemote.toStringWithPort()); + vinfolog("Query from %s turned into NXDomain because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort()); updateBlockStats(); setRCode(RCode::NXDomain); return true; case DNSAction::Action::Refused: - vinfolog("Query from %s refused because of dynamic block", dq.ids.origRemote.toStringWithPort()); + vinfolog("Query from %s refused because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort()); updateBlockStats(); setRCode(RCode::Refused); return true; case DNSAction::Action::Truncate: - if (!dq.overTCP()) { + if (!dnsQuestion.overTCP()) { updateBlockStats(); - vinfolog("Query from %s truncated because of dynamic block", dq.ids.origRemote.toStringWithPort()); - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [](dnsheader& header) { + vinfolog("Query from %s truncated because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort()); + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [](dnsheader& header) { header.tc = true; header.qr = true; header.ra = header.rd; @@ -1131,26 +1135,26 @@ static bool applyRulesToQuery(LocalHolders& holders, DNSQuestion& dq, const stru return true; } else { - vinfolog("Query from %s for %s over TCP *not* truncated because of dynamic block", dq.ids.origRemote.toStringWithPort(), dq.ids.qname.toLogString()); + vinfolog("Query from %s for %s over TCP *not* truncated because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort(), dnsQuestion.ids.qname.toLogString()); } break; case DNSAction::Action::NoRecurse: updateBlockStats(); - vinfolog("Query from %s setting rd=0 because of dynamic block", dq.ids.origRemote.toStringWithPort()); - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [](dnsheader& header) { + vinfolog("Query from %s setting rd=0 because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort()); + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [](dnsheader& header) { header.rd = false; return true; }); return true; default: updateBlockStats(); - vinfolog("Query from %s dropped because of dynamic block", dq.ids.origRemote.toStringWithPort()); + vinfolog("Query from %s dropped because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort()); return false; } } } - if (auto got = holders.dynSMTBlock->lookup(dq.ids.qname)) { + if (auto* got = holders.dynSMTBlock->lookup(dnsQuestion.ids.qname)) { auto updateBlockStats = [&got]() { ++dnsdist::metrics::g_stats.dynBlocked; got->blocks++; @@ -1166,23 +1170,23 @@ static bool applyRulesToQuery(LocalHolders& holders, DNSQuestion& dq, const stru /* do nothing */ break; case DNSAction::Action::Nxdomain: - vinfolog("Query from %s for %s turned into NXDomain because of dynamic block", dq.ids.origRemote.toStringWithPort(), dq.ids.qname.toLogString()); + vinfolog("Query from %s for %s turned into NXDomain because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort(), dnsQuestion.ids.qname.toLogString()); updateBlockStats(); setRCode(RCode::NXDomain); return true; case DNSAction::Action::Refused: - vinfolog("Query from %s for %s refused because of dynamic block", dq.ids.origRemote.toStringWithPort(), dq.ids.qname.toLogString()); + vinfolog("Query from %s for %s refused because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort(), dnsQuestion.ids.qname.toLogString()); updateBlockStats(); setRCode(RCode::Refused); return true; case DNSAction::Action::Truncate: - if (!dq.overTCP()) { + if (!dnsQuestion.overTCP()) { updateBlockStats(); - vinfolog("Query from %s for %s truncated because of dynamic block", dq.ids.origRemote.toStringWithPort(), dq.ids.qname.toLogString()); - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [](dnsheader& header) { + vinfolog("Query from %s for %s truncated because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort(), dnsQuestion.ids.qname.toLogString()); + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [](dnsheader& header) { header.tc = true; header.qr = true; header.ra = header.rd; @@ -1193,20 +1197,20 @@ static bool applyRulesToQuery(LocalHolders& holders, DNSQuestion& dq, const stru return true; } else { - vinfolog("Query from %s for %s over TCP *not* truncated because of dynamic block", dq.ids.origRemote.toStringWithPort(), dq.ids.qname.toLogString()); + vinfolog("Query from %s for %s over TCP *not* truncated because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort(), dnsQuestion.ids.qname.toLogString()); } break; case DNSAction::Action::NoRecurse: updateBlockStats(); - vinfolog("Query from %s setting rd=0 because of dynamic block", dq.ids.origRemote.toStringWithPort()); - dnsdist::PacketMangling::editDNSHeaderFromPacket(dq.getMutableData(), [](dnsheader& header) { + vinfolog("Query from %s setting rd=0 because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort()); + dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion.getMutableData(), [](dnsheader& header) { header.rd = false; return true; }); return true; default: updateBlockStats(); - vinfolog("Query from %s for %s dropped because of dynamic block", dq.ids.origRemote.toStringWithPort(), dq.ids.qname.toLogString()); + vinfolog("Query from %s for %s dropped because of dynamic block", dnsQuestion.ids.origRemote.toStringWithPort(), dnsQuestion.ids.qname.toLogString()); return false; } } @@ -1216,43 +1220,40 @@ static bool applyRulesToQuery(LocalHolders& holders, DNSQuestion& dq, const stru DNSAction::Action action = DNSAction::Action::None; string ruleresult; bool drop = false; - for (const auto& lr : *holders.ruleactions) { - if (lr.d_rule->matches(&dq)) { - lr.d_rule->d_matches++; - action = (*lr.d_action)(&dq, &ruleresult); - if (processRulesResult(action, dq, ruleresult, drop)) { + for (const auto& rule : *holders.ruleactions) { + if (rule.d_rule->matches(&dnsQuestion)) { + rule.d_rule->d_matches++; + action = (*rule.d_action)(&dnsQuestion, &ruleresult); + if (processRulesResult(action, dnsQuestion, ruleresult, drop)) { break; } } } - if (drop) { - return false; - } - - return true; + return !drop; } -ssize_t udpClientSendRequestToBackend(const std::shared_ptr& ss, const int sd, const PacketBuffer& request, bool healthCheck) +ssize_t udpClientSendRequestToBackend(const std::shared_ptr& backend, const int socketDesc, const PacketBuffer& request, bool healthCheck) { - ssize_t result; + ssize_t result = 0; - if (ss->d_config.sourceItf == 0) { - result = send(sd, request.data(), request.size(), 0); + if (backend->d_config.sourceItf == 0) { + result = send(socketDesc, request.data(), request.size(), 0); } else { - struct msghdr msgh; - struct iovec iov; + msghdr msgh{}; + iovec iov{}; cmsgbuf_aligned cbuf; - ComboAddress remote(ss->d_config.remote); + ComboAddress remote(backend->d_config.remote); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-type-const-cast) fillMSGHdr(&msgh, &iov, &cbuf, sizeof(cbuf), const_cast(reinterpret_cast(request.data())), request.size(), &remote); - addCMsgSrcAddr(&msgh, &cbuf, &ss->d_config.sourceAddr, ss->d_config.sourceItf); - result = sendmsg(sd, &msgh, 0); + addCMsgSrcAddr(&msgh, &cbuf, &backend->d_config.sourceAddr, static_cast(backend->d_config.sourceItf)); + result = sendmsg(socketDesc, &msgh, 0); } if (result == -1) { int savederrno = errno; - vinfolog("Error sending request to backend %s: %s", ss->d_config.remote.toStringWithPort(), stringerror(savederrno)); + vinfolog("Error sending request to backend %s: %s", backend->d_config.remote.toStringWithPort(), stringerror(savederrno)); /* This might sound silly, but on Linux send() might fail with EINVAL if the interface the socket was bound to doesn't exist anymore. @@ -1260,24 +1261,24 @@ ssize_t udpClientSendRequestToBackend(const std::shared_ptr& ss because it's not using the same socket. */ if (!healthCheck && (savederrno == EINVAL || savederrno == ENODEV || savederrno == ENETUNREACH || savederrno == EBADF)) { - ss->reconnect(); + backend->reconnect(); } } return result; } -static bool isUDPQueryAcceptable(ClientState& cs, LocalHolders& holders, const struct msghdr* msgh, const ComboAddress& remote, ComboAddress& dest, bool& expectProxyProtocol) +static bool isUDPQueryAcceptable(ClientState& clientState, LocalHolders& holders, const struct msghdr* msgh, const ComboAddress& remote, ComboAddress& dest, bool& expectProxyProtocol) { - if (msgh->msg_flags & MSG_TRUNC) { + if ((msgh->msg_flags & MSG_TRUNC) != 0) { /* message was too large for our buffer */ vinfolog("Dropping message too large for our buffer"); - ++cs.nonCompliantQueries; + ++clientState.nonCompliantQueries; ++dnsdist::metrics::g_stats.nonCompliantQueries; return false; } - expectProxyProtocol = cs.d_enableProxyProtocol && expectProxyProtocolFrom(remote); + expectProxyProtocol = clientState.d_enableProxyProtocol && expectProxyProtocolFrom(remote); if (!holders.acl->match(remote) && !expectProxyProtocol) { vinfolog("Query from %s dropped because of ACL", remote.toStringWithPort()); ++dnsdist::metrics::g_stats.aclDrops; @@ -1294,38 +1295,35 @@ static bool isUDPQueryAcceptable(ClientState& cs, LocalHolders& holders, const s */ const ComboAddress bogusV4("0.0.0.0:0"); const ComboAddress bogusV6("[::]:0"); - if (dest.sin4.sin_family == AF_INET && dest == bogusV4) { - dest.sin4.sin_family = 0; - } - else if (dest.sin4.sin_family == AF_INET6 && dest == bogusV6) { + if ((dest.sin4.sin_family == AF_INET && dest == bogusV4) || (dest.sin4.sin_family == AF_INET6 && dest == bogusV6)) { dest.sin4.sin_family = 0; } else { /* we don't get the port, only the address */ - dest.sin4.sin_port = cs.local.sin4.sin_port; + dest.sin4.sin_port = clientState.local.sin4.sin_port; } } else { dest.sin4.sin_family = 0; } - ++cs.queries; + ++clientState.queries; ++dnsdist::metrics::g_stats.queries; return true; } -bool checkDNSCryptQuery(const ClientState& cs, PacketBuffer& query, std::unique_ptr& dnsCryptQuery, time_t now, bool tcp) +bool checkDNSCryptQuery(const ClientState& clientState, PacketBuffer& query, std::unique_ptr& dnsCryptQuery, time_t now, bool tcp) { - if (cs.dnscryptCtx) { + if (clientState.dnscryptCtx) { #ifdef HAVE_DNSCRYPT PacketBuffer response; - dnsCryptQuery = std::make_unique(cs.dnscryptCtx); + dnsCryptQuery = std::make_unique(clientState.dnscryptCtx); bool decrypted = handleDNSCryptQuery(query, *dnsCryptQuery, tcp, now, response); if (!decrypted) { - if (response.size() > 0) { + if (!response.empty()) { query = std::move(response); return true; } @@ -1360,9 +1358,10 @@ bool checkQueryHeaders(const struct dnsheader& dnsHeader, ClientState& clientSta #ifndef DISABLE_RECVMMSG #if defined(HAVE_RECVMMSG) && defined(HAVE_SENDMMSG) && defined(MSG_WAITFORONE) -static void queueResponse(const ClientState& cs, const PacketBuffer& response, const ComboAddress& dest, const ComboAddress& remote, struct mmsghdr& outMsg, struct iovec* iov, cmsgbuf_aligned* cbuf) +static void queueResponse(const ClientState& clientState, const PacketBuffer& response, const ComboAddress& dest, const ComboAddress& remote, struct mmsghdr& outMsg, struct iovec* iov, cmsgbuf_aligned* cbuf) { outMsg.msg_len = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast,cppcoreguidelines-pro-type-reinterpret-cast): API fillMSGHdr(&outMsg.msg_hdr, iov, nullptr, 0, const_cast(reinterpret_cast(&response.at(0))), response.size(), const_cast(&remote)); if (dest.sin4.sin_family == 0) { @@ -1376,38 +1375,38 @@ static void queueResponse(const ClientState& cs, const PacketBuffer& response, c #endif /* DISABLE_RECVMMSG */ /* self-generated responses or cache hits */ -static bool prepareOutgoingResponse(LocalHolders& holders, const ClientState& cs, DNSQuestion& dq, bool cacheHit) +static bool prepareOutgoingResponse(LocalHolders& holders, const ClientState& clientState, DNSQuestion& dnsQuestion, bool cacheHit) { - std::shared_ptr ds{nullptr}; - DNSResponse dr(dq.ids, dq.getMutableData(), ds); - dr.d_incomingTCPState = dq.d_incomingTCPState; - dr.ids.selfGenerated = true; + std::shared_ptr backend{nullptr}; + DNSResponse dnsResponse(dnsQuestion.ids, dnsQuestion.getMutableData(), backend); + dnsResponse.d_incomingTCPState = dnsQuestion.d_incomingTCPState; + dnsResponse.ids.selfGenerated = true; - if (!applyRulesToResponse(cacheHit ? *holders.cacheHitRespRuleactions : *holders.selfAnsweredRespRuleactions, dr)) { + if (!applyRulesToResponse(cacheHit ? *holders.cacheHitRespRuleactions : *holders.selfAnsweredRespRuleactions, dnsResponse)) { return false; } - if (dr.ids.ttlCap > 0) { + if (dnsResponse.ids.ttlCap > 0) { std::string result; - LimitTTLResponseAction ac(0, dr.ids.ttlCap, {}); - ac(&dr, &result); + LimitTTLResponseAction ltrac(0, dnsResponse.ids.ttlCap, {}); + ltrac(&dnsResponse, &result); } - if (dr.ids.d_extendedError) { - dnsdist::edns::addExtendedDNSError(dr.getMutableData(), dr.getMaximumSize(), dr.ids.d_extendedError->infoCode, dr.ids.d_extendedError->extraText); + if (dnsResponse.ids.d_extendedError) { + dnsdist::edns::addExtendedDNSError(dnsResponse.getMutableData(), dnsResponse.getMaximumSize(), dnsResponse.ids.d_extendedError->infoCode, dnsResponse.ids.d_extendedError->extraText); } if (cacheHit) { ++dnsdist::metrics::g_stats.cacheHits; } - if (dr.isAsynchronous()) { + if (dnsResponse.isAsynchronous()) { return false; } #ifdef HAVE_DNSCRYPT - if (!cs.muted) { - if (!encryptResponse(dq.getMutableData(), dq.getMaximumSize(), dq.overTCP(), dq.ids.dnsCryptQuery)) { + if (!clientState.muted) { + if (!encryptResponse(dnsQuestion.getMutableData(), dnsQuestion.getMaximumSize(), dnsQuestion.overTCP(), dnsQuestion.ids.dnsCryptQuery)) { return false; } } @@ -1453,7 +1452,7 @@ ProcessQueryResult processQueryAfterRules(DNSQuestion& dnsQuestion, LocalHolders uint32_t allowExpired = selectedBackend ? 0 : g_staleCacheEntriesTTL; if (dnsQuestion.ids.packetCache && !dnsQuestion.ids.skipCache) { - dnsQuestion.ids.dnssecOK = (getEDNSZ(dnsQuestion) & EDNS_HEADER_FLAG_DO); + dnsQuestion.ids.dnssecOK = (getEDNSZ(dnsQuestion) & EDNS_HEADER_FLAG_DO) != 0; } if (dnsQuestion.useECS && ((selectedBackend && selectedBackend->d_config.useECS) || (!selectedBackend && serverPool->getECS()))) { @@ -1511,7 +1510,7 @@ ProcessQueryResult processQueryAfterRules(DNSQuestion& dnsQuestion, LocalHolders ++dnsQuestion.ids.cs->responses; return ProcessQueryResult::SendAnswer; } - else if (dnsQuestion.ids.protocol == dnsdist::Protocol::DoH && !forwardedOverUDP) { + if (dnsQuestion.ids.protocol == dnsdist::Protocol::DoH && !forwardedOverUDP) { /* do a second-lookup for UDP responses, but we do not want TC=1 answers */ if (dnsQuestion.ids.packetCache->get(dnsQuestion, dnsQuestion.getHeader()->id, &dnsQuestion.ids.cacheKeyUDP, dnsQuestion.ids.subnet, dnsQuestion.ids.dnssecOK, true, allowExpired, false, false, true)) { if (!prepareOutgoingResponse(holders, *dnsQuestion.ids.cs, dnsQuestion, true)) { @@ -1580,15 +1579,14 @@ ProcessQueryResult processQueryAfterRules(DNSQuestion& dnsQuestion, LocalHolders class UDPTCPCrossQuerySender : public TCPQuerySender { public: - UDPTCPCrossQuerySender() - { - } - - ~UDPTCPCrossQuerySender() - { - } - - bool active() const override + UDPTCPCrossQuerySender() = default; + UDPTCPCrossQuerySender(const UDPTCPCrossQuerySender&) = delete; + UDPTCPCrossQuerySender& operator=(const UDPTCPCrossQuerySender&) = delete; + UDPTCPCrossQuerySender(UDPTCPCrossQuerySender&&) = default; + UDPTCPCrossQuerySender& operator=(UDPTCPCrossQuerySender&&) = default; + ~UDPTCPCrossQuerySender() override = default; + + [[nodiscard]] bool active() const override { return true; } @@ -1612,7 +1610,7 @@ class UDPTCPCrossQuerySender : public TCPQuerySender return handleResponse(now, std::move(response)); } - void notifyIOError(const struct timeval&, TCPResponse&&) override + void notifyIOError([[maybe_unused]] const struct timeval& now, [[maybe_unused]] TCPResponse&& response) override { // nothing to do } @@ -1621,24 +1619,26 @@ class UDPTCPCrossQuerySender : public TCPQuerySender class UDPCrossProtocolQuery : public CrossProtocolQuery { public: - UDPCrossProtocolQuery(PacketBuffer&& buffer_, InternalQueryState&& ids_, std::shared_ptr ds) : - CrossProtocolQuery(InternalQuery(std::move(buffer_), std::move(ids_)), ds) + UDPCrossProtocolQuery(PacketBuffer&& buffer_, InternalQueryState&& ids_, std::shared_ptr backend) : + CrossProtocolQuery(InternalQuery(std::move(buffer_), std::move(ids_)), backend) { auto& ids = query.d_idstate; const auto& buffer = query.d_buffer; if (ids.udpPayloadSize == 0) { - uint16_t z = 0; - getEDNSUDPPayloadSizeAndZ(reinterpret_cast(buffer.data()), buffer.size(), &ids.udpPayloadSize, &z); + uint16_t zValue = 0; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + getEDNSUDPPayloadSizeAndZ(reinterpret_cast(buffer.data()), buffer.size(), &ids.udpPayloadSize, &zValue); if (ids.udpPayloadSize < 512) { ids.udpPayloadSize = 512; } } } - - ~UDPCrossProtocolQuery() - { - } + UDPCrossProtocolQuery(const UDPCrossProtocolQuery&) = delete; + UDPCrossProtocolQuery& operator=(const UDPCrossProtocolQuery&) = delete; + UDPCrossProtocolQuery(UDPCrossProtocolQuery&&) = delete; + UDPCrossProtocolQuery& operator=(UDPCrossProtocolQuery&&) = delete; + ~UDPCrossProtocolQuery() override = default; std::shared_ptr getTCPQuerySender() override { @@ -1651,11 +1651,11 @@ class UDPCrossProtocolQuery : public CrossProtocolQuery std::shared_ptr UDPCrossProtocolQuery::s_sender = std::make_shared(); -std::unique_ptr getUDPCrossProtocolQueryFromDQ(DNSQuestion& dq); -std::unique_ptr getUDPCrossProtocolQueryFromDQ(DNSQuestion& dq) +std::unique_ptr getUDPCrossProtocolQueryFromDQ(DNSQuestion& dnsQuestion); +std::unique_ptr getUDPCrossProtocolQueryFromDQ(DNSQuestion& dnsQuestion) { - dq.ids.origID = dq.getHeader()->id; - return std::make_unique(std::move(dq.getMutableData()), std::move(dq.ids), nullptr); + dnsQuestion.ids.origID = dnsQuestion.getHeader()->id; + return std::make_unique(std::move(dnsQuestion.getMutableData()), std::move(dnsQuestion.ids), nullptr); } ProcessQueryResult processQuery(DNSQuestion& dnsQuestion, LocalHolders& holders, std::shared_ptr& selectedBackend) @@ -1666,7 +1666,7 @@ ProcessQueryResult processQuery(DNSQuestion& dnsQuestion, LocalHolders& holders, /* we need an accurate ("real") value for the response and to store into the IDS, but not for insertion into the rings for example */ - struct timespec now; + timespec now{}; gettime(&now); if (!applyRulesToQuery(holders, dnsQuestion, now)) { @@ -1751,19 +1751,19 @@ bool assignOutgoingUDPQueryToBackend(std::shared_ptr& downstrea return true; } -static void processUDPQuery(ClientState& cs, LocalHolders& holders, const struct msghdr* msgh, const ComboAddress& remote, ComboAddress& dest, PacketBuffer& query, struct mmsghdr* responsesVect, unsigned int* queuedResponses, struct iovec* respIOV, cmsgbuf_aligned* respCBuf) +static void processUDPQuery(ClientState& clientState, LocalHolders& holders, const struct msghdr* msgh, const ComboAddress& remote, ComboAddress& dest, PacketBuffer& query, std::vector* responsesVect, unsigned int* queuedResponses, struct iovec* respIOV, cmsgbuf_aligned* respCBuf) { assert(responsesVect == nullptr || (queuedResponses != nullptr && respIOV != nullptr && respCBuf != nullptr)); uint16_t queryId = 0; InternalQueryState ids; - ids.cs = &cs; + ids.cs = &clientState; ids.origRemote = remote; ids.hopRemote = remote; ids.protocol = dnsdist::Protocol::DoUDP; try { bool expectProxyProtocol = false; - if (!isUDPQueryAcceptable(cs, holders, msgh, remote, dest, expectProxyProtocol)) { + if (!isUDPQueryAcceptable(clientState, holders, msgh, remote, dest, expectProxyProtocol)) { return; } /* dest might have been updated, if we managed to harvest the destination address */ @@ -1777,7 +1777,7 @@ static void processUDPQuery(ClientState& cs, LocalHolders& holders, const struct pick the less terrible option, but we want to update origDest which is used by rules and actions to at least the correct address family */ - ids.origDest = cs.local; + ids.origDest = clientState.local; ids.hopLocal.sin4.sin_family = 0; } @@ -1788,9 +1788,9 @@ static void processUDPQuery(ClientState& cs, LocalHolders& holders, const struct ids.queryRealTime.start(); - auto dnsCryptResponse = checkDNSCryptQuery(cs, query, ids.dnsCryptQuery, ids.queryRealTime.d_start.tv_sec, false); + auto dnsCryptResponse = checkDNSCryptQuery(clientState, query, ids.dnsCryptQuery, ids.queryRealTime.d_start.tv_sec, false); if (dnsCryptResponse) { - sendUDPResponse(cs.udpFD, query, 0, dest, remote); + sendUDPResponse(clientState.udpFD, query, 0, dest, remote); return; } @@ -1799,7 +1799,7 @@ static void processUDPQuery(ClientState& cs, LocalHolders& holders, const struct const dnsheader_aligned dnsHeader(query.data()); queryId = ntohs(dnsHeader->id); - if (!checkQueryHeaders(*dnsHeader, cs)) { + if (!checkQueryHeaders(*dnsHeader, clientState)) { return; } @@ -1810,71 +1810,72 @@ static void processUDPQuery(ClientState& cs, LocalHolders& holders, const struct return true; }); - sendUDPResponse(cs.udpFD, query, 0, dest, remote); + sendUDPResponse(clientState.udpFD, query, 0, dest, remote); return; } } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(query.data()), query.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); if (ids.dnsCryptQuery) { ids.protocol = dnsdist::Protocol::DNSCryptUDP; } - DNSQuestion dq(ids, query); - const uint16_t* flags = getFlagsFromDNSHeader(dq.getHeader().get()); + DNSQuestion dnsQuestion(ids, query); + const uint16_t* flags = getFlagsFromDNSHeader(dnsQuestion.getHeader().get()); ids.origFlags = *flags; if (!proxyProtocolValues.empty()) { - dq.proxyProtocolValues = make_unique>(std::move(proxyProtocolValues)); + dnsQuestion.proxyProtocolValues = make_unique>(std::move(proxyProtocolValues)); } - std::shared_ptr ss{nullptr}; - auto result = processQuery(dq, holders, ss); + std::shared_ptr backend{nullptr}; + auto result = processQuery(dnsQuestion, holders, backend); if (result == ProcessQueryResult::Drop || result == ProcessQueryResult::Asynchronous) { return; } // the buffer might have been invalidated by now (resized) - const auto dh = dq.getHeader(); + const auto dnsHeader = dnsQuestion.getHeader(); if (result == ProcessQueryResult::SendAnswer) { #ifndef DISABLE_RECVMMSG #if defined(HAVE_RECVMMSG) && defined(HAVE_SENDMMSG) && defined(MSG_WAITFORONE) - if (dq.ids.delayMsec == 0 && responsesVect != nullptr) { - queueResponse(cs, query, dest, remote, responsesVect[*queuedResponses], respIOV, respCBuf); + if (dnsQuestion.ids.delayMsec == 0 && responsesVect != nullptr) { + queueResponse(clientState, query, dest, remote, (*responsesVect)[*queuedResponses], respIOV, respCBuf); (*queuedResponses)++; - handleResponseSent(dq.ids.qname, dq.ids.qtype, 0., remote, ComboAddress(), query.size(), *dh, dnsdist::Protocol::DoUDP, dnsdist::Protocol::DoUDP, false); + handleResponseSent(dnsQuestion.ids.qname, dnsQuestion.ids.qtype, 0., remote, ComboAddress(), query.size(), *dnsHeader, dnsdist::Protocol::DoUDP, dnsdist::Protocol::DoUDP, false); return; } #endif /* defined(HAVE_RECVMMSG) && defined(HAVE_SENDMMSG) && defined(MSG_WAITFORONE) */ #endif /* DISABLE_RECVMMSG */ /* we use dest, always, because we don't want to use the listening address to send a response since it could be 0.0.0.0 */ - sendUDPResponse(cs.udpFD, query, dq.ids.delayMsec, dest, remote); + sendUDPResponse(clientState.udpFD, query, dnsQuestion.ids.delayMsec, dest, remote); - handleResponseSent(dq.ids.qname, dq.ids.qtype, 0., remote, ComboAddress(), query.size(), *dh, dnsdist::Protocol::DoUDP, dnsdist::Protocol::DoUDP, false); + handleResponseSent(dnsQuestion.ids.qname, dnsQuestion.ids.qtype, 0., remote, ComboAddress(), query.size(), *dnsHeader, dnsdist::Protocol::DoUDP, dnsdist::Protocol::DoUDP, false); return; } - if (result != ProcessQueryResult::PassToBackend || ss == nullptr) { + if (result != ProcessQueryResult::PassToBackend || backend == nullptr) { return; } - if (ss->isTCPOnly()) { + if (backend->isTCPOnly()) { std::string proxyProtocolPayload; /* we need to do this _before_ creating the cross protocol query because after that the buffer will have been moved */ - if (ss->d_config.useProxyProtocol) { - proxyProtocolPayload = getProxyProtocolPayload(dq); + if (backend->d_config.useProxyProtocol) { + proxyProtocolPayload = getProxyProtocolPayload(dnsQuestion); } - ids.origID = dh->id; - auto cpq = std::make_unique(std::move(query), std::move(ids), ss); + ids.origID = dnsHeader->id; + auto cpq = std::make_unique(std::move(query), std::move(ids), backend); cpq->query.d_proxyProtocolPayload = std::move(proxyProtocolPayload); - ss->passCrossProtocolQuery(std::move(cpq)); + backend->passCrossProtocolQuery(std::move(cpq)); return; } - assignOutgoingUDPQueryToBackend(ss, dh->id, dq, query); + assignOutgoingUDPQueryToBackend(backend, dnsHeader->id, dnsQuestion, query); } catch (const std::exception& e) { vinfolog("Got an error in UDP question thread while parsing a query from %s, id %d: %s", ids.origRemote.toStringWithPort(), queryId, e.what()); @@ -1884,13 +1885,13 @@ static void processUDPQuery(ClientState& cs, LocalHolders& holders, const struct #ifdef HAVE_XSK namespace dnsdist::xsk { -bool XskProcessQuery(ClientState& cs, LocalHolders& holders, XskPacket& packet) +bool XskProcessQuery(ClientState& clientState, LocalHolders& holders, XskPacket& packet) { uint16_t queryId = 0; const auto& remote = packet.getFromAddr(); const auto& dest = packet.getToAddr(); InternalQueryState ids; - ids.cs = &cs; + ids.cs = &clientState; ids.origRemote = remote; ids.hopRemote = remote; ids.origDest = dest; @@ -1900,7 +1901,7 @@ bool XskProcessQuery(ClientState& cs, LocalHolders& holders, XskPacket& packet) try { bool expectProxyProtocol = false; - if (!XskIsQueryAcceptable(packet, cs, holders, expectProxyProtocol)) { + if (!XskIsQueryAcceptable(packet, clientState, holders, expectProxyProtocol)) { return false; } @@ -1912,7 +1913,7 @@ bool XskProcessQuery(ClientState& cs, LocalHolders& holders, XskPacket& packet) ids.queryRealTime.start(); - auto dnsCryptResponse = checkDNSCryptQuery(cs, query, ids.dnsCryptQuery, ids.queryRealTime.d_start.tv_sec, false); + auto dnsCryptResponse = checkDNSCryptQuery(clientState, query, ids.dnsCryptQuery, ids.queryRealTime.d_start.tv_sec, false); if (dnsCryptResponse) { packet.setPayload(query); return true; @@ -1923,7 +1924,7 @@ bool XskProcessQuery(ClientState& cs, LocalHolders& holders, XskPacket& packet) dnsheader_aligned dnsHeader(query.data()); queryId = ntohs(dnsHeader->id); - if (!checkQueryHeaders(*dnsHeader.get(), cs)) { + if (!checkQueryHeaders(*dnsHeader, clientState)) { return false; } @@ -1938,19 +1939,20 @@ bool XskProcessQuery(ClientState& cs, LocalHolders& holders, XskPacket& packet) } } + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) ids.qname = DNSName(reinterpret_cast(query.data()), query.size(), sizeof(dnsheader), false, &ids.qtype, &ids.qclass); if (ids.origDest.sin4.sin_family == 0) { - ids.origDest = cs.local; + ids.origDest = clientState.local; } if (ids.dnsCryptQuery) { ids.protocol = dnsdist::Protocol::DNSCryptUDP; } - DNSQuestion dq(ids, query); + DNSQuestion dnsQuestion(ids, query); if (!proxyProtocolValues.empty()) { - dq.proxyProtocolValues = make_unique>(std::move(proxyProtocolValues)); + dnsQuestion.proxyProtocolValues = make_unique>(std::move(proxyProtocolValues)); } - std::shared_ptr ss{nullptr}; - auto result = processQuery(dq, holders, ss); + std::shared_ptr backend{nullptr}; + auto result = processQuery(dnsQuestion, holders, backend); if (result == ProcessQueryResult::Drop) { return false; @@ -1958,48 +1960,47 @@ bool XskProcessQuery(ClientState& cs, LocalHolders& holders, XskPacket& packet) if (result == ProcessQueryResult::SendAnswer) { packet.setPayload(query); - if (dq.ids.delayMsec > 0) { - packet.addDelay(dq.ids.delayMsec); + if (dnsQuestion.ids.delayMsec > 0) { + packet.addDelay(dnsQuestion.ids.delayMsec); } - const auto dh = dq.getHeader(); - handleResponseSent(ids.qname, ids.qtype, 0., remote, ComboAddress(), query.size(), *dh, dnsdist::Protocol::DoUDP, dnsdist::Protocol::DoUDP, false); + const auto dnsHeader = dnsQuestion.getHeader(); + handleResponseSent(ids.qname, ids.qtype, 0., remote, ComboAddress(), query.size(), *dnsHeader, dnsdist::Protocol::DoUDP, dnsdist::Protocol::DoUDP, false); return true; } - if (result != ProcessQueryResult::PassToBackend || ss == nullptr) { + if (result != ProcessQueryResult::PassToBackend || backend == nullptr) { return false; } // the buffer might have been invalidated by now (resized) - const auto dh = dq.getHeader(); - if (ss->isTCPOnly()) { + const auto dnsHeader = dnsQuestion.getHeader(); + if (backend->isTCPOnly()) { std::string proxyProtocolPayload; /* we need to do this _before_ creating the cross protocol query because after that the buffer will have been moved */ - if (ss->d_config.useProxyProtocol) { - proxyProtocolPayload = getProxyProtocolPayload(dq); + if (backend->d_config.useProxyProtocol) { + proxyProtocolPayload = getProxyProtocolPayload(dnsQuestion); } - ids.origID = dh->id; - auto cpq = std::make_unique(std::move(query), std::move(ids), ss); + ids.origID = dnsHeader->id; + auto cpq = std::make_unique(std::move(query), std::move(ids), backend); cpq->query.d_proxyProtocolPayload = std::move(proxyProtocolPayload); - ss->passCrossProtocolQuery(std::move(cpq)); + backend->passCrossProtocolQuery(std::move(cpq)); return false; } - if (ss->d_xskInfos.empty()) { - assignOutgoingUDPQueryToBackend(ss, dh->id, dq, query, true); + if (backend->d_xskInfos.empty()) { + assignOutgoingUDPQueryToBackend(backend, dnsHeader->id, dnsQuestion, query, true); return false; } - else { - assignOutgoingUDPQueryToBackend(ss, dh->id, dq, query, false); - auto sourceAddr = ss->pickSourceAddressForSending(); - packet.setAddr(sourceAddr, ss->d_config.sourceMACAddr, ss->d_config.remote, ss->d_config.destMACAddr); - packet.setPayload(query); - packet.rewrite(); - return true; - } + + assignOutgoingUDPQueryToBackend(backend, dnsHeader->id, dnsQuestion, query, false); + auto sourceAddr = backend->pickSourceAddressForSending(); + packet.setAddr(sourceAddr, backend->d_config.sourceMACAddr, backend->d_config.remote, backend->d_config.destMACAddr); + packet.setPayload(query); + packet.rewrite(); + return true; } catch (const std::exception& e) { vinfolog("Got an error in UDP question thread while parsing a query from %s, id %d: %s", remote.toStringWithPort(), queryId, e.what()); @@ -2012,16 +2013,16 @@ bool XskProcessQuery(ClientState& cs, LocalHolders& holders, XskPacket& packet) #ifndef DISABLE_RECVMMSG #if defined(HAVE_RECVMMSG) && defined(HAVE_SENDMMSG) && defined(MSG_WAITFORONE) -static void MultipleMessagesUDPClientThread(ClientState* cs, LocalHolders& holders) +static void MultipleMessagesUDPClientThread(ClientState* clientState, LocalHolders& holders) { struct MMReceiver { PacketBuffer packet; ComboAddress remote; ComboAddress dest; - struct iovec iov; + iovec iov{}; /* used by HarvestDestinationAddress */ - cmsgbuf_aligned cbuf; + cmsgbuf_aligned cbuf{}; }; const size_t vectSize = g_udpVectorSize; @@ -2029,23 +2030,24 @@ static void MultipleMessagesUDPClientThread(ClientState* cs, LocalHolders& holde throw std::runtime_error("The value of setUDPMultipleMessagesVectorSize is too high, the maximum value is " + std::to_string(std::numeric_limits::max())); } - auto recvData = std::make_unique(vectSize); - auto msgVec = std::make_unique(vectSize); - auto outMsgVec = std::make_unique(vectSize); + auto recvData = std::vector(vectSize); + auto msgVec = std::vector(vectSize); + auto outMsgVec = std::vector(vectSize); /* the actual buffer is larger because: - we may have to add EDNS and/or ECS - we use it for self-generated responses (from rule or cache) but we only accept incoming payloads up to that size */ - const size_t initialBufferSize = getInitialUDPPacketBufferSize(cs->d_enableProxyProtocol); - const size_t maxIncomingPacketSize = getMaximumIncomingPacketSize(*cs); + const size_t initialBufferSize = getInitialUDPPacketBufferSize(clientState->d_enableProxyProtocol); + const size_t maxIncomingPacketSize = getMaximumIncomingPacketSize(*clientState); /* initialize the structures needed to receive our messages */ for (size_t idx = 0; idx < vectSize; idx++) { - recvData[idx].remote.sin4.sin_family = cs->local.sin4.sin_family; + recvData[idx].remote.sin4.sin_family = clientState->local.sin4.sin_family; recvData[idx].packet.resize(initialBufferSize); - fillMSGHdr(&msgVec[idx].msg_hdr, &recvData[idx].iov, &recvData[idx].cbuf, sizeof(recvData[idx].cbuf), reinterpret_cast(&recvData[idx].packet.at(0)), maxIncomingPacketSize, &recvData[idx].remote); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + fillMSGHdr(&msgVec[idx].msg_hdr, &recvData[idx].iov, &recvData[idx].cbuf, sizeof(recvData[idx].cbuf), reinterpret_cast(recvData[idx].packet.data()), maxIncomingPacketSize, &recvData[idx].remote); } /* go now */ @@ -2061,7 +2063,7 @@ static void MultipleMessagesUDPClientThread(ClientState* cs, LocalHolders& holde /* block until we have at least one message ready, but return as many as possible to save the syscall costs */ - int msgsGot = recvmmsg(cs->udpFD, msgVec.get(), vectSize, MSG_WAITFORONE | MSG_TRUNC, nullptr); + int msgsGot = recvmmsg(clientState->udpFD, msgVec.data(), vectSize, MSG_WAITFORONE | MSG_TRUNC, nullptr); if (msgsGot <= 0) { vinfolog("Getting UDP messages via recvmmsg() failed with: %s", stringerror()); @@ -2078,19 +2080,19 @@ static void MultipleMessagesUDPClientThread(ClientState* cs, LocalHolders& holde if (static_cast(got) < sizeof(struct dnsheader)) { ++dnsdist::metrics::g_stats.nonCompliantQueries; - ++cs->nonCompliantQueries; + ++clientState->nonCompliantQueries; continue; } recvData[msgIdx].packet.resize(got); - processUDPQuery(*cs, holders, msgh, remote, recvData[msgIdx].dest, recvData[msgIdx].packet, outMsgVec.get(), &msgsToSend, &recvData[msgIdx].iov, &recvData[msgIdx].cbuf); + processUDPQuery(*clientState, holders, msgh, remote, recvData[msgIdx].dest, recvData[msgIdx].packet, &outMsgVec, &msgsToSend, &recvData[msgIdx].iov, &recvData[msgIdx].cbuf); } /* immediate (not delayed or sent to a backend) responses (mostly from a rule, dynamic block or the cache) can be sent in batch too */ if (msgsToSend > 0 && msgsToSend <= static_cast(msgsGot)) { - int sent = sendmmsg(cs->udpFD, outMsgVec.get(), msgsToSend, 0); + int sent = sendmmsg(clientState->udpFD, outMsgVec.data(), msgsToSend, 0); if (sent < 0 || static_cast(sent) != msgsToSend) { vinfolog("Error sending responses with sendmmsg() (%d on %u): %s", sent, msgsToSend, stringerror()); @@ -2130,8 +2132,8 @@ static void udpClientThread(std::vector states) const size_t initialBufferSize = getInitialUDPPacketBufferSize(true); PacketBuffer packet(initialBufferSize); - struct msghdr msgh; - struct iovec iov; + msghdr msgh{}; + iovec iov{}; ComboAddress remote; ComboAddress dest; @@ -2164,6 +2166,7 @@ static void udpClientThread(std::vector states) remote.sin4.sin_family = param.cs->local.sin4.sin_family; /* used by HarvestDestinationAddress */ cmsgbuf_aligned cbuf; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) fillMSGHdr(&msgh, &iov, &cbuf, sizeof(cbuf), reinterpret_cast(&packet.at(0)), param.maxIncomingPacketSize, &remote); while (true) { try { @@ -2179,12 +2182,13 @@ static void udpClientThread(std::vector states) } else { auto callback = [&remote, &msgh, &iov, &packet, &handleOnePacket, initialBufferSize](int socket, FDMultiplexer::funcparam_t& funcparam) { - auto param = boost::any_cast(funcparam); + const auto* param = boost::any_cast(funcparam); try { remote.sin4.sin_family = param->cs->local.sin4.sin_family; packet.resize(initialBufferSize); /* used by HarvestDestinationAddress */ cmsgbuf_aligned cbuf; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) fillMSGHdr(&msgh, &iov, &cbuf, sizeof(cbuf), reinterpret_cast(&packet.at(0)), param->maxIncomingPacketSize, &remote); handleOnePacket(*param); } @@ -2196,14 +2200,13 @@ static void udpClientThread(std::vector states) } }; auto mplexer = std::unique_ptr(FDMultiplexer::getMultiplexerSilent(params.size())); - for (size_t idx = 0; idx < params.size(); idx++) { - const auto& param = params.at(idx); + for (const auto& param : params) { mplexer->addReadFD(param.socket, callback, ¶m); } - struct timeval tv; + timeval now{}; while (true) { - mplexer->run(&tv, -1); + mplexer->run(&now, -1); } } } @@ -2318,7 +2321,7 @@ static void secPollThread() catch (...) { } // coverity[store_truncates_time_t] - sleep(g_secPollInterval); + std::this_thread::sleep_for(std::chrono::seconds(g_secPollInterval)); } } #endif /* DISABLE_SECPOLL */ @@ -2336,7 +2339,7 @@ static void healthChecksThread() auto states = g_dstates.getLocal(); // this points to the actual shared_ptrs! for (;;) { - struct timeval now; + timeval now{}; gettimeofday(&now, nullptr); auto elapsedTimeUsec = uSec(now - lastRound); if (elapsedTimeUsec < intervalUsec) { @@ -2348,7 +2351,7 @@ static void healthChecksThread() } std::unique_ptr mplexer{nullptr}; - for (auto& dss : *states) { + for (const auto& dss : *states) { dss->updateStatisticsInfo(); dss->handleUDPTimeouts(); @@ -2372,28 +2375,34 @@ static void healthChecksThread() } } -static void bindAny(int af, int sock) +static void bindAny(int addressFamily, int sock) { __attribute__((unused)) int one = 1; #ifdef IP_FREEBIND - if (setsockopt(sock, IPPROTO_IP, IP_FREEBIND, &one, sizeof(one)) < 0) + if (setsockopt(sock, IPPROTO_IP, IP_FREEBIND, &one, sizeof(one)) < 0) { warnlog("Warning: IP_FREEBIND setsockopt failed: %s", stringerror()); + } #endif #ifdef IP_BINDANY - if (af == AF_INET) - if (setsockopt(sock, IPPROTO_IP, IP_BINDANY, &one, sizeof(one)) < 0) + if (addressFamily == AF_INET) { + if (setsockopt(sock, IPPROTO_IP, IP_BINDANY, &one, sizeof(one)) < 0) { warnlog("Warning: IP_BINDANY setsockopt failed: %s", stringerror()); + } + } #endif #ifdef IPV6_BINDANY - if (af == AF_INET6) - if (setsockopt(sock, IPPROTO_IPV6, IPV6_BINDANY, &one, sizeof(one)) < 0) + if (addressFamily == AF_INET6) { + if (setsockopt(sock, IPPROTO_IPV6, IPV6_BINDANY, &one, sizeof(one)) < 0) { warnlog("Warning: IPV6_BINDANY setsockopt failed: %s", stringerror()); + } + } #endif #ifdef SO_BINDANY - if (setsockopt(sock, SOL_SOCKET, SO_BINDANY, &one, sizeof(one)) < 0) + if (setsockopt(sock, SOL_SOCKET, SO_BINDANY, &one, sizeof(one)) < 0) { warnlog("Warning: SO_BINDANY setsockopt failed: %s", stringerror()); + } #endif } @@ -2458,10 +2467,10 @@ static void checkFileDescriptorsLimits(size_t udpBindsCount, size_t tcpBindsCoun requiredFDsCount++; /* history file */ requiredFDsCount++; - struct rlimit rl; - getrlimit(RLIMIT_NOFILE, &rl); - if (rl.rlim_cur <= requiredFDsCount) { - warnlog("Warning, this configuration can use more than %d file descriptors, web server and console connections not included, and the current limit is %d.", std::to_string(requiredFDsCount), std::to_string(rl.rlim_cur)); + rlimit resourceLimits{}; + getrlimit(RLIMIT_NOFILE, &resourceLimits); + if (resourceLimits.rlim_cur <= requiredFDsCount) { + warnlog("Warning, this configuration can use more than %d file descriptors, web server and console connections not included, and the current limit is %d.", std::to_string(requiredFDsCount), std::to_string(resourceLimits.rlim_cur)); #ifdef HAVE_SYSTEMD warnlog("You can increase this value by using LimitNOFILE= in the systemd unit file or ulimit."); #else @@ -2761,7 +2770,7 @@ static void sigTermHandler(int) #endif #endif -static void sigTermHandler(int) +static void sigTermHandler([[maybe_unused]] int sig) { #if !defined(__SANITIZE_THREAD__) /* TSAN is rightfully unhappy about this: diff --git a/pdns/dnsdistdist/dnsdist.hh b/pdns/dnsdistdist/dnsdist.hh index 5f3bb816288f..7c5d77a7c500 100644 --- a/pdns/dnsdistdist/dnsdist.hh +++ b/pdns/dnsdistdist/dnsdist.hh @@ -1089,7 +1089,7 @@ public: }; using servers_t = vector>; -void responderThread(std::shared_ptr state); +void responderThread(std::shared_ptr dss); extern LockGuarded g_lua; extern std::string g_outputBuffer; // locking for this is ok, as locked by g_luamutex @@ -1242,7 +1242,7 @@ bool checkQueryHeaders(const struct dnsheader& dnsHeader, ClientState& clientSta extern std::vector> g_dnsCryptLocals; bool handleDNSCryptQuery(PacketBuffer& packet, DNSCryptQuery& query, bool tcp, time_t now, PacketBuffer& response); -bool checkDNSCryptQuery(const ClientState& cs, PacketBuffer& query, std::unique_ptr& dnsCryptQuery, time_t now, bool tcp); +bool checkDNSCryptQuery(const ClientState& clientState, PacketBuffer& query, std::unique_ptr& dnsCryptQuery, time_t now, bool tcp); #include "dnsdist-snmp.hh" @@ -1270,7 +1270,7 @@ bool processResponderPacket(std::shared_ptr& dss, PacketBuffer& bool assignOutgoingUDPQueryToBackend(std::shared_ptr& downstream, uint16_t queryID, DNSQuestion& dnsQuestion, PacketBuffer& query, bool actuallySend = true); -ssize_t udpClientSendRequestToBackend(const std::shared_ptr& ss, const int sd, const PacketBuffer& request, bool healthCheck = false); +ssize_t udpClientSendRequestToBackend(const std::shared_ptr& backend, const int socketDesc, const PacketBuffer& request, bool healthCheck = false); bool sendUDPResponse(int origFD, const PacketBuffer& response, const int delayMsec, const ComboAddress& origDest, const ComboAddress& origRemote); void handleResponseSent(const DNSName& qname, const QType& qtype, double udiff, const ComboAddress& client, const ComboAddress& backend, unsigned int size, const dnsheader& cleartextDH, dnsdist::Protocol outgoingProtocol, dnsdist::Protocol incomingProtocol, bool fromBackend); void handleResponseSent(const InternalQueryState& ids, double udiff, const ComboAddress& client, const ComboAddress& backend, unsigned int size, const dnsheader& cleartextDH, dnsdist::Protocol outgoingProtocol, bool fromBackend); From 7678ac23d923b78ba2d84d51e902cfce222bbd8f Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Wed, 6 Mar 2024 16:49:30 +0100 Subject: [PATCH 25/25] dnsdist: Delint dnsdist-protobuf.cc --- pdns/dnsdistdist/dnsdist-protobuf.cc | 83 ++++++++++++++-------------- 1 file changed, 42 insertions(+), 41 deletions(-) diff --git a/pdns/dnsdistdist/dnsdist-protobuf.cc b/pdns/dnsdistdist/dnsdist-protobuf.cc index 30445ed24f18..d3b9200dc7c2 100644 --- a/pdns/dnsdistdist/dnsdist-protobuf.cc +++ b/pdns/dnsdistdist/dnsdist-protobuf.cc @@ -127,17 +127,17 @@ void DNSDistProtoBufMessage::serialize(std::string& data) const if ((data.capacity() - data.size()) < 128) { data.reserve(data.size() + 128); } - pdns::ProtoZero::Message m{data}; + pdns::ProtoZero::Message msg{data}; - m.setType(d_type); + msg.setType(d_type); if (d_time) { - m.setTime(d_time->first, d_time->second); + msg.setTime(d_time->first, d_time->second); } else { - struct timespec ts; - gettime(&ts, true); - m.setTime(ts.tv_sec, ts.tv_nsec / 1000); + timespec now{}; + gettime(&now, true); + msg.setTime(now.tv_sec, now.tv_nsec / 1000); } const auto distProto = d_dq.getProtocol(); @@ -151,11 +151,11 @@ void DNSDistProtoBufMessage::serialize(std::string& data) const } else if (distProto == dnsdist::Protocol::DoH) { protocol = pdns::ProtoZero::Message::TransportProtocol::DoH; - m.setHTTPVersion(pdns::ProtoZero::Message::HTTPVersion::HTTP2); + msg.setHTTPVersion(pdns::ProtoZero::Message::HTTPVersion::HTTP2); } else if (distProto == dnsdist::Protocol::DoH3) { protocol = pdns::ProtoZero::Message::TransportProtocol::DoH; - m.setHTTPVersion(pdns::ProtoZero::Message::HTTPVersion::HTTP3); + msg.setHTTPVersion(pdns::ProtoZero::Message::HTTPVersion::HTTP3); } else if (distProto == dnsdist::Protocol::DNSCryptUDP) { protocol = pdns::ProtoZero::Message::TransportProtocol::DNSCryptUDP; @@ -167,68 +167,69 @@ void DNSDistProtoBufMessage::serialize(std::string& data) const protocol = pdns::ProtoZero::Message::TransportProtocol::DoQ; } - m.setRequest(d_dq.ids.d_protoBufData && d_dq.ids.d_protoBufData->uniqueId ? *d_dq.ids.d_protoBufData->uniqueId : getUniqueID(), d_requestor ? *d_requestor : d_dq.ids.origRemote, d_responder ? *d_responder : d_dq.ids.origDest, d_question ? d_question->d_name : d_dq.ids.qname, d_question ? d_question->d_type : d_dq.ids.qtype, d_question ? d_question->d_class : d_dq.ids.qclass, d_dq.getHeader()->id, protocol, d_bytes ? *d_bytes : d_dq.getData().size()); + msg.setRequest(d_dq.ids.d_protoBufData && d_dq.ids.d_protoBufData->uniqueId ? *d_dq.ids.d_protoBufData->uniqueId : getUniqueID(), d_requestor ? *d_requestor : d_dq.ids.origRemote, d_responder ? *d_responder : d_dq.ids.origDest, d_question ? d_question->d_name : d_dq.ids.qname, d_question ? d_question->d_type : d_dq.ids.qtype, d_question ? d_question->d_class : d_dq.ids.qclass, d_dq.getHeader()->id, protocol, d_bytes ? *d_bytes : d_dq.getData().size()); if (d_serverIdentity) { - m.setServerIdentity(*d_serverIdentity); + msg.setServerIdentity(*d_serverIdentity); } else if (d_ServerIdentityRef != nullptr) { - m.setServerIdentity(*d_ServerIdentityRef); + msg.setServerIdentity(*d_ServerIdentityRef); } if (d_ednsSubnet) { - m.setEDNSSubnet(*d_ednsSubnet, 128); + msg.setEDNSSubnet(*d_ednsSubnet, 128); } - m.startResponse(); + msg.startResponse(); if (d_queryTime) { // coverity[store_truncates_time_t] - m.setQueryTime(d_queryTime->first, d_queryTime->second); + msg.setQueryTime(d_queryTime->first, d_queryTime->second); } else { - m.setQueryTime(d_dq.getQueryRealTime().tv_sec, d_dq.getQueryRealTime().tv_nsec / 1000); + msg.setQueryTime(d_dq.getQueryRealTime().tv_sec, d_dq.getQueryRealTime().tv_nsec / 1000); } if (d_dr != nullptr) { - m.setResponseCode(d_rcode ? *d_rcode : d_dr->getHeader()->rcode); - m.addRRsFromPacket(reinterpret_cast(d_dr->getData().data()), d_dr->getData().size(), d_includeCNAME); + msg.setResponseCode(d_rcode ? *d_rcode : d_dr->getHeader()->rcode); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + msg.addRRsFromPacket(reinterpret_cast(d_dr->getData().data()), d_dr->getData().size(), d_includeCNAME); } else { if (d_rcode) { - m.setResponseCode(*d_rcode); + msg.setResponseCode(*d_rcode); } } - for (const auto& rr : d_additionalRRs) { - m.addRR(rr.d_name, rr.d_type, rr.d_class, rr.d_ttl, rr.d_data); + for (const auto& arr : d_additionalRRs) { + msg.addRR(arr.d_name, arr.d_type, arr.d_class, arr.d_ttl, arr.d_data); } for (const auto& tag : d_additionalTags) { - m.addPolicyTag(tag); + msg.addPolicyTag(tag); } - m.commitResponse(); + msg.commitResponse(); if (d_dq.ids.d_protoBufData) { const auto& pbData = d_dq.ids.d_protoBufData; if (!pbData->d_deviceName.empty()) { - m.setDeviceName(pbData->d_deviceName); + msg.setDeviceName(pbData->d_deviceName); } if (!pbData->d_deviceID.empty()) { - m.setDeviceId(pbData->d_deviceID); + msg.setDeviceId(pbData->d_deviceID); } if (!pbData->d_requestorID.empty()) { - m.setRequestorId(pbData->d_requestorID); + msg.setRequestorId(pbData->d_requestorID); } } for (const auto& [key, values] : d_metaTags) { if (!values.d_strings.empty() || !values.d_integers.empty()) { - m.setMeta(key, values.d_strings, values.d_integers); + msg.setMeta(key, values.d_strings, values.d_integers); } else { /* the MetaValue field is _required_ to exist, even if we have no value */ - m.setMeta(key, {std::string()}, {}); + msg.setMeta(key, {std::string()}, {}); } } } @@ -236,18 +237,18 @@ void DNSDistProtoBufMessage::serialize(std::string& data) const ProtoBufMetaKey::ProtoBufMetaKey(const std::string& key) { auto& idx = s_types.get(); - auto it = idx.find(key); - if (it != idx.end()) { - d_type = it->d_type; + auto typeIt = idx.find(key); + if (typeIt != idx.end()) { + d_type = typeIt->d_type; return; } else { auto [prefix, variable] = splitField(key, ':'); if (!variable.empty()) { - it = idx.find(prefix); - if (it != idx.end() && it->d_prefix) { - d_type = it->d_type; - if (it->d_numeric) { + typeIt = idx.find(prefix); + if (typeIt != idx.end() && typeIt->d_prefix) { + d_type = typeIt->d_type; + if (typeIt->d_numeric) { try { d_numericSubKey = std::stoi(variable); } @@ -256,7 +257,7 @@ ProtoBufMetaKey::ProtoBufMetaKey(const std::string& key) } } else { - if (!it->d_caseSensitive) { + if (!typeIt->d_caseSensitive) { boost::algorithm::to_lower(variable); } d_subKey = variable; @@ -271,21 +272,21 @@ ProtoBufMetaKey::ProtoBufMetaKey(const std::string& key) std::vector ProtoBufMetaKey::getValues(const DNSQuestion& dnsquestion) const { auto& idx = s_types.get(); - auto it = idx.find(d_type); - if (it == idx.end()) { + auto typeIt = idx.find(d_type); + if (typeIt == idx.end()) { throw std::runtime_error("Trying to get the values of an unsupported type: " + std::to_string(static_cast(d_type))); } - return (it->d_func)(dnsquestion, d_subKey, d_numericSubKey); + return (typeIt->d_func)(dnsquestion, d_subKey, d_numericSubKey); } const std::string& ProtoBufMetaKey::getName() const { auto& idx = s_types.get(); - auto it = idx.find(d_type); - if (it == idx.end()) { + auto typeIt = idx.find(d_type); + if (typeIt == idx.end()) { throw std::runtime_error("Trying to get the name of an unsupported type: " + std::to_string(static_cast(d_type))); } - return it->d_name; + return typeIt->d_name; } const ProtoBufMetaKey::TypeContainer ProtoBufMetaKey::s_types = {