package app import ( "context" "encoding/json" "log/slog" "os" "path/filepath" "strings" "sync" "sync/atomic" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" "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" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire" ) // NodeDir is where the data of a probe lives: the primary probe uses the root // of the data directory (exactly the 1.x layout), the others probes/. func NodeDir(dataDir, name string, primary bool) string { if primary { return dataDir } return filepath.Join(dataDir, "probes", name) } // shared holds what every node of the hub uses together. type shared struct { c Config log *slog.Logger en enricher rd *rdns.Resolver ctx context.Context wg *sync.WaitGroup mgr func() *hub.Manager prim *Node mu sync.Mutex all []*Node } // Node is the store, the runner and the engines of one probe. It implements // hub.Node and fed.Backend. type Node struct { name string Dir string Primary bool St *store.Store Run *Runner Elog *evlog.Log Inc *incidents.Store Enf *enforce.Engine Q *hub.CmdQueue sh *shared egr atomic.Pointer[egress.Engine] egrSrc atomic.Pointer[egress.Source] egrActive atomic.Bool sources atomic.Pointer[[]string] // Last containers.map / resolv.conf the probe sent. The probe resends them // only when they change, so they are kept here and applied to every engine // this node builds (a configuration change rebuilds the engine). containers atomic.Pointer[[]byte] resolv atomic.Pointer[[]byte] } func (sh *shared) newNode(name string, primary bool, rec hub.Probe) (*Node, error) { c := sh.c dir := NodeDir(c.DataDir, name, primary) if err := os.MkdirAll(dir, 0o700); err != nil { return nil, err } loc, _ := store.ParseLocation(c.Location) if !primary { loc = nil } st := store.New(store.Config{Name: name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList(), Location: loc}) if rec.Location != nil { st.SetLocation(&store.Location{Lat: rec.Location.Lat, Lon: rec.Location.Lon, Label: rec.Location.Label}) } st.SetDomains(splitList(c.Domains)) n := &Node{name: name, Dir: dir, Primary: primary, St: st, sh: sh} if max, err := ParseSize(orDefault(c.EventsMax, DefaultEventsMax)); err == nil && max > 0 { el, err := evlog.Open(evlog.Options{Dir: filepath.Join(dir, "events"), MaxBytes: max, Retention: c.Retention, Log: sh.log}) if err != nil { sh.log.Warn("event registry unavailable, replay disabled", "node", name, "err", err) } else { n.Elog = el st.SetEventLog(el) sh.wg.Add(1) go func() { defer sh.wg.Done(); el.Run(sh.ctx) }() } } st.SetRDNS(sh.rd) offsets := LoadState(st, dir, sh.log) run, err := NewRemoteRunner(c, st, sh.log, dir) if err != nil { return nil, err } run.Enr = sh.en st.SetEnricher(sh.en) st.SetAttribution(Attribution) run.StartRemote(sh.ctx, offsets) n.Run = run run.EgressFeed = func(l []byte) { if e := n.egr.Load(); e != nil { e.Ingest(l) } } if n.Inc, err = incidents.Open(filepath.Join(dir, "incidents.json"), sh.log); err != nil { return nil, err } if n.Q, err = hub.OpenQueue(filepath.Join(dir, "commands.json")); err != nil { return nil, err } n.Enf = newEnforce(c, st, name, dir, n.Q.Enqueue, sh.en, func() bool { return true }) if n.Enf != nil { sh.wg.Add(1) go func() { defer sh.wg.Done(); n.Enf.Run(sh.ctx) }() } n.loadProbeFiles() if !egressOff(c) { if err := n.buildEgress(rec.Egress); err != nil { return nil, err } if strings.EqualFold(c.Egress, "on") { n.activateEgress() } } run.Extra = func() []store.SourceStatus { out := []store.SourceStatus{} if n.Primary { out = append(out, geoStatus(sh.en.g, c.GeoDir)) } return out } // save every minute, prune every 10 sh.wg.Add(1) go n.maintain() sh.mu.Lock() sh.all = append(sh.all, n) if primary { sh.prim = n } sh.mu.Unlock() return n, nil } func (n *Node) maintain() { defer n.sh.wg.Done() c := n.sh.c _ = c save := time.NewTicker(60 * time.Second) prune := time.NewTicker(10 * time.Minute) defer save.Stop() defer prune.Stop() for { select { case <-n.sh.ctx.Done(): n.Close() return case <-save.C: if err := n.Run.Save(); err != nil { n.sh.log.Warn("snapshot failed", "node", n.name, "err", err) } case <-prune.C: if k := n.St.Prune(); k > 0 { n.sh.log.Info("pruned old IPs", "node", n.name, "n", k) } } } } // Close writes the final snapshot and flushes the queue and the tickets. func (n *Node) Close() { if err := n.Run.Save(); err != nil { n.sh.log.Warn("final snapshot failed", "node", n.name, "err", err) } if n.Inc != nil { n.Inc.Flush() } if n.Q != nil { n.Q.Close() } } // probeFilePath is where the last copy of a file sent by the probe is kept, // so that after a hub restart the egress lines replayed by the probe are // judged with its resolvers and container names before it sends them again. func (n *Node) probeFilePath(name string) string { return filepath.Join(n.Dir, "probe-"+name) } func (n *Node) loadProbeFiles() { for _, f := range []struct { name string dst *atomic.Pointer[[]byte] }{{wire.FileContainers, &n.containers}, {wire.FileResolv, &n.resolv}} { b, err := os.ReadFile(n.probeFilePath(f.name)) if err != nil || len(b) > wire.MaxFileBytes { continue } f.dst.Store(&b) } } func (n *Node) saveProbeFile(name string, data []byte) { p := n.probeFilePath(name) if old, err := os.ReadFile(p); err == nil && string(old) == string(data) { return } tmp := p + ".tmp" if err := os.WriteFile(tmp, data, 0o600); err != nil { n.sh.log.Warn("probe file not saved", "node", n.name, "file", name, "err", err) return } if err := os.Rename(tmp, p); err != nil { n.sh.log.Warn("probe file not saved", "node", n.name, "file", name, "err", err) } } func (n *Node) buildEgress(eg hub.Egress) error { eng, err := newEgressEngine(n.sh.c, n.St, eg, n.Primary) if err != nil { return err } if b := n.containers.Load(); b != nil { eng.SetContainers(*b) } if b := n.resolv.Load(); b != nil { eng.SetResolv(*b) } n.egr.Store(eng) n.egrSrc.Store(egress.NewRemoteSource(eng, n.sh.log)) n.egrSrc.Load().SetState("waiting") if n.egrActive.Load() && n.Primary { server.SetEgress(eng) } return nil } func (n *Node) activateEgress() { e := n.egr.Load() if e == nil { return } n.egrActive.Store(true) if s := n.egrSrc.Load(); s != nil { s.SetState("following") } if n.Primary { server.SetEgress(e) } } // Egress returns the engine when the node has egress analysis active. func (n *Node) EgressEngine() *egress.Engine { if !n.egrActive.Load() { return nil } return n.egr.Load() } // ResetEgress rebuilds the engine with a new configuration (its in-memory // history starts over). func (n *Node) ResetEgress(eg hub.Egress) { if egressOff(n.sh.c) { return } if err := n.buildEgress(eg); err != nil { n.sh.log.Warn("egress configuration rejected", "node", n.name, "err", err) } } // ---- hub.Node ---- func (n *Node) Name() string { return n.name } func (n *Node) Ready() bool { return true } func (n *Node) Offsets() map[string]wire.Pos { return n.Run.RemoteOffsets() } func (n *Node) Apply(b wire.Batch) (int, int) { // Files first: egress lines of this very batch must be judged with the // resolvers and container names that came with them. for _, f := range b.Files { data := []byte(f.Data) switch f.Name { case wire.FileContainers: n.containers.Store(&data) case wire.FileResolv: n.resolv.Store(&data) default: continue } n.saveProbeFile(f.Name, data) if e := n.egr.Load(); e != nil { if f.Name == wire.FileContainers { e.SetContainers(data) } else { e.SetResolv(data) } } } acc, dup := n.Run.ApplyBatch(b.Lines) if acc > 0 { for _, l := range b.Lines { if l.Src == wire.SrcEgress { n.activateEgress() break } } } return acc, dup } func (n *Node) Hello(h wire.Hello) { n.sources.Store(&h.Sources) for _, s := range h.Sources { if s == wire.SrcEgress { n.activateEgress() } } } func (n *Node) Queue() *hub.CmdQueue { return n.Q } func (n *Node) SetStatus(st wire.Status, connected bool) { n.Run.SetRemoteStatus(st, connected) } func (n *Node) SetLocation(l *wire.Location) { if l == nil { n.St.SetLocation(nil) return } n.St.SetLocation(&store.Location{Lat: l.Lat, Lon: l.Lon, Label: l.Label}) } // ---- fed.Backend ---- func (n *Node) connected() bool { if m := n.sh.mgr(); m != nil { return m.Connected(n.name) } return false } func (n *Node) Online() bool { return n.connected() } func (n *Node) Location() *store.Location { return n.St.Location() } func (n *Node) Export(rg store.Range) store.PeerExport { return n.St.ExportFor(rg) } func (n *Node) Study(q store.PeriodQuery) store.PeerStudy { return n.St.StudyFor(q) } func (n *Node) EgressReport(from, to int64) (egress.Report, bool) { e := n.EgressEngine() if e == nil { return egress.Report{}, false } return e.Report(from, to), true } func (n *Node) Egress(from, to int64) json.RawMessage { rep, ok := n.EgressReport(from, to) if !ok { return nil } b, _ := json.Marshal(rep) return b } func (n *Node) Subscribe() (<-chan store.LiveEvent, func()) { in, stop := n.St.Subscribe() out := make(chan store.LiveEvent, 64) done := make(chan struct{}) go func() { for { select { case <-done: return case fe := <-in: le := n.St.Live(fe) select { case out <- le: default: } } } }() return out, func() { close(done); stop() } } func (n *Node) SubscribeVisits() (<-chan store.VisitMsg, func()) { return n.St.SubscribeVisits() } // HostInfo feeds fed.Hub.Hosts with the connection state of the probe. func (n *Node) HostInfo() store.HostInfo { hi := store.HostInfo{Name: n.name, Online: n.connected(), Live: n.connected(), Location: n.St.Location()} if m := n.sh.mgr(); m != nil { if in, ok := m.Info(n.name); ok { hi.Version, hi.LastSeen, hi.LatencyMS = in.Version, in.LastSeen, in.LagMS if !in.Connected && in.LastSeen > 0 { hi.Error = "probe offline" } } } return hi }