package main import ( "bytes" "crypto/rand" "encoding/hex" "encoding/json" "errors" "flag" "fmt" "io" "math" "net/http" "net/url" "sort" "strings" "sync" "text/tabwriter" "time" "github.com/BurntSushi/toml" "migadu_counters/internal/api" "migadu_counters/internal/config" "migadu_counters/internal/counting" "migadu_counters/internal/domains" ) const ( defaultWarnPercent = 80 defaultMailFromIn = "countersend@example.com" requestTimeout = 10 * time.Second pollInterval = 50 * time.Millisecond // settleTime is how long to wait before the final read when no counter // is expected to move, so nothing is there to poll for. settleTime = 500 * time.Millisecond ) // cliConfig mirrors the daemon config fields this tool needs; TOML ignores the // rest, so the daemon's own config file can be used as is. type cliConfig struct { Addr string `toml:"addr"` AuthToken string `toml:"auth_token"` Notify struct { WarnPercent *int64 `toml:"warn_percent"` OrgURL string `toml:"org_url"` AddressURL string `toml:"address_url"` DomainURL string `toml:"domain_url"` WarnOrgURL string `toml:"warn_org_url"` WarnAddressURL string `toml:"warn_address_url"` WarnDomainURL string `toml:"warn_domain_url"` } `toml:"notify"` } // loadConfig reads the daemon config. Without --config the default paths are // tried; when none exists the tool still runs with --url and the token from // the environment. found says whether a file was read. func loadConfig(path string, haveURL bool) (cfg cliConfig, found bool, err error) { if path == "" { discovered, derr := config.Discover("") if derr != nil { if haveURL { return cfg, false, nil } return cfg, false, derr } path = discovered } if _, err := toml.DecodeFile(path, &cfg); err != nil { return cfg, false, fmt.Errorf("read config %s: %v", path, err) } return cfg, true, nil } // baseURL turns the daemon's listen address into a URL: ":5555" → // "http://localhost:5555"; a full URL is used as is. func baseURL(addr string) string { if addr == "" { addr = ":5555" } if strings.HasPrefix(addr, "http://") || strings.HasPrefix(addr, "https://") { return strings.TrimRight(addr, "/") } if strings.HasPrefix(addr, ":") { addr = "localhost" + addr } return "http://" + addr } // notifyHosts lists where the configured notifications go, without URL // credentials. func notifyHosts(cfg cliConfig) []string { seen := map[string]bool{} var hosts []string n := cfg.Notify for _, raw := range []string{n.OrgURL, n.AddressURL, n.DomainURL, n.WarnOrgURL, n.WarnAddressURL, n.WarnDomainURL} { u, err := url.Parse(raw) if raw == "" || err != nil || u.Host == "" || seen[u.Host] { continue } seen[u.Host] = true hosts = append(hosts, u.Host) } sort.Strings(hosts) return hosts } // side is one address whose counters a run moves. type side struct { role string // sender | recipient addr string // normalised flow string // i | o before *api.CountersResponse after *api.CountersResponse } func (s *side) flowName() string { if s.flow == domains.FlowOut { return "outgoing" } return "incoming" } func levelValue(l api.CountersLevel, flow string) (int64, *int64) { if flow == domains.FlowOut { return l.Out, l.OutLimit } return l.In, l.InLimit } func addressCount(r *api.CountersResponse, flow string) (int64, bool) { if r == nil { return 0, false } for _, l := range r.Levels { if l.Level == domains.AddressLevel { n, _ := levelValue(l, flow) return n, true } } return 0, false } type client struct { http *http.Client base string token string } func (c *client) counters(address string) (*api.CountersResponse, error) { q := url.Values{"address": {address}} req, err := http.NewRequest(http.MethodGet, c.base+"/counters?"+q.Encode(), nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+c.token) resp, err := c.http.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("GET /counters answered %d", resp.StatusCode) } var r api.CountersResponse if err := json.Unmarshal(body, &r); err != nil { return nil, fmt.Errorf("GET /counters: %v", err) } return &r, nil } // readAll refreshes dest for every side and returns the first error. func (c *client) readAll(sides []*side, dest func(*side) **api.CountersResponse) error { var first error for _, s := range sides { r, err := c.counters(s.addr) if err != nil { if first == nil { first = err } continue } *dest(s) = r } return first } // sendStats is the outcome of the POSTs. type sendStats struct { status map[int]int connErrors int firstConnErr error firstBadBody string latencies []time.Duration elapsed time.Duration } func (c *client) post(path, runID string, n, concurrency int, body func(trace string) any) sendStats { stats := sendStats{status: map[int]int{}} var mu sync.Mutex jobs := make(chan int) var wg sync.WaitGroup start := time.Now() for w := 0; w < concurrency; w++ { wg.Add(1) go func() { defer wg.Done() for i := range jobs { code, respBody, took, err := c.postOne(path, body(fmt.Sprintf("countersend-%s-%d", runID, i))) mu.Lock() stats.latencies = append(stats.latencies, took) if err != nil { stats.connErrors++ if stats.firstConnErr == nil { stats.firstConnErr = err } } else { stats.status[code]++ if code != http.StatusAccepted && stats.firstBadBody == "" { stats.firstBadBody = respBody } } mu.Unlock() } }() } for i := 1; i <= n; i++ { jobs <- i } close(jobs) wg.Wait() stats.elapsed = time.Since(start) return stats } func (c *client) postOne(path string, payload any) (int, string, time.Duration, error) { data, err := json.Marshal(payload) if err != nil { return 0, "", 0, err } req, err := http.NewRequest(http.MethodPost, c.base+path, bytes.NewReader(data)) if err != nil { return 0, "", 0, err } req.Header.Set("Authorization", "Bearer "+c.token) req.Header.Set("Content-Type", "application/json") start := time.Now() resp, err := c.http.Do(req) if err != nil { return 0, "", time.Since(start), err } defer resp.Body.Close() respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) return resp.StatusCode, strings.TrimSpace(string(respBody)), time.Since(start), nil } func percentile(sorted []time.Duration, p float64) time.Duration { if len(sorted) == 0 { return 0 } return sorted[int(math.Ceil(p*float64(len(sorted))))-1] } func printStats(w io.Writer, st sendStats, n int) { codes := make([]int, 0, len(st.status)) for c := range st.status { codes = append(codes, c) } sort.Ints(codes) parts := make([]string, 0, len(codes)) for _, c := range codes { parts = append(parts, fmt.Sprintf("%d=%d", c, st.status[c])) } if len(parts) == 0 { parts = append(parts, "none") } fmt.Fprintf(w, "status: %s\n", strings.Join(parts, " ")) if st.connErrors > 0 { fmt.Fprintf(w, "connection errors: %d (first: %v)\n", st.connErrors, st.firstConnErr) } if st.firstBadBody != "" { fmt.Fprintf(w, "first error reply: %s\n", st.firstBadBody) } sort.Slice(st.latencies, func(i, j int) bool { return st.latencies[i] < st.latencies[j] }) rate := float64(n) / st.elapsed.Seconds() fmt.Fprintf(w, "timing: %v total, %.0f req/s, p50 %v, p99 %v\n", st.elapsed.Round(time.Microsecond), rate, percentile(st.latencies, 0.50).Round(time.Microsecond), percentile(st.latencies, 0.99).Round(time.Microsecond)) } // crossings describes every threshold a run of n would reach. A counter // already past a threshold cannot cross it again and is not listed. func crossings(sides []*side, n, percent int64) []string { var out []string for _, s := range sides { if s.before == nil || !s.before.Managed { continue } for _, l := range s.before.Levels { count, limit := levelValue(l, s.flow) if limit == nil { continue } where := fmt.Sprintf("%s %s %s: %d + %d", l.Level, l.ID, s.flowName(), count, n) if warn := counting.WarnThreshold(*limit, percent); warn > 0 && counting.Crossed(count+n, n, warn) { out = append(out, fmt.Sprintf("%s reaches the warning threshold %d (limit %d)", where, warn, *limit)) } if counting.Crossed(count+n, n, *limit) { out = append(out, fmt.Sprintf("%s reaches the limit %d", where, *limit)) } } } return out } func describeHosts(found bool, hosts []string) string { switch { case !found: return "notifications would go to the hosts in the daemon's config (no config was read here)" case len(hosts) == 0: return "no notify URL is configured, so nothing would be sent" default: return "notifications would go to: " + strings.Join(hosts, ", ") } } func printCounters(w io.Writer, s *side) { fmt.Fprintf(w, "%s %s, %s\n", s.role, s.addr, s.flowName()) if s.after == nil { fmt.Fprintln(w, " counters could not be read") return } tw := tabwriter.NewWriter(w, 0, 8, 2, ' ', 0) fmt.Fprintln(tw, " LEVEL\tID\tBEFORE\tAFTER\tCHANGE\tLIMIT") for _, l := range s.after.Levels { now, limit := levelValue(l, s.flow) before, change := "-", "-" if s.before != nil { for _, b := range s.before.Levels { if b.Level == l.Level { v, _ := levelValue(b, s.flow) before, change = fmt.Sprint(v), fmt.Sprintf("%+d", now-v) } } } lim := "-" if limit != nil { lim = fmt.Sprint(*limit) } fmt.Fprintf(tw, " %s\t%s\t%s\t%d\t%s\t%s\n", l.Level, l.ID, before, now, change, lim) } tw.Flush() } func runSend(args []string, stdout, stderr io.Writer, getenv func(string) string) int { fs := flag.NewFlagSet("countersend send", flag.ContinueOnError) fs.SetOutput(stderr) urlFlag := fs.String("url", "", "where to send: base URL of the daemon (default: addr from the config)") route := fs.String("route", "", "in or out") n := fs.Int("n", 1, "number of requests") concurrency := fs.Int("concurrency", 1, "requests in flight at once") recipient := fs.String("recipient", "", "recipient address") authUser := fs.String("auth-user", "", "SMTP login (--route out only)") mailFrom := fs.String("mail-from", "", "envelope sender (default: the auth user for out, "+defaultMailFromIn+" for in)") junk := fs.Bool("junk", false, "set junk:true (--route in only)") configPath := fs.String("config", "", "daemon config (default: "+strings.Join(config.DefaultPaths, " or ")+")") allowNotify := fs.Bool("allow-notify", false, "allow a run that would reach a warning threshold or a limit") wait := fs.Duration("wait", 5*time.Second, "how long to wait for the counters to move") if err := fs.Parse(args); err != nil { return exitUsage } var problems []string if fs.NArg() != 0 { problems = append(problems, "unexpected arguments: "+strings.Join(fs.Args(), " ")) } if *route != "in" && *route != "out" { problems = append(problems, "--route must be in or out") } if *recipient == "" { problems = append(problems, "--recipient is required") } if *route == "out" && *authUser == "" { problems = append(problems, "--auth-user is required with --route out") } if *route == "in" && *authUser != "" { problems = append(problems, "--auth-user only applies to --route out") } if *route == "out" && *junk { problems = append(problems, "--junk only applies to --route in") } if *n < 1 { problems = append(problems, "--n must be at least 1") } if *concurrency < 1 { problems = append(problems, "--concurrency must be at least 1") } if len(problems) > 0 { fmt.Fprintln(stderr, strings.Join(problems, "\n")) return exitUsage } cfg, found, err := loadConfig(*configPath, *urlFlag != "") if err != nil { fmt.Fprintf(stderr, "%v\nuse --config, or --url with %s set\n", err, config.EnvAuthToken) return exitUsage } token := cfg.AuthToken if v := getenv(config.EnvAuthToken); v != "" { token = v } if token == "" { fmt.Fprintf(stderr, "no auth token: set auth_token in the config or %s\n", config.EnvAuthToken) return exitUsage } base := *urlFlag if base == "" { base = baseURL(cfg.Addr) } base = strings.TrimRight(base, "/") if u, err := url.Parse(base); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { fmt.Fprintf(stderr, "--url must be an http(s) URL, got %q\n", base) return exitUsage } percent := int64(defaultWarnPercent) if cfg.Notify.WarnPercent != nil { percent = *cfg.Notify.WarnPercent } transport := http.DefaultTransport.(*http.Transport).Clone() transport.Proxy = nil transport.MaxIdleConnsPerHost = *concurrency c := &client{http: &http.Client{Timeout: requestTimeout, Transport: transport}, base: base, token: token} // Work out which counters this run moves. var sides []*side senderAddr := "" if *route == "out" { if addr, _, err := api.NormalizeAuthUser(*authUser); err == nil { senderAddr = addr sides = append(sides, &side{role: "sender", addr: addr, flow: domains.FlowOut}) } else { fmt.Fprintln(stdout, "auth user is not a usable address: the sender side will not be counted") } } if addr, err := api.NormalizeEmail(*recipient); err == nil { sides = append(sides, &side{role: "recipient", addr: addr, flow: domains.FlowIn}) } else { fmt.Fprintf(stdout, "recipient %s is not a usable address: the recipient side will not be counted\n", api.SanitizeForLog(*recipient)) } from := *mailFrom if from == "" { from = defaultMailFromIn if *route == "out" { from = senderAddr } } beforeErr := c.readAll(sides, func(s *side) **api.CountersResponse { return &s.before }) exempt := false for _, s := range sides { exempt = exempt || (s.before != nil && s.before.Exempt) } if addr, err := api.NormalizeEmail(from); err == nil { r, err := c.counters(addr) switch { case err != nil && beforeErr == nil: beforeErr = err case err == nil && r.Exempt: exempt = true } } hostInfo := describeHosts(found, notifyHosts(cfg)) if beforeErr != nil && !*allowNotify { fmt.Fprintf(stderr, "refusing to send: cannot read the counters, so cannot tell whether this run would notify anyone: %v\n", beforeErr) fmt.Fprintf(stderr, "%s\nuse --allow-notify to send anyway\n", hostInfo) return exitFail } if !exempt { if hits := crossings(sides, int64(*n), percent); len(hits) > 0 { if !*allowNotify { fmt.Fprintln(stderr, "refusing to send: this run would trigger notifications:") for _, h := range hits { fmt.Fprintln(stderr, " "+h) } fmt.Fprintf(stderr, "%s\nuse --allow-notify if that is what you want\n", hostInfo) return exitFail } fmt.Fprintln(stdout, "this run will trigger notifications:") for _, h := range hits { fmt.Fprintln(stdout, " "+h) } fmt.Fprintln(stdout, hostInfo) } } idBytes := make([]byte, 4) if _, err := rand.Read(idBytes); err != nil { fmt.Fprintln(stderr, err) return exitFail } runID := hex.EncodeToString(idBytes) path := "/" + *route fmt.Fprintf(stdout, "POST %s%s n=%d concurrency=%d trace ids: countersend-%s-*\n", base, path, *n, *concurrency, runID) stats := c.post(path, runID, *n, *concurrency, func(trace string) any { if *route == "out" { return api.OutRequest{TraceID: trace, AuthUser: *authUser, MailFrom: from, Recipient: *recipient} } return api.InRequest{TraceID: trace, MailFrom: from, Recipient: *recipient, Junk: *junk} }) printStats(stdout, stats, *n) accepted := int64(stats.status[http.StatusAccepted]) failed := accepted != int64(*n) if failed { fmt.Fprintf(stderr, "FAIL: %d of %d requests were not accepted\n", int64(*n)-accepted, *n) } // A counter is expected to move when the daemon would count it. var judged []*side if !exempt && !*junk && accepted > 0 { for _, s := range sides { if s.before != nil && s.before.Managed { judged = append(judged, s) } } } risen := func(s *side) bool { before, ok1 := addressCount(s.before, s.flow) after, ok2 := addressCount(s.after, s.flow) return ok1 && ok2 && after-before >= accepted } afterErr := c.waitForCounters(sides, judged, risen, *wait) for _, s := range sides { printCounters(stdout, s) switch { case exempt: fmt.Fprintln(stdout, " exempt address in this request: nothing should move") case *junk: fmt.Fprintln(stdout, " junk: whether this counts depends on count_junk") case s.before != nil && !s.before.Managed: fmt.Fprintln(stdout, " domain not hosted: nothing should move") } } for _, s := range judged { if !risen(s) { before, _ := addressCount(s.before, s.flow) after, _ := addressCount(s.after, s.flow) fmt.Fprintf(stderr, "FAIL: %s %s counter did not rise by %d within %v (rose by %d)\n", s.role, s.addr, accepted, *wait, after-before) failed = true } } if accepted > 0 && (beforeErr != nil || afterErr != nil) { err := errors.Join(beforeErr, afterErr) fmt.Fprintf(stderr, "FAIL: counting could not be confirmed: %v\n", err) failed = true } if failed { return exitFail } fmt.Fprintln(stdout, "OK") return exitOK } // waitForCounters polls until every judged side has risen, or wait passes. // Without judged sides it reads once after a short settle time. func (c *client) waitForCounters(sides, judged []*side, risen func(*side) bool, wait time.Duration) error { dest := func(s *side) **api.CountersResponse { return &s.after } if len(judged) == 0 { time.Sleep(min(wait, settleTime)) return c.readAll(sides, dest) } deadline := time.Now().Add(wait) for { err := c.readAll(sides, dest) done := err == nil for _, s := range judged { done = done && risen(s) } if done || !time.Now().Before(deadline) { return err } time.Sleep(pollInterval) } }