package store import ( "crypto/rand" "crypto/sha256" "net/url" "regexp" "sort" "strings" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" ) // Privacy: visitors are never stored. A visitor is the 64-bit prefix of // SHA-256(salt | ip | domain) (SHA-256(salt | ip) for the all-domains total) // kept in memory only while its UTC day lasts; the salt is random per process // and per day, so hashes cannot be linked across days, and nothing here // reaches a snapshot or the API. // // A visitor is a person with a real browser: a GET 2xx of a document by a // browser User-Agent (not a bot, tool or unknown client), not a prefetch and, // when the browser says so, with Sec-Fetch-Dest "document". The key leaves the // User-Agent out on purpose: scrapers rotate it per request from one address // (a measured 2.7x inflation), a person's browser does not. Everything else // that talks to a site (bots, tools, unknown or empty User-Agents) is counted // apart as non-human clients. const ( anMinutes = 49 * 60 // minute buckets (48 h plus one hour of margin) anDays = 31 // daily buckets for the tops maxDomains = 24 visCap = 20000 anTop = 40 latN = 12 otherDom = "(other)" ) var latBounds = [latN - 1]float64{5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000} type anHour struct { Hour int64 Req, Pages, Bots uint32 Bytes uint64 S [4]uint32 // 2xx 3xx 4xx 5xx Lat [latN]uint32 } type anDay struct { Day int64 Visitors, NonHuman uint32 Pages, Refs, Countries, Cities, Browsers, OSes, Devices, Bots map[string]uint32 } type domData struct { MinSt [anMinutes]int64 MinReq [anMinutes]uint32 MinPages [anMinutes]uint32 Hours [hourSlots]anHour Days [anDays]anDay Last int64 // unix time of the last request, for pruning idle domains // in memory only, never in a snapshot (unexported fields are skipped by gob) vis map[uint64]struct{} nh map[uint64]struct{} visDay int64 } // gDay is the all-domains daily total: one person on two sites counts once. type gDay struct { Day int64 Visitors, NonHuman uint32 } type trafficState struct { dom map[string]*domData gdays [anDays]gDay salt [16]byte saltDay int64 // in memory only gvis, gnh map[uint64]struct{} gvisDay int64 } var assetExt = map[string]bool{ "js": true, "mjs": true, "css": true, "png": true, "jpg": true, "jpeg": true, "gif": true, "svg": true, "ico": true, "webp": true, "avif": true, "woff": true, "woff2": true, "ttf": true, "otf": true, "eot": true, "map": true, "json": true, "xml": true, "txt": true, "mp4": true, "webm": true, "mp3": true, "ogg": true, "pdf": true, "zip": true, "gz": true, "wasm": true, "bmp": true, "webmanifest": true, "rss": true, "atom": true, } // isHuman reports whether the User-Agent belongs to a real browser. func isHuman(e core.Enrich) bool { if e.Bot || e.Tool { return false } switch e.Device { case "desktop", "mobile", "tablet": return true } return false } func isAssetPath(p string) bool { if i := strings.IndexAny(p, "?#"); i >= 0 { p = p[:i] } i := strings.LastIndexByte(p, '.') return i >= 0 && i > strings.LastIndexByte(p, '/') && assetExt[strings.ToLower(p[i+1:])] } func isPageView(ev core.Event) bool { if ev.Method != "GET" || ev.Status < 200 || ev.Status > 299 || ev.Prefetch { return false } // A browser that says what it is fetching: only a navigation is a page // (fetch/XHR is "empty", frames "iframe"). No header: cannot tell, accept. if d := ev.FetchDest; d != "" && d != "document" { return false } p := ev.Path if i := strings.IndexAny(p, "?#"); i >= 0 { p = p[:i] } if i := strings.LastIndexByte(p, '.'); i >= 0 && i > strings.LastIndexByte(p, '/') { return !assetExt[strings.ToLower(p[i+1:])] } return true } func normDomain(d string) string { d = strings.ToLower(strings.TrimSpace(d)) if i := strings.LastIndexByte(d, ':'); i > 0 && !strings.Contains(d[i:], "]") { d = d[:i] } if d == "" { return "-" } return d } func refHost(ref, domain string) string { if ref == "" || ref == "-" { return "" } u, err := url.Parse(ref) if err != nil || u.Host == "" { return "" } h := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") if h == "" || h == domain || h == strings.TrimPrefix(domain, "www.") || strings.HasSuffix(h, "."+strings.TrimPrefix(domain, "www.")) { return "" } return h } func latBucket(ns int64) int { ms := float64(ns) / 1e6 for i, b := range latBounds { if ms <= b { return i } } return latN - 1 } // SetDomains restricts the analytics to these domains (exact names, or // "*.example.com" for a whole subtree). Empty means: any domain that has // answered a request successfully. func (s *Store) SetDomains(list []string) { s.mu.Lock() defer s.mu.Unlock() s.allow = nil for _, d := range list { if d = strings.ToLower(strings.TrimSpace(d)); d != "" { s.allow = append(s.allow, d) } } } func (s *Store) domainAllowed(name string) bool { if len(s.allow) == 0 { return true } for _, a := range s.allow { if a == name || strings.HasPrefix(a, "*.") && strings.HasSuffix(name, a[1:]) { return true } } return false } // domLocked returns the slot of a domain. A new slot is only opened for a // domain that has served a 2xx: Host headers sent by scanners (random names // answered with 404, or with the catch-all http->https 301) cannot take slots // from real sites. func (s *Store) domLocked(name string, status int) *domData { if s.tr.dom == nil { s.tr.dom = map[string]*domData{} } if d := s.tr.dom[name]; d != nil { return d } if status < 200 || status > 299 || !s.domainAllowed(name) { return nil } if len(s.tr.dom) >= maxDomains { name = otherDom if d := s.tr.dom[name]; d != nil { return d } } d := &domData{} s.tr.dom[name] = d return d } var uuidRe = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) // readableSlug reports a human URL slug: lowercase words and numbers joined by // "-" (blog-post-title-2024). Those are kept even when long. func readableSlug(s string) bool { for _, word := range strings.Split(s, "-") { if word == "" || len(word) > 16 { return false } for _, r := range word { if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9') { return false } } } return true } // mixedToken reports the shape of a token or opaque identifier: letters and // "-_." only, and either digits mixed with letters, mixed case, or "_"/".". func mixedToken(s string) bool { var lower, upper, digits, punct bool for _, r := range s { switch { case r >= '0' && r <= '9': digits = true case r >= 'a' && r <= 'z': lower = true case r >= 'A' && r <= 'Z': upper = true case r == '_' || r == '.': punct = true case r == '-': default: return false } } letters := lower || upper return letters && (digits || (lower && upper) || punct) } // normalizePath turns token-like path segments (UUIDs, long hex or mixed // alphanumeric ids, long numbers) into ":id" so a top-pages list is not // filled by one-off URLs and a token in a URL is not kept. func normalizePath(p string) string { parts := strings.Split(p, "/") for i, seg := range parts { // personal or secret-looking segments: e-mail addresses, long opaque // values, and mixed letter+digit tokens (reset links, invites, ids) if strings.Contains(seg, "@") || len(seg) >= 48 || (len(seg) >= 24 && !readableSlug(seg)) || (len(seg) >= 12 && !readableSlug(seg) && mixedToken(seg)) { parts[i] = ":id" continue } if len(seg) >= 16 && uuidRe.MatchString(seg) { parts[i] = ":id" continue } if len(seg) >= 16 && !strings.ContainsAny(seg, "-_.") && strings.ContainsAny(seg, "0123456789") && alnum(seg) { parts[i] = ":id" continue } if len(seg) >= 8 && allDigits(seg) { parts[i] = ":id" } } return strings.Join(parts, "/") } func alnum(s string) bool { for _, r := range s { if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z') { return false } } return true } func allDigits(s string) bool { for _, r := range s { if r < '0' || r > '9' { return false } } return true } // Traffic records one legitimate request (category ok or notfound) for the // analytics view. Attack traffic, monitoring probes and forged monitors must // not be passed here. func (s *Store) Traffic(ev core.Event) { now := s.now() if ev.Time.Before(now.Add(-s.cfg.Retention)) || ev.Source != "traefik" { return } ts := ev.Time.Unix() if max := now.Unix() + 300; ts > max { ts = max } dom := normDomain(ev.Domain) day := ts / 86400 s.mu.Lock() defer s.mu.Unlock() d := s.domLocked(dom, ev.Status) if d == nil { return } d.Last = ts if !isAssetPath(ev.Path) { s.emitVisit(ts, dom, ev.Path, ev.IP, ev.Status, ev.E.Device, ev.E.Bot, ev.E.Tool) } m := ts / 60 mi := int(m % anMinutes) if d.MinSt[mi] != m { d.MinSt[mi], d.MinReq[mi], d.MinPages[mi] = m, 0, 0 } d.MinReq[mi]++ h := ts / 3600 hs := &d.Hours[int(h%hourSlots)] if hs.Hour != h { *hs = anHour{Hour: h} } hs.Req++ hs.Bytes += uint64(max64(ev.Bytes, 0)) if c := ev.Status/100 - 2; c >= 0 && c < 4 { hs.S[c]++ } if ev.DurationNS > 0 { hs.Lat[latBucket(ev.DurationNS)]++ } dd := &d.Days[int(day%anDays)] if dd.Day != day { *dd = anDay{Day: day} } // per-day hash state (the salt changes every UTC day) if s.tr.saltDay != day { rand.Read(s.tr.salt[:]) s.tr.saltDay = day } fresh := d.visDay == day && d.vis != nil if !fresh { if day < d.visDay { fresh = false // older than the day being counted (out of order) } else { d.vis, d.nh, d.visDay = make(map[uint64]struct{}, 64), make(map[uint64]struct{}, 16), day fresh = true } } gfresh := s.tr.gvisDay == day && s.tr.gvis != nil if !gfresh && day >= s.tr.gvisDay { s.tr.gvis, s.tr.gnh, s.tr.gvisDay = make(map[uint64]struct{}, 256), make(map[uint64]struct{}, 64), day gfresh = true } gd := &s.tr.gdays[int(day%anDays)] if gd.Day != day { *gd = gDay{Day: day} } kd, kg := s.visitorKey(ev.IP, dom), s.visitorKey(ev.IP, "") human := isHuman(ev.E) if !human { // bots, tools, unknown or empty User-Agents: never a visitor or a page if ev.E.Bot { hs.Bots++ name := ev.E.BotName if name == "" { name = "bot" } bumpCap(&dd.Bots, name, anTop) } if fresh { if _, seen := d.nh[kd]; !seen && len(d.nh) < visCap { d.nh[kd] = struct{}{} dd.NonHuman++ } } if gfresh { if _, seen := s.tr.gnh[kg]; !seen && len(s.tr.gnh) < visCap*4 { s.tr.gnh[kg] = struct{}{} gd.NonHuman++ } } return } if !isPageView(ev) { return } hs.Pages++ d.MinPages[mi]++ p := ev.Path if i := strings.IndexAny(p, "?#"); i >= 0 { p = p[:i] } bumpCap(&dd.Pages, normalizePath(p), anTop) bumpCap(&dd.Refs, refHost(ev.Referer, dom), anTop) if gfresh { if _, seen := s.tr.gvis[kg]; !seen && len(s.tr.gvis) < visCap*4 { s.tr.gvis[kg] = struct{}{} gd.Visitors++ } } if !fresh { return } if _, seen := d.vis[kd]; seen || len(d.vis) >= visCap { return } d.vis[kd] = struct{}{} dd.Visitors++ if ev.E.CC != "" { bumpCap(&dd.Countries, ev.E.CC, 300) } if ev.E.City != "" { city := ev.E.City if ev.E.CC != "" { city += ", " + ev.E.CC } bumpCap(&dd.Cities, city, anTop) } bumpCap(&dd.Browsers, orUnknown(ev.E.Browser), anTop) bumpCap(&dd.OSes, orUnknown(ev.E.OS), anTop) bumpCap(&dd.Devices, orUnknown(ev.E.Device), 10) } // visitorKey is the 64-bit prefix of SHA-256(salt | ip | domain) with today's salt. func (s *Store) visitorKey(ip, dom string) uint64 { h := sha256.New() h.Write(s.tr.salt[:]) h.Write([]byte(ip)) h.Write([]byte{0}) h.Write([]byte(dom)) var sum [32]byte h.Sum(sum[:0]) var key uint64 for i := 0; i < 8; i++ { key = key<<8 | uint64(sum[i]) } return key } func max64(a, b int64) int64 { if a > b { return a } return b } func orUnknown(s string) string { if s == "" { return "unknown" } return s } // TrafficData is the mergeable analytics payload. type TrafficData struct { Host string `json:"host"` Range RangeInfo `json:"range"` Domain string `json:"domain"` Generated int64 `json:"generated"` Domains []Count `json:"domains"` Requests uint64 `json:"requests"` Pages uint64 `json:"pages"` Visitors uint64 `json:"visitors"` NonHuman uint64 `json:"nonhuman"` // distinct non-human clients (bots, tools, unknown), apart from visitors Bots uint64 `json:"bots"` Bytes uint64 `json:"bytes"` Status [4]uint64 `json:"status"` Lat [latN]uint64 `json:"lat"` P50 float64 `json:"p50_ms"` P95 float64 `json:"p95_ms"` Timeline struct { Start int64 `json:"start"` Step int64 `json:"step"` Req []uint32 `json:"req"` Pages []uint32 `json:"pages"` } `json:"timeline"` TopPages []Count `json:"top_pages"` Referrers []Count `json:"referrers"` Countries []Count `json:"countries"` Cities []Count `json:"cities"` Browsers []Count `json:"browsers"` OSes []Count `json:"oses"` Devices []Count `json:"devices"` BotNames []Count `json:"bot_names"` } func quantile(h [latN]uint64, q float64) float64 { var total uint64 for _, v := range h { total += v } if total == 0 { return 0 } target := q * float64(total) var cum float64 lower := 0.0 for i, v := range h { upper := 20000.0 if i < len(latBounds) { upper = latBounds[i] } if cum+float64(v) >= target && v > 0 { return lower + (upper-lower)*(target-cum)/float64(v) } cum += float64(v) lower = upper } return lower } // Finish recomputes derived values (percentiles) after a merge. func (t *TrafficData) Finish() { t.P50, t.P95 = round1(quantile(t.Lat, 0.5)), round1(quantile(t.Lat, 0.95)) } // TrafficSummary returns the analytics of one domain for a named range. func (s *Store) TrafficSummary(rangeName, domain string) TrafficData { return s.TrafficFor(ParseRange(rangeName), domain) } // TrafficFor returns the analytics of one domain ("" or "all": every domain). func (s *Store) TrafficFor(rg Range, domain string) TrafficData { now := s.now().Unix() from, to := rg.bounds(now) out := TrafficData{Host: s.cfg.Name, Range: rg.Info(now), Domain: domain, Generated: now} if out.Domain == "" { out.Domain = "all" } g := rg.grid(now) nb, step, start := g.N, g.Step, g.Start out.Timeline.Start, out.Timeline.Step = start, step out.Timeline.Req, out.Timeline.Pages = make([]uint32, nb), make([]uint32, nb) firstHour, lastHour := start/3600, to/3600 firstDay, lastDay := from/86400, to/86400 maps := [8]map[string]uint32{{}, {}, {}, {}, {}, {}, {}, {}} domReq := map[string]uint32{} domVis, domNH := map[int64]uint64{}, map[int64]uint64{} s.mu.RLock() for name, d := range s.tr.dom { var reqRange uint32 for i := range d.Hours { h := &d.Hours[i] if h.Hour == 0 || h.Hour < firstHour || h.Hour > lastHour { continue } reqRange += h.Req if out.Domain != "all" && out.Domain != name { continue } if !g.minute() { out.Requests += uint64(h.Req) out.Pages += uint64(h.Pages) if b := (h.Hour*3600 - start) / step; b >= 0 && b < int64(nb) { out.Timeline.Req[b] += h.Req out.Timeline.Pages[b] += h.Pages } } out.Bots += uint64(h.Bots) out.Bytes += h.Bytes for k, v := range h.S { out.Status[k] += uint64(v) } for k, v := range h.Lat { out.Lat[k] += uint64(v) } } domReq[name] = reqRange if out.Domain != "all" && out.Domain != name { continue } if g.minute() { for m := start / 60; m <= to/60; m++ { i := int(m % anMinutes) if d.MinSt[i] != m { continue } out.Requests += uint64(d.MinReq[i]) out.Pages += uint64(d.MinPages[i]) if b := (m*60 - start) / step; b >= 0 && b < int64(nb) { out.Timeline.Req[b] += d.MinReq[i] out.Timeline.Pages[b] += d.MinPages[i] } } } for i := range d.Days { dd := &d.Days[i] if dd.Day == 0 || dd.Day < firstDay || dd.Day > lastDay { continue } domVis[dd.Day] += uint64(dd.Visitors) domNH[dd.Day] += uint64(dd.NonHuman) for k, src := range [8]map[string]uint32{dd.Pages, dd.Refs, dd.Countries, dd.Cities, dd.Browsers, dd.OSes, dd.Devices, dd.Bots} { for key, v := range src { maps[k][key] += v } } } } if out.Domain == "all" { // all domains: a person (or bot) seen on two sites the same day counts once for day := firstDay; day <= lastDay; day++ { gd := s.tr.gdays[int(day%anDays)] if gd.Day == day { out.Visitors += uint64(gd.Visitors) out.NonHuman += uint64(gd.NonHuman) } else { // day recorded before the global total existed out.Visitors += domVis[day] out.NonHuman += domNH[day] } } } else { for day := firstDay; day <= lastDay; day++ { out.Visitors += domVis[day] out.NonHuman += domNH[day] } } s.mu.RUnlock() for name, n := range domReq { if n > 0 { out.Domains = append(out.Domains, Count{Key: name, N: n}) } } sort.Slice(out.Domains, func(i, j int) bool { if out.Domains[i].N != out.Domains[j].N { return out.Domains[i].N > out.Domains[j].N } return out.Domains[i].Key < out.Domains[j].Key }) out.TopPages, out.Referrers, out.Countries, out.Cities = topN(maps[0], anTop), topN(maps[1], anTop), topN(maps[2], 120), topN(maps[3], anTop) out.Browsers, out.OSes, out.Devices, out.BotNames = topN(maps[4], anTop), topN(maps[5], anTop), topN(maps[6], 10), topN(maps[7], anTop) // Visitors come from daily buckets, pages from exact minutes: never report more visitors than page views. if out.Visitors > out.Pages { out.Visitors = out.Pages } out.Finish() return out } // MergeTraffic combines per-host analytics of the same range and domain. func MergeTraffic(host string, parts []TrafficData) TrafficData { if len(parts) == 0 { return TrafficData{Host: host} } out := TrafficData{Host: host, Range: parts[0].Range, Domain: parts[0].Domain, Generated: parts[0].Generated} out.Timeline.Start, out.Timeline.Step = parts[0].Timeline.Start, parts[0].Timeline.Step nb := len(parts[0].Timeline.Req) out.Timeline.Req, out.Timeline.Pages = make([]uint32, nb), make([]uint32, nb) var doms, pages, refs, ctry, cities, br, oses, dev, bots [][]Count for _, p := range parts { out.Requests += p.Requests out.Pages += p.Pages out.Visitors += p.Visitors out.NonHuman += p.NonHuman out.Bots += p.Bots out.Bytes += p.Bytes for i := range p.Status { out.Status[i] += p.Status[i] } for i := range p.Lat { out.Lat[i] += p.Lat[i] } if p.Timeline.Step == out.Timeline.Step && out.Timeline.Step > 0 { shift := (p.Timeline.Start - out.Timeline.Start) / out.Timeline.Step for i := range p.Timeline.Req { if j := int64(i) + shift; j >= 0 && j < int64(nb) { out.Timeline.Req[j] += p.Timeline.Req[i] out.Timeline.Pages[j] += p.Timeline.Pages[i] } } } doms, pages, refs = append(doms, p.Domains), append(pages, p.TopPages), append(refs, p.Referrers) ctry, cities, br = append(ctry, p.Countries), append(cities, p.Cities), append(br, p.Browsers) oses, dev, bots = append(oses, p.OSes), append(dev, p.Devices), append(bots, p.BotNames) } out.Domains, out.TopPages, out.Referrers = mergeCounts(maxDomains+1, doms...), mergeCounts(anTop, pages...), mergeCounts(anTop, refs...) out.Countries, out.Cities, out.Browsers = mergeCounts(120, ctry...), mergeCounts(anTop, cities...), mergeCounts(anTop, br...) out.OSes, out.Devices, out.BotNames = mergeCounts(anTop, oses...), mergeCounts(10, dev...), mergeCounts(anTop, bots...) out.Finish() return out }