package app import ( "context" "errors" "fmt" "log/slog" "net" "net/http" "os" "os/signal" "path/filepath" "runtime/debug" "strings" "sync" "syscall" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) // acquireLock creates /.lock exclusively: its presence means "hub // running" and makes `urutau import` refuse. It is removed on a normal stop. func acquireLock(dir string) (release func(), err error) { if err := os.MkdirAll(dir, 0o700); err != nil { return nil, err } path := filepath.Join(dir, lockName) f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { if errors.Is(err, os.ErrExist) { pid, _ := os.ReadFile(path) return nil, fmt.Errorf("%s exists (pid %s): another hub uses this data directory; if none is running, remove the file", path, strings.TrimSpace(string(pid))) } return nil, err } fmt.Fprintf(f, "%d\n", os.Getpid()) f.Close() return func() { os.Remove(path) }, nil } // nodeSet implements server.NodeSet over the manager. type nodeSet struct{ m *hub.Manager } func (n nodeSet) node(host string) *Node { nd, _ := n.m.Get(host).(*Node) return nd } func (n nodeSet) Hosts() []string { var out []string for _, x := range n.m.Nodes() { out = append(out, x.Name()) } return out } func (n nodeSet) Enforce(h string) *enforce.Engine { if nd := n.node(h); nd != nil { return nd.Enf } return nil } func (n nodeSet) Egress(h string) *egress.Engine { if nd := n.node(h); nd != nil { return nd.EgressEngine() } return nil } func (n nodeSet) Incidents(h string) *incidents.Store { if nd := n.node(h); nd != nil { return nd.Inc } return nil } // Hub is a running hub without its listener: Serve and the tests build one. type Hub struct { Handler http.Handler Mgr *hub.Manager Primary *Node Fed *fed.Hub wg *sync.WaitGroup } // Wait blocks until every background goroutine stopped (cancel the context // first); the nodes then have saved their snapshots. func (h *Hub) Wait() { h.wg.Wait() h.Mgr.Close() } // NewHub validates c and starts the nodes and the background work until ctx is done. func NewHub(ctx context.Context, c Config, token string, log *slog.Logger) (*Hub, error) { if err := c.Validate(token); err != nil { return nil, err } wg := &sync.WaitGroup{} watchTorExits(ctx, c.TorExits, 24*time.Hour, log) if !strings.EqualFold(c.TorAuto, "off") { watchTorLists(ctx, filepath.Join(c.DataDir, "tor"), torExitURL, torRelayURL, 6*time.Hour, log) } rd := rdns.New() gr, gerr := geo.Open(c.GeoDir) if gerr != nil { log.Warn("geo databases unavailable, locations disabled until they are downloaded", "dir", c.GeoDir, "err", gerr) gr = nil } en := enricher{g: gr} // Real build dates of the geo databases for /api/v1/integrity (0 = unknown). store.GeoBuilds = func() (int64, int64) { if gr == nil { return 0, 0 } s := gr.Status() var city, asn int64 if !s.City.Build.IsZero() { city = s.City.Build.Unix() } if !s.ASN.Build.IsZero() { asn = s.ASN.Build.Unix() } return city, asn } var mgr *hub.Manager sh := &shared{c: c, log: log, en: en, rd: rd, ctx: ctx, wg: wg, mgr: func() *hub.Manager { return mgr }} mgr, err := hub.NewManager(c.DataDir, c.Name, Version, func(name string, primary bool, rec hub.Probe) (hub.Node, error) { return sh.newNode(name, primary, rec) }, log) if err != nil { return nil, err } if err := mgr.Load(); err != nil { return nil, err } prim, _ := mgr.Get(c.Name).(*Node) if prim == nil { return nil, fmt.Errorf("primary node %q was not created", c.Name) } if prim.Enf != nil { server.SetEnforce(prim.Enf) } fh := fed.NewHub(func() []fed.Backend { var out []fed.Backend for _, n := range mgr.Nodes() { if nd, ok := n.(*Node); ok && !nd.Primary { out = append(out, nd) } } return out }) tproxy, _ := core.ParseCIDRs(c.TrustedProxy) ign, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted) bindHost, _, _ := net.SplitHostPort(c.Bind) h := server.New(server.Options{Token: token, TrustedProxy: tproxy, Ignore: ign, AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: prim.St, Hub: fh, Incidents: prim.Inc, Probes: mgr, Nodes: nodeSet{mgr}}) server.StartIncidentSync(ctx, wg) wg.Add(2) go func() { defer wg.Done(); rd.Run(ctx) }() go func() { defer wg.Done(); fh.Run(ctx) }() if gr != nil && c.GeoUpdate > 0 { gr.StartUpdater(ctx, c.GeoUpdate, &http.Client{Timeout: 10 * time.Minute}) } if strings.EqualFold(c.EnforceShare, "on") { wg.Add(1) go func() { defer wg.Done() shareDecisions(ctx, func() []*Node { var out []*Node for _, n := range mgr.Nodes() { if nd, ok := n.(*Node); ok { out = append(out, nd) } } return out }) }() } return &Hub{Handler: h, Mgr: mgr, Primary: prim, Fed: fh, wg: wg}, nil } // Serve runs the daemon until SIGTERM/SIGINT; it returns nil on a clean stop. func Serve(c Config) error { log := slog.New(slog.NewTextHandler(os.Stderr, nil)) warn, err := CheckRemovedEnv(os.LookupEnv) if err != nil { return err } for _, k := range warn { log.Warn("variable of the 1.x image ignored: the log paths belong to the probe now", "var", k) } token, terr := Secret("URUTAU_TOKEN") if terr != nil { return terr } if err := c.Validate(token); err != nil { return err } if os.Getenv("GOMEMLIMIT") == "" { debug.SetMemoryLimit(SoftMemoryLimit) } release, err := acquireLock(c.DataDir) if err != nil { return err } defer release() ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) defer stop() hb, err := NewHub(ctx, c, token, log) if err != nil { return err } ln, err := net.Listen("tcp", c.Bind) if err != nil { stop() hb.Wait() return err } srv := server.HTTPServer(hb.Handler, ctx) log.Info("urutau started", "version", Version, "name", c.Name, "bind", ln.Addr().String(), "probes", len(hb.Mgr.Nodes()), "auth", !c.NoAuth) errc := make(chan error, 1) go func() { errc <- srv.Serve(ln) }() select { case err := <-errc: stop() hb.Wait() return err case <-ctx.Done(): } log.Info("shutting down") sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() _ = srv.Shutdown(sctx) hb.Wait() // every node saves its snapshot and flushes its tickets log.Info("snapshot saved") if err := <-errc; err != nil && !errors.Is(err, http.ErrServerClosed) { return fmt.Errorf("server: %w", err) } return nil } // LoadState restores the snapshot in dir. A missing file is a fresh start; a // corrupt or truncated one is set aside (.corrupt), logged, and the daemon // starts empty (the sources then backfill from the logs). func LoadState(st *store.Store, dir string, log *slog.Logger) map[string]store.Offset { path := SnapshotPath(dir) offsets, err := st.Load(path) if err != nil { log.Error("snapshot unreadable, starting fresh", "err", err) _ = os.Rename(path, path+".corrupt") return map[string]store.Offset{} } if len(offsets) > 0 { log.Info("snapshot restored", "ips", st.IPCount()) } return offsets } func splitList(s string) []string { var out []string for _, p := range strings.Split(s, ",") { if p = strings.TrimSpace(p); p != "" { out = append(out, p) } } return out } // SoftMemoryLimit is the Go soft memory limit when GOMEMLIMIT is not set; see // the worst case measurements in the store tests. const SoftMemoryLimit = 256 << 20 func orDefault(v, def string) string { if v == "" { return def } return v }