| 1 |
package log |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"fmt" |
| 6 |
"log/slog" |
| 7 |
"os" |
| 8 |
"os/signal" |
| 9 |
"slices" |
| 10 |
"strings" |
| 11 |
"sync" |
| 12 |
"sync/atomic" |
| 13 |
|
| 14 |
"codeberg.org/miekg/dns/cmd/atomdns/internal/dnsctx" |
| 15 |
"codeberg.org/miekg/dns/cmd/atomdns/internal/dnsserver" |
| 16 |
) |
| 17 |
|
| 18 |
var ( |
| 19 |
state atomic.Bool |
| 20 |
startonce sync.Once |
| 21 |
shutonce sync.Once |
| 22 |
) |
| 23 |
|
| 24 |
func valid(val string) error { |
| 25 |
if !dnsctx.Valid(val) { |
| 26 |
return fmt.Errorf("invalid context key: %s", val) |
| 27 |
} |
| 28 |
if slices.Contains([]string{"ecs/addr", "id/id"}, val) { |
| 29 |
return fmt.Errorf("default context key used: %s", val) |
| 30 |
} |
| 31 |
return nil |
| 32 |
} |
| 33 |
|
| 34 |
func split(val string) (handler, key string) { |
| 35 |
before, after, _ := strings.Cut(val, "/") |
| 36 |
return before, after |
| 37 |
} |
| 38 |
|
| 39 |
func (l *Log) Setup(co *dnsserver.Controller) error { |
| 40 |
l.Contexts = map[string][]string{} |
| 41 |
l.UnixAddr = co.Global.UnixAddr |
| 42 |
|
| 43 |
co.Next() // "log" |
| 44 |
if co.NextBlock(0) { |
| 45 |
err := valid(co.Val()) |
| 46 |
if err != nil { |
| 47 |
return co.PropErr(err) |
| 48 |
} |
| 49 |
h, k := split(co.Val()) |
| 50 |
l.Contexts[h] = append(l.Contexts[h], k) |
| 51 |
|
| 52 |
for co.NextLine() { |
| 53 |
if co.Val() == "}" { |
| 54 |
break |
| 55 |
} |
| 56 |
err := valid(co.Val()) |
| 57 |
if err != nil { |
| 58 |
return co.PropErr(err) |
| 59 |
} |
| 60 |
h, k := split(co.Val()) |
| 61 |
l.Contexts[h] = append(l.Contexts[h], k) |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
state.Store(!co.Global.Disable) |
| 66 |
ctx, cancel := context.WithCancel(context.Background()) |
| 67 |
|
| 68 |
co.OnStartup(func() error { |
| 69 |
startonce.Do(func() { |
| 70 |
_log().Info("Startup", "signal", "USR1", slog.Bool("enabled", !co.Global.Disable)) |
| 71 |
sigchan := make(chan os.Signal, 1) |
| 72 |
go func() { |
| 73 |
signal.Notify(sigchan, SIGUSR1) |
| 74 |
for { |
| 75 |
select { |
| 76 |
case <-sigchan: |
| 77 |
signal.Notify(sigchan, SIGUSR1) |
| 78 |
if state.Load() { |
| 79 |
_log().Info("Received signal, disabling query logging") |
| 80 |
state.Store(false) |
| 81 |
} else { |
| 82 |
_log().Info("Received signal, enabling query logging") |
| 83 |
state.Store(true) |
| 84 |
} |
| 85 |
case <-ctx.Done(): |
| 86 |
return |
| 87 |
} |
| 88 |
} |
| 89 |
}() |
| 90 |
}) |
| 91 |
return nil |
| 92 |
}) |
| 93 |
|
| 94 |
co.OnShutdown(func() error { |
| 95 |
shutonce.Do(func() { |
| 96 |
_log().Info("Shutdown", "signal", "USR1") |
| 97 |
cancel() |
| 98 |
}) |
| 99 |
return nil |
| 100 |
}) |
| 101 |
|
| 102 |
co.OnReset(func() { |
| 103 |
startonce = sync.Once{} |
| 104 |
shutonce = sync.Once{} |
| 105 |
}) |
| 106 |
|
| 107 |
return nil |
| 108 |
} |