| 1 |
package drunk |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"io" |
| 6 |
"log/slog" |
| 7 |
"sync/atomic" |
| 8 |
"time" |
| 9 |
|
| 10 |
"codeberg.org/miekg/dns" |
| 11 |
"codeberg.org/miekg/dns/cmd/atomdns/internal/dnsctx" |
| 12 |
"codeberg.org/miekg/dns/cmd/atomdns/internal/dnslog" |
| 13 |
"codeberg.org/miekg/dns/dnstest" |
| 14 |
"codeberg.org/miekg/dns/dnsutil" |
| 15 |
) |
| 16 |
|
| 17 |
type Drunk struct { |
| 18 |
i atomic.Uint64 // counter of queries |
| 19 |
drop uint64 |
| 20 |
delay uint64 |
| 21 |
truncate uint64 |
| 22 |
|
| 23 |
duration time.Duration |
| 24 |
} |
| 25 |
|
| 26 |
func (d *Drunk) HandlerFunc(next dns.HandlerFunc) dns.HandlerFunc { |
| 27 |
return dns.HandlerFunc(func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) { |
| 28 |
i := d.i.Load() |
| 29 |
d.i.Add(1) |
| 30 |
|
| 31 |
drop := d.drop > 0 && i%d.drop == 0 |
| 32 |
delay := d.delay > 0 && i%d.delay == 0 |
| 33 |
trunc := d.truncate > 0 && i%d.truncate == 0 |
| 34 |
|
| 35 |
m := r.Copy() |
| 36 |
dnsutil.SetReply(m, r) |
| 37 |
m.Authoritative = true |
| 38 |
m.Truncated = trunc |
| 39 |
|
| 40 |
rw := dnstest.NewRecorder(w) |
| 41 |
next.ServeDNS(ctx, rw, r) |
| 42 |
|
| 43 |
if drop || rw.Msg == nil { // drop or hijacked conn |
| 44 |
log().With(dnsctx.Id(ctx)).Debug("Dropping") |
| 45 |
return |
| 46 |
} |
| 47 |
if delay { |
| 48 |
log().With(dnsctx.Id(ctx)).Debug("Delaying", slog.Duration("delay", d.duration)) |
| 49 |
time.Sleep(d.duration) |
| 50 |
} |
| 51 |
if trunc { |
| 52 |
rw.Msg.Truncated = true |
| 53 |
// have to repack now |
| 54 |
if err := rw.Msg.Pack(); err != nil { |
| 55 |
dnslog.PackFail(ctx, log(), Err(err)) |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
io.Copy(w, rw.Msg) |
| 60 |
}) |
| 61 |
} |