package server import ( "net/http" "net/url" "slices" "sort" "strconv" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) func init() { // GET /api/v1/sessions/funnel?range|from&to&host: every session of the // period counted by stage, plus the 200 sessions the study keeps and the // escalation chains. With peers the counts fall back to the merged sample. registerUserRoute("GET /api/v1/sessions/funnel", func(s *Server) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { p, ok := s.periodStudy(w, r) if !ok { return } var counts *store.StageCounts if eq, ok := s.eventFilter(w, r, 24*time.Hour); ok { if local, peers, _, ok := s.studyHosts(w, eq.Host); ok && local && !peers && s.userSlot(w) { defer func() { <-s.user }() pq := store.PeriodQuery{From: eq.From, To: eq.To, IP: eq.IP, Cat: eq.Cat, Fam: eq.Fam} if n, err := strconv.ParseInt(r.URL.Query().Get("gap"), 10, 64); err == nil { pq.Gap = n } c := s.opt.Store.CountStages(pq) counts = &c } } writeJSON(w, 200, pagedFunnel(store.FunnelOf(p, counts), r.URL.Query())) } }) } // funnelPage is the funnel with its session list cut to one page; hosts and // fams list every value of the (unfiltered) study for the filter menus. type funnelPage struct { store.FunnelOut Hosts []string `json:"hosts"` Fams []string `json:"fams"` pageTotal } // pagedFunnel filters (stage, host, fam) and paginates the session list after // the peers were merged; the funnel counts always cover the whole study. func pagedFunnel(f store.FunnelOut, q url.Values) funnelPage { hosts, fams := map[string]bool{}, map[string]bool{} for _, x := range f.Sessions { for _, h := range x.Hosts { hosts[h] = true } for k := range x.Fams { fams[k] = true } } stage, host, fam := q.Get("stage"), q.Get("host_f"), q.Get("fam") list := make([]intel.Session, 0, len(f.Sessions)) for _, x := range f.Sessions { st := x.Stage if st == "" { st = "recon" } if (stage != "" && st != stage) || (fam != "" && x.Fams[fam] == 0) { continue } if host != "" && !slices.Contains(x.Hosts, host) { continue } list = append(list, x) } page, per := pageParams(q) from, to := window(len(list), page, per) f.Sessions = list[from:to] return funnelPage{f, sortedKeys(hosts), sortedKeys(fams), pageTotal{metaOf(len(list), page, per), len(list)}} } func sortedKeys(m map[string]bool) []string { out := make([]string, 0, len(m)) for k := range m { out = append(out, k) } sort.Strings(out) return out }