| 1 |
package url |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"errors" |
| 6 |
"fmt" |
| 7 |
"log/slog" |
| 8 |
"maps" |
| 9 |
"os" |
| 10 |
"path/filepath" |
| 11 |
"strings" |
| 12 |
|
| 13 |
"codeberg.org/miekg/dns/cmd/atomdns/handlers/dbfile/zone" |
| 14 |
"codeberg.org/miekg/dns/cmd/atomdns/internal/dnslog" |
| 15 |
"codeberg.org/miekg/dns/cmd/atomdns/internal/dnsserver" |
| 16 |
"codeberg.org/miekg/dns/dnsutil" |
| 17 |
) |
| 18 |
|
| 19 |
func (u *Url) Setup(co *dnsserver.Controller) error { |
| 20 |
u.Zones = map[string]*zone.Zone{} |
| 21 |
u.ctx, u.cancel = context.WithCancel(context.Background()) |
| 22 |
|
| 23 |
if co.Next() { |
| 24 |
if !co.Next() { |
| 25 |
return co.ArgErr() |
| 26 |
} |
| 27 |
u.Path = co.Path() |
| 28 |
|
| 29 |
for co.NextBlock(0) { |
| 30 |
if !strings.HasPrefix(co.Val(), "http://") && !strings.HasPrefix(co.Val(), "https://") { |
| 31 |
return co.PropErr(fmt.Errorf("URL needs to start with a scheme")) |
| 32 |
} |
| 33 |
u.URLs = append(u.URLs, strings.TrimSpace(co.Val())) |
| 34 |
} |
| 35 |
} |
| 36 |
if len(u.URLs) == 0 { |
| 37 |
return co.PropEmptyErr("url") |
| 38 |
} |
| 39 |
|
| 40 |
for _, z := range co.Keys() { |
| 41 |
u.Zones[dnsutil.Canonical(z)] = zone.New(z, u.Path) |
| 42 |
} |
| 43 |
co.OnStartup(func() error { |
| 44 |
log().Info("Startup", "reload", filepath.Base(u.Path)) |
| 45 |
u.RLock() |
| 46 |
zones := maps.Values(u.Zones) |
| 47 |
u.RUnlock() |
| 48 |
for z := range zones { |
| 49 |
alog := log().With(slog.String("zone", z.Origin()), slog.String("file", filepath.Base(z.Path))) |
| 50 |
_, err := os.Stat(z.Path) |
| 51 |
if errors.Is(err, os.ErrNotExist) { |
| 52 |
alog.Warn("Waiting for zone to appear") |
| 53 |
continue |
| 54 |
} |
| 55 |
if err := z.Load(); err != nil { |
| 56 |
return u.Err(err) |
| 57 |
} |
| 58 |
} |
| 59 |
return u.Reload() |
| 60 |
}) |
| 61 |
co.OnStartup(func() error { |
| 62 |
log().Info("Startup", "URLs", dnslog.GroupValues("URL", u.URLs), "file", filepath.Base(u.Path)) |
| 63 |
|
| 64 |
go func() { |
| 65 |
err := u.Fetch() |
| 66 |
if err != nil { |
| 67 |
alog := log().With("URLs", dnslog.GroupValues("URL", u.URLs), slog.String("file", filepath.Base(u.Path))) |
| 68 |
alog.Error("Failed to fetch", Err(err)) |
| 69 |
} |
| 70 |
}() |
| 71 |
return u.Refetch() |
| 72 |
}) |
| 73 |
|
| 74 |
co.OnShutdown(func() error { |
| 75 |
log().Info("Shutdown", "reload", filepath.Base(u.Path)) |
| 76 |
u.cancel() |
| 77 |
return nil |
| 78 |
}) |
| 79 |
co.OnShutdown(func() error { |
| 80 |
log().Info("Shutdown", "URLs", dnslog.GroupValues("URL", u.URLs)) |
| 81 |
u.cancel() |
| 82 |
return nil |
| 83 |
}) |
| 84 |
|
| 85 |
return nil |
| 86 |
} |