204-black_hole-apply-Fisher-Yates-shuffle-algorithm-to-r.patch 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. From e34dca717e78d24a84b98c2b5d371c4253b7e260 Mon Sep 17 00:00:00 2001
  2. From: sbwml <[email protected]>
  3. Date: Wed, 20 Sep 2023 14:51:19 +0800
  4. Subject: [PATCH 4/5] black_hole: apply Fisher-Yates shuffle algorithm to
  5. randomize IP order
  6. ---
  7. plugin/executable/black_hole/black_hole.go | 15 +++++++++++++++
  8. 1 file changed, 15 insertions(+)
  9. --- a/plugin/executable/black_hole/black_hole.go
  10. +++ b/plugin/executable/black_hole/black_hole.go
  11. @@ -27,6 +27,8 @@ import (
  12. "github.com/miekg/dns"
  13. "net/netip"
  14. "strings"
  15. + "math/rand"
  16. + "sync"
  17. )
  18. const PluginType = "black_hole"
  19. @@ -40,6 +42,7 @@ var _ sequence.Executable = (*BlackHole)
  20. type BlackHole struct {
  21. ipv4 []netip.Addr
  22. ipv6 []netip.Addr
  23. + shuffleMutex sync.Mutex
  24. }
  25. // QuickSetup format: [ipv4|ipv6] ...
  26. @@ -65,9 +68,21 @@ func NewBlackHole(ips []string) (*BlackH
  27. return b, nil
  28. }
  29. +func (b *BlackHole) shuffleIPs() {
  30. + b.shuffleMutex.Lock()
  31. + defer b.shuffleMutex.Unlock()
  32. + rand.Shuffle(len(b.ipv4), func(i, j int) {
  33. + b.ipv4[i], b.ipv4[j] = b.ipv4[j], b.ipv4[i]
  34. + })
  35. + rand.Shuffle(len(b.ipv6), func(i, j int) {
  36. + b.ipv6[i], b.ipv6[j] = b.ipv6[j], b.ipv6[i]
  37. + })
  38. +}
  39. +
  40. // Exec implements sequence.Executable. It set a response with given ips if
  41. // query has corresponding qtypes.
  42. func (b *BlackHole) Exec(_ context.Context, qCtx *query_context.Context) error {
  43. + b.shuffleIPs()
  44. if r := b.Response(qCtx.Q()); r != nil {
  45. qCtx.SetResponse(r)
  46. }