package waf import ( "bufio" "context" "io" "log/slog" "os" "path/filepath" "regexp" "strconv" "strings" "sync" "time" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/store" ) // Collector tails every site access log, aggregates counters and records // blocked requests. It never blocks on I/O for more than a few milliseconds // per file per cycle. type Collector struct { db *store.Store cfg *config.Config log *slog.Logger mu sync.Mutex live map[int64]*liveAgg offsets map[string]int64 maxRead int64 lastCollect int64 } // Debug exposes collector internals for operators and smoke tests. func (c *Collector) Debug() map[string]any { c.mu.Lock() defer c.mu.Unlock() newest := int64(0) for slot := range c.live { if slot > newest { newest = slot } } return map[string]any{ "buckets": len(c.live), "newest_slot": newest, "now": time.Now().Unix(), "last_collect": c.lastCollect, "files": len(c.offsets), } } type liveAgg struct { requests int64 blocked int64 bytes int64 rtSum float64 rtCount int64 } type minuteAgg struct { requests int64 blocked int64 throttled int64 bytes int64 rtSum float64 rtCount int64 } // NewCollector builds a collector. func NewCollector(db *store.Store, cfg *config.Config, log *slog.Logger) *Collector { return &Collector{ db: db, cfg: cfg, log: log, live: map[int64]*liveAgg{}, offsets: map[string]int64{}, maxRead: 8 << 20, // at most 8 MiB per file per cycle } } // Run polls logs until the context is cancelled. func (c *Collector) Run(ctx context.Context) { ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() c.collect(ctx) for { select { case <-ctx.Done(): return case <-ticker.C: c.collect(ctx) } } } var accessLine = regexp.MustCompile(`^(\S+) \S+ \S+ \[([^\]]+)\] "([^"]*)" (\d{3}) (\d+) "([^"]*)" "([^"]*)" "?([\d.]+)"?`) const logTimeLayout = "02/Jan/2006:15:04:05 -0700" func (c *Collector) collect(ctx context.Context) { sites, err := c.db.ListSites(ctx) if err != nil { c.log.Warn("waf collector: list sites", "error", err) return } minuteBuckets := map[string]*minuteAgg{} // key: slug|bucket for _, st := range sites { path := filepath.Join(c.cfg.SiteLogDir(st.Slug), "access.log") c.tailFile(ctx, st.Slug, path, minuteBuckets) } for key, agg := range minuteBuckets { slug, bucketStr, ok := strings.Cut(key, "|") if !ok { continue } bucket, _ := strconv.ParseInt(bucketStr, 10, 64) if err := c.db.WAFMetricAdd(ctx, bucket, slug, agg.requests, agg.blocked, agg.throttled, agg.bytes, agg.rtSum, agg.rtCount); err != nil { c.log.Warn("waf collector: flush metrics", "error", err) break } } c.trimLive(time.Now()) c.mu.Lock() c.lastCollect = time.Now().Unix() c.mu.Unlock() } func (c *Collector) tailFile(ctx context.Context, slug, path string, buckets map[string]*minuteAgg) { fi, err := os.Stat(path) if err != nil { return } size := fi.Size() c.mu.Lock() offset, seen := c.offsets[path] c.mu.Unlock() if !seen { stored, err := c.db.WAFOffset(ctx, path) if err == nil && stored > 0 { offset = stored } else { // Seed from the last 2 MiB so the dashboard is not empty after a // fresh install on a busy server. offset = size - 2<<20 } if offset < 0 { offset = 0 } } if size < offset { offset = 0 // log rotated } if size == offset { c.saveOffset(ctx, path, offset) return } f, err := os.Open(path) if err != nil { return } defer f.Close() if _, err := f.Seek(offset, io.SeekStart); err != nil { return } reader := bufio.NewReaderSize(f, 64*1024) read := int64(0) events := 0 for read < c.maxRead { line, err := reader.ReadString('\n') read += int64(len(line)) if line != "" { c.handleLine(ctx, slug, strings.TrimRight(line, "\r\n"), buckets, &events) } if err != nil { break } } c.saveOffset(ctx, path, offset+read) } func (c *Collector) handleLine(ctx context.Context, slug, line string, buckets map[string]*minuteAgg, events *int) { m := accessLine.FindStringSubmatch(line) if m == nil { return } ip, timeStr, request, statusStr, bytesStr, _, ua, rtStr := m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8] ts, err := time.Parse(logTimeLayout, timeStr) if err != nil { ts = time.Now() } status, _ := strconv.Atoi(statusStr) bytesN, _ := strconv.ParseInt(bytesStr, 10, 64) rt, _ := strconv.ParseFloat(rtStr, 64) bucket := ts.Truncate(time.Minute).Unix() key := slug + "|" + strconv.FormatInt(bucket, 10) agg := buckets[key] if agg == nil { agg = &minuteAgg{} buckets[key] = agg } agg.requests++ agg.bytes += bytesN agg.rtSum += rt agg.rtCount++ // 429 is throttling (often legitimate bursts), not malicious traffic. blocked := status == 444 || status == 403 throttled := status == 429 if blocked { agg.blocked++ } if throttled { agg.throttled++ } method, uri := splitRequest(request) if blocked || throttled { withBlock := int64(0) if blocked { withBlock = 1 } c.addLive(ts, 1, withBlock, bytesN, rt) if *events < 20 { *events++ ev := &store.WAFEvent{ TS: ts.Unix(), Site: slug, IP: ip, Method: method, URI: uri, UA: truncate(ua, 300), Status: status, Rule: ruleForStatus(status), } if err := c.db.WAFEventAdd(ctx, ev); err != nil { c.log.Debug("waf collector: event", "error", err) } } return } c.addLive(ts, 1, 0, bytesN, rt) } func ruleForStatus(status int) string { switch status { case 429: return "rate-limit" case 403: return "waf-block" default: return "scanner" } } func splitRequest(req string) (method, uri string) { parts := strings.SplitN(req, " ", 3) if len(parts) >= 2 { return parts[0], truncate(parts[1], 500) } return "", truncate(req, 500) } func (c *Collector) addLive(ts time.Time, requests, blocked, bytesN int64, rt float64) { slot := ts.Unix() / 10 * 10 c.mu.Lock() defer c.mu.Unlock() agg := c.live[slot] if agg == nil { agg = &liveAgg{} c.live[slot] = agg } agg.requests += requests agg.blocked += blocked agg.bytes += bytesN agg.rtSum += rt agg.rtCount++ } func (c *Collector) trimLive(now time.Time) { cutoff := now.Unix() - 600 c.mu.Lock() defer c.mu.Unlock() for slot := range c.live { if slot < cutoff { delete(c.live, slot) } } } func (c *Collector) saveOffset(ctx context.Context, path string, offset int64) { c.mu.Lock() c.offsets[path] = offset c.mu.Unlock() if err := c.db.SetWAFOffset(ctx, path, offset); err != nil { c.log.Debug("waf collector: offset", "error", err) } } // Live returns current qps, bytes per second and average response time (ms). func (c *Collector) Live() (qps, traffic, rt float64) { now := time.Now().Unix() windowStart := now - 10 rtStart := now - 60 c.mu.Lock() defer c.mu.Unlock() var req, bytesN int64 var rtSum float64 var rtCount int64 for slot, agg := range c.live { if slot >= windowStart { req += agg.requests bytesN += agg.bytes } if slot >= rtStart { rtSum += agg.rtSum rtCount += agg.rtCount } } qps = float64(req) / 10 traffic = float64(bytesN) / 10 if rtCount > 0 { rt = rtSum / float64(rtCount) * 1000 } return } // LiveSeries returns 10 second buckets for the last points*10 seconds. func (c *Collector) LiveSeries(points int) map[string][]store.WAFPoint { if points <= 0 || points > 120 { points = 36 } now := time.Now().Unix() / 10 * 10 out := map[string][]store.WAFPoint{"requests": {}, "blocked": {}, "traffic": {}, "rt": {}} c.mu.Lock() defer c.mu.Unlock() for i := points - 1; i >= 0; i-- { slot := now - int64(i*10) agg := c.live[slot] var qps, traffic, rt float64 var blocked float64 if agg != nil { qps = float64(agg.requests) / 10 traffic = float64(agg.bytes) / 10 blocked = float64(agg.blocked) if agg.rtCount > 0 { rt = agg.rtSum / float64(agg.rtCount) * 1000 } } out["requests"] = append(out["requests"], store.WAFPoint{TS: slot, Value: qps}) out["blocked"] = append(out["blocked"], store.WAFPoint{TS: slot, Value: blocked}) out["traffic"] = append(out["traffic"], store.WAFPoint{TS: slot, Value: traffic}) out["rt"] = append(out["rt"], store.WAFPoint{TS: slot, Value: rt}) } return out } // Prune removes data older than the retention window. func (c *Collector) Prune(ctx context.Context, days int) error { if days <= 0 { days = 7 } cutoff := time.Now().AddDate(0, 0, -days).Unix() _, err := c.db.PruneWAF(ctx, cutoff) return err } func truncate(s string, n int) string { if len(s) <= n { return s } return s[:n] }