package server import ( "context" "encoding/json" "net/http" "sort" "sync/atomic" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress" ) func init() { registerUserRoute("GET /api/v1/egress", func(s *Server) http.HandlerFunc { return s.egressAPI }) } var egressEngine atomic.Pointer[egress.Engine] // SetEgress attaches the egress engine (nil disables the endpoints). It is // called by the daemon wiring, before or after the server starts. func SetEgress(e *egress.Engine) { egressEngine.Store(e) } type egressOut struct { Enabled bool `json:"enabled"` Source egress.SourceInfo `json:"source"` egress.Report SuppressedCount int `json:"suppressed_count"` } // egressAPI: GET /api/v1/egress?range=24h&host=all|. On a hub the // local engine and the peers' reports are merged, items carrying "host". func (s *Server) egressAPI(w http.ResponseWriter, r *http.Request) { rg, ok := s.rangeOf(w, r) if !ok { return } host := r.URL.Query().Get("host") if len(host) > 253 { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host"}) return } local, peers, only, ok := s.studyHosts(w, host) if !ok { return } from, to := rg.Bounds(s.opt.Store.Now().Unix()) eng := egressEngine.Load() out := egressOut{Source: egress.SourceInfo{State: "disabled"}} if eng != nil { out.Source = eng.Info() out.Enabled = true } rep, peerOn := s.egressReport(r.Context(), from, to, local, peers, only) if peerOn { out.Enabled = true } // incidents are fed only by the 60 s loop, never by a request out.Report = rep out.SuppressedCount = s.annotateFindings(&out.Report, r.URL.Query().Get("suppressed") == "1") writeJSON(w, 200, out) } // egressReport builds the report of the window: the local engine and, on a hub, // the peers' reports merged (items carrying "host"). peerOn is true when a peer answered. func (s *Server) egressReport(ctx context.Context, from, to int64, local, peers bool, only string) (rep egress.Report, peerOn bool) { eng := egressEngine.Load() rep = egress.EmptyReport() if local && eng != nil { rep = eng.Report(from, to) } if peers && s.opt.Hub != nil { merged := egress.EmptyReport() merged.Timeline.Start = rep.Timeline.Start if local && eng != nil { rep.Stamp(s.opt.Store.Name()) merged.Merge(rep, s.opt.Store.Name()) } raws := s.opt.Hub.EgressFor(ctx, from, to, only) names := make([]string, 0, len(raws)) for n := range raws { names = append(names, n) } sort.Strings(names) for _, n := range names { var pr egress.Report if json.Unmarshal(raws[n], &pr) != nil { continue } pr.Sanitize(n) merged.Merge(pr, n) peerOn = true } rep = merged } return rep, peerOn }