traffic

package
v0.4.123 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: AGPL-3.0 Imports: 33 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package traffic implements the request-recording subsystem (docs §10): an embedded go-mitmproxy proxy whose addon writes every target HTTP exchange into a human-browsable file tree, with a sidecar SQLite index for paged queries. Full capture, plaintext (no redaction), target HTTP only.

Index

Constants

View Source
const (
	IdentitySchemaVersion        = 1
	IdentityNormalizationVersion = "ascii-fold-v1"

	// IdentityDefaultMaxBodyBytes covers every body the recorder can store:
	// go-mitmproxy streams (and the recorder therefore skips) a body once it
	// reaches its 5 MiB StreamLargeBodies threshold, so recorded bodies are
	// always smaller than 5 MiB.
	IdentityDefaultMaxBodyBytes = 5 << 20
)
View Source
const IdentityLexiconVersion = "idscan-1"

IdentityLexiconVersion identifies the built-in wordlist generation. Reports carry it so two baselines are only compared when the lexicon matches.

View Source
const TrafficSearchDescription = "" /* 666-byte string literal not displayed */

TrafficSearchDescription is persisted into the tool catalog for new and upgraded installations. Keep it in the traffic package so the runtime tool and the catalog migration cannot drift apart.

Variables

This section is empty.

Functions

func OpenIndexReadOnly added in v0.4.97

func OpenIndexReadOnly(path string) (*sql.DB, error)

OpenIndexReadOnly opens a traffic index SQLite file without creating it and without any of traffic.Open's side effects (mkdir, proxy, CA generation).

func SeedToolMetas

func SeedToolMetas() []actool.CoreTool

SeedToolMetas returns the traffic tools built on a ZERO receiver, for seeding the tools catalog (metadata only — Name/Description/InputSchema). The handlers close over the nil receiver but are never invoked on this instance, so it is safe.

func SetupProxyLog added in v0.4.71

func SetupProxyLog(dataDir string)

SetupProxyLog 把 go-mitmproxy 的日志单独写到 <dataDir>/traffic.log。

目录爆破/扫描时每个失败请求都有一条 "CONNECT ERROR ... context canceled" (level=error),混在主日志里会把启动/升级等关键信息淹没。logrus 在本项目 只有 go-mitmproxy 在使用,所以这里独占式重定向是安全的;只在二进制入口调用, 测试里的临时 Traffic 实例不受影响(否则 Windows 上打开的句柄会让 TempDir 清理失败)。 打开失败时保持默认输出,不阻塞启动;超过 64MB 时在启动阶段轮转一次。

func ValidateProxyURL

func ValidateProxyURL(raw string) (*url.URL, error)

ValidateProxyURL parses and checks a proxy URL (http/https/socks5, optional user:pass), returning the parsed URL. Exposed so callers can validate a global proxy before persisting it even when the traffic proxy itself is disabled.

Types

type ArchiveExchange

type ArchiveExchange struct {
	ID          string `json:"id"`
	TS          int64  `json:"ts"`
	Host        string `json:"host"`
	Method      string `json:"method"`
	URLTemplate string `json:"url_template"`
	URL         string `json:"url"`
	Status      int    `json:"status"`
	ContentType string `json:"content_type"`
	ReqLen      int    `json:"req_len"`
	RespLen     int    `json:"resp_len"`
	ReqHead     string `json:"req_head"`
	ReqBody     []byte `json:"req_body,omitempty"`
	ReqBlob     string `json:"req_blob,omitempty"`
	RespHead    string `json:"resp_head"`
	RespBody    []byte `json:"resp_body,omitempty"`
	RespBlob    string `json:"resp_blob,omitempty"`
}

type ArchiveSnapshot

type ArchiveSnapshot struct {
	Version   int               `json:"version"`
	Exchanges []ArchiveExchange `json:"exchanges"`
	Blobs     []string          `json:"blobs"`
}

ArchiveSnapshot is the portable traffic subset embedded in one task archive. Large content-addressed bodies are copied alongside this manifest rather than base64-encoded, preserving deduplication and allowing the tar writer to stream.

type EvidenceExchange

type EvidenceExchange struct {
	ID, URL, Method, ContentType string
	TS                           int64
	Status                       int
	ReqHead, RespHead            string
	ReqLen, RespLen              int64
	ReqHash, RespHash            string
	Request, Response            io.Reader
}

EvidenceExchange exposes complete captured bodies only during the callback. Readers are closed before releasing the writer lock, so host deletion cannot remove a blob between its index lookup and its evidence copy.

type ExchangeMeta

type ExchangeMeta struct {
	ID          string `json:"id"`
	TS          int64  `json:"ts"`
	Host        string `json:"host"`
	Method      string `json:"method"`
	URLTemplate string `json:"url_template"`
	URL         string `json:"url"`
	Status      int    `json:"status"`
	ContentType string `json:"content_type"`
	RespLen     int    `json:"resp_len"`
	Path        string `json:"path"`
}

ExchangeMeta is one row of the index (returned by Search).

type HostCount

type HostCount struct {
	Host  string `json:"host"`
	Count int    `json:"count"`
}

HostCount is one distinct recorded host plus its exchange count.

type HostDeleteStage

type HostDeleteStage struct {
	// contains filtered or unexported fields
}

HostDeleteStage keeps the SQLite delete transaction open so a task deletion can be coordinated with PostgreSQL: the traffic side is staged here and only committed once the caller's own transaction has succeeded. The Traffic write lock is held until Commit or Rollback, so no recorder can add rows or a blob reference for a host that is mid-deletion. Rolling back is just a transaction rollback now that nothing is moved on disk.

func (*HostDeleteStage) Commit

func (s *HostDeleteStage) Commit() error

Commit makes the staged deletion permanent. SQLite is committed only after the caller has committed its PostgreSQL task deletion.

func (*HostDeleteStage) Deleted

func (s *HostDeleteStage) Deleted() int64

Deleted reports the number of exchange rows selected by this stage.

func (*HostDeleteStage) Rollback

func (s *HostDeleteStage) Rollback() error

Rollback discards the staged deletion, leaving the traffic store untouched.

type HostGuard added in v0.4.123

type HostGuard func(ctx context.Context, hosts []string) (map[string]bool, error)

HostGuard returns the subset of hosts that are still safe to delete. The worker supplies a PostgreSQL ownership re-check; nil means "no re-check".

type IdentityAllowRule added in v0.4.97

type IdentityAllowRule struct {
	TermID string `json:"term_id,omitempty"`
	Host   string `json:"host,omitempty"`
	Reason string `json:"reason"`
}

IdentityAllowRule suppresses hits for one term, one host, or both. Reason is mandatory so every suppression is auditable.

type IdentityAllowlist added in v0.4.97

type IdentityAllowlist struct {
	Rules []IdentityAllowRule `json:"rules"`
}

IdentityAllowlist is the false-positive control file accepted by --allowlist.

func LoadAllowlist added in v0.4.97

func LoadAllowlist(path string) (*IdentityAllowlist, error)

type IdentityCoverage added in v0.4.97

type IdentityCoverage struct {
	Total           int64            `json:"total"`
	Eligible        int64            `json:"eligible"`
	Excluded        IdentityExcluded `json:"excluded"`
	WithBody        int64            `json:"with_body"`
	RequestCapture  int64            `json:"request_capture"`
	ResponseCapture int64            `json:"response_capture"`
	CaptureCoverage float64          `json:"capture_coverage"`
	ScanCoverage    float64          `json:"scan_coverage"`
	BodyTruncated   int64            `json:"body_truncated"`
	BodyBytesRead   int64            `json:"body_bytes_read"`
	LegacyRows      int64            `json:"legacy_rows"`
}

IdentityCoverage separates "what the recorder captured" from "what this scan could read". Both are reported; neither is presented as target-side truth.

type IdentityDBInfo added in v0.4.97

type IdentityDBInfo struct {
	Path       string `json:"path"`
	Mode       string `json:"mode"`
	TrafficDir string `json:"traffic_dir,omitempty"`
}

IdentityDBInfo records which index was scanned and how it was opened.

type IdentityExcluded added in v0.4.97

type IdentityExcluded struct {
	HEAD             int64 `json:"head"`
	Informational1xx int64 `json:"informational_1xx"`
	NoContent        int64 `json:"no_content_204_205"`
	NotModified304   int64 `json:"not_modified_304"`
	FailedStatus0    int64 `json:"failed_status0"`
}

IdentityExcluded breaks down rows that cannot be evaluated for capture coverage. Their sum plus Eligible and LegacyRows equals Total.

type IdentityFinding added in v0.4.97

type IdentityFinding struct {
	ExchangeID string   `json:"exchange_id"`
	TS         int64    `json:"ts"`
	Host       string   `json:"host"`
	List       string   `json:"list"`
	TermID     string   `json:"term_id"`
	Terms      []string `json:"terms,omitempty"`
	Where      string   `json:"where"`
	Offset     int      `json:"offset"`
	Snippet    string   `json:"snippet"`
	Severity   string   `json:"severity"`
}

IdentityFinding is a promoted hit: any A hit, or >=2 distinct B terms in one exchange. C never produces a finding.

type IdentityHostStat added in v0.4.97

type IdentityHostStat struct {
	Host      string           `json:"host"`
	Exchanges int64            `json:"exchanges"`
	Eligible  int64            `json:"eligible"`
	WithBody  int64            `json:"with_body"`
	Hits      map[string]int64 `json:"hits"`
	Findings  int64            `json:"findings"`
	Rules     []string         `json:"rules,omitempty"`
	Samples   []IdentitySample `json:"samples,omitempty"`
}

IdentityHostStat is per-host counts. Hits counts distinct (term, exchange) pairs; Rules lists the term IDs seen.

type IdentityLexicon added in v0.4.97

type IdentityLexicon struct {
	Version string         `json:"version"`
	Mode    string         `json:"mode,omitempty"`
	Terms   []IdentityTerm `json:"terms"`
}

IdentityLexicon is the wordlist used by ScanIdentity. Terms are matched case-insensitively (ASCII fold); CJK terms are matched as byte substrings.

func BuiltinLexicon added in v0.4.97

func BuiltinLexicon() *IdentityLexicon

BuiltinLexicon returns a fresh copy of the compiled-in wordlist. Only strings present in the current tree are included: historical canary strings removed by #37 stay out of the binary and can only be loaded with --wordlist.

func LoadLexicon added in v0.4.97

func LoadLexicon(path string) (*IdentityLexicon, error)

LoadLexicon reads a JSON wordlist. With mode=merge (the default) terms are merged into the built-in list by ID; mode=replace uses the file alone.

type IdentityLexiconInfo added in v0.4.97

type IdentityLexiconInfo struct {
	Version string         `json:"version"`
	Source  string         `json:"source"`
	Counts  map[string]int `json:"counts"`
}

IdentityLexiconInfo records the wordlist generation used for a report.

type IdentityListStat added in v0.4.97

type IdentityListStat struct {
	Hits      int64 `json:"hits"`
	Exchanges int64 `json:"exchanges"`
	Findings  int64 `json:"findings"`
}

IdentityListStat aggregates one wordlist across all hosts.

type IdentityReport added in v0.4.97

type IdentityReport struct {
	SchemaVersion        int                         `json:"schema_version"`
	GeneratedAt          time.Time                   `json:"generated_at"`
	DB                   IdentityDBInfo              `json:"db"`
	Lexicon              IdentityLexiconInfo         `json:"lexicon"`
	NormalizationVersion string                      `json:"normalization_version"`
	Scan                 IdentityScanStats           `json:"scan"`
	Coverage             IdentityCoverage            `json:"coverage"`
	Lists                map[string]IdentityListStat `json:"lists"`
	Hosts                []IdentityHostStat          `json:"hosts"`
	Tasks                []IdentityTaskStat          `json:"tasks,omitempty"`
	UnmappedHosts        []string                    `json:"unmapped_hosts,omitempty"`
	Samples              []IdentitySample            `json:"samples"`
	Findings             []IdentityFinding           `json:"findings"`
	FindingsTotal        int64                       `json:"findings_total"`
	Suppressed           IdentitySuppressed          `json:"suppressed"`
	Warnings             []string                    `json:"warnings"`
	Notes                []string                    `json:"notes"`
}

IdentityReport is the machine-readable output of ScanIdentity.

func ScanIdentity added in v0.4.97

func ScanIdentity(ctx context.Context, opt IdentityScanOptions) (*IdentityReport, error)

ScanIdentity runs one offline scan. It returns an error before doing any work if the index cannot be opened strictly read-only.

type IdentitySample added in v0.4.97

type IdentitySample struct {
	ExchangeID string `json:"exchange_id"`
	TS         int64  `json:"ts"`
	Host       string `json:"host"`
	List       string `json:"list"`
	TermID     string `json:"term_id"`
	Where      string `json:"where"`
	Offset     int    `json:"offset"`
	Snippet    string `json:"snippet"`
}

IdentitySample is one redacted hit context.

type IdentityScanOptions added in v0.4.97

type IdentityScanOptions struct {
	// DBPath points at index.sqlite directly; DataDir is the deployment data
	// directory (index at <DataDir>/traffic/_index/index.sqlite).
	DBPath string
	// TrafficDir is the recorder directory holding _blobs; it defaults to the
	// parent of _index when the index lives at the standard path.
	TrafficDir string
	DataDir    string

	Lexicon      *IdentityLexicon
	Allowlist    *IdentityAllowlist
	Tiers        []string
	Hosts        []string
	Since        int64
	Until        int64
	Limit        int
	Batch        int
	MaxBodyBytes int64
	TaskMap      map[string][]int64
	Now          func() time.Time
}

IdentityScanOptions configures an offline scan.

type IdentityScanStats added in v0.4.97

type IdentityScanStats struct {
	Rows           int64 `json:"rows"`
	Batches        int64 `json:"batches"`
	Scanned        int64 `json:"scanned"`
	Truncated      bool  `json:"truncated"`
	BinarySkipped  int64 `json:"binary_skipped"`
	BlobMissing    int64 `json:"blob_missing"`
	BodyMissing    int64 `json:"body_missing"`
	LegacyRows     int64 `json:"legacy_rows"`
	DurationMillis int64 `json:"duration_ms"`
}

IdentityScanStats counts work done, independent of coverage.

type IdentitySuppressed added in v0.4.97

type IdentitySuppressed struct {
	ByAllowlist int64                    `json:"by_allowlist"`
	Rules       []IdentitySuppressedRule `json:"rules,omitempty"`
}

IdentitySuppressed records allowlisted hits without silently dropping them.

type IdentitySuppressedRule added in v0.4.97

type IdentitySuppressedRule struct {
	TermID string `json:"term_id,omitempty"`
	Host   string `json:"host,omitempty"`
	Reason string `json:"reason"`
	Count  int64  `json:"count"`
}

IdentitySuppressedRule records one allowlist rule that fired.

type IdentityTaskStat added in v0.4.97

type IdentityTaskStat struct {
	TaskID   int64            `json:"task_id"`
	Hosts    []string         `json:"hosts"`
	Shared   bool             `json:"shared"`
	Hits     map[string]int64 `json:"hits"`
	Findings int64            `json:"findings"`
}

IdentityTaskStat is an external host->task aggregation.

type IdentityTerm added in v0.4.97

type IdentityTerm struct {
	ID       string `json:"id"`
	List     string `json:"list"`
	Pattern  string `json:"pattern"`
	Boundary bool   `json:"boundary"`
	CJK      bool   `json:"cjk"`
	Note     string `json:"note,omitempty"`
	// contains filtered or unexported fields
}

IdentityTerm is one literal pattern in an identity wordlist.

Three lists mirror issue #40:

  • A: platform brand / namespace strings (high confidence);
  • B: platform capability, tool and skill names (medium confidence);
  • C: generic framework / security-tool defaults (low confidence).

Boundary=false makes the term a plain substring. Boundary=true rejects a hit whose neighbouring ASCII byte is a letter or digit, so "pojun" matches "pojun-hostd" and "POJUN_WORKER_CHAT" but not "pojunk" or "Pojunior". Underscore is deliberately not a boundary character: the platform's env prefixes are themselves brand evidence.

type PageQuery

type PageQuery struct {
	Host    string // host substring
	Method  string // exact method (case-insensitive)
	Query   string // broad search box: metadata columns OR captured text
	Body    string // content box: captured request/response text only (full-text)
	Path    string // url_template substring — the vulnerability's path
	Status  string // exact code ("404") or class bucket ("4xx")
	RespMin int64  // minimum resp_len, or -1 when unset
	RespMax int64  // maximum resp_len, or -1 when unset
	Sort    string // ts | status | resp_len (default ts)
	Order   string // asc | desc (default desc)
}

PageQuery bundles the optional filters and sort order for Page. Every filter is combined with AND; an empty string skips that filter, and RespMin/RespMax of -1 skip the response-size bounds. An empty Sort/Order defaults to newest-first by timestamp.

type PoolEntry

type PoolEntry struct {
	URL      string `json:"url"`      // http/https/socks5,可含 user:pass(输出时掩码)
	Name     string `json:"name"`     // 展示名
	Enabled  bool   `json:"enabled"`  // 手动开关
	Weight   int    `json:"weight"`   // 轮询权重(round_robin 有效,≥1)
	Failures int    `json:"failures"` // 连败计数(熔断窗口)
	LastOK   string `json:"last_ok,omitempty"`
	LastFail string `json:"last_fail,omitempty"`
	// BreakRemaining 是该上游当前熔断的剩余秒数(0=未熔断)。主动健康检查与
	// 手动验证都会读写 last_ok/last_fail/break,页面据此筛选失效代理。
	BreakRemaining int `json:"break_remaining,omitempty"`
}

PoolEntry 是池中的一个上游代理。

type RetentionDeleteResult added in v0.4.120

type RetentionDeleteResult struct {
	Deleted       int64 `json:"deleted"`
	Protected     int64 `json:"protected"`
	LegacyDirs    int64 `json:"legacy_dirs"`
	BlobReclaimed bool  `json:"blob_reclaimed"`
}

RetentionDeleteResult reports a committed retention pass.

type RetentionStats added in v0.4.120

type RetentionStats struct {
	Candidates int64 `json:"candidates"`
	Protected  int64 `json:"protected"`
	Deletable  int64 `json:"deletable"`
}

RetentionStats is a dry-run view of age-based cleanup. Protected counts exchanges that are older than the cutoff but referenced by PostgreSQL evidence/regression/graph state; they are never deleted.

type Traffic

type Traffic struct {
	// contains filtered or unexported fields
}

Traffic runs the recording proxy and owns the file tree + index.

func Open

func Open(dir, addr string) (*Traffic, error)

Open initializes the traffic tree, blob store and SQLite index under dir.

func (*Traffic) Blob

func (t *Traffic) Blob(hash string) (*os.File, int64, error)

Blob opens a spilled body for streaming; the caller must close the file. Streaming matters here: the driver exposes no incremental BLOB API, so keeping large bodies on disk is what lets them be served without loading them whole.

func (*Traffic) BlobBytes added in v0.4.123

func (t *Traffic) BlobBytes() int64

BlobBytes 返回内容寻址 blob 目录占用的字节数(含两个历史分层布局)。

func (*Traffic) BlobRange

func (t *Traffic) BlobRange(hash string, offset, length int64) (data []byte, total int64, err error)

BlobRange reads at most length bytes of a blob from offset, and reports the blob's total size. Used by the agent tool to page through a large body without pulling all of it into the model's context.

func (*Traffic) CACertPath

func (t *Traffic) CACertPath() string

CACertPath returns the PEM CA cert clients must trust to verify HTTPS through the MITM proxy (go-mitmproxy writes it here on first start).

func (*Traffic) CancelReclaim added in v0.4.123

func (t *Traffic) CancelReclaim()

reclaim hands space freed by a deletion back to the filesystem. Deleting rows only makes them invisible: SQLite chains their pages onto a freelist, and deleting from the contentless_delete full-text index writes tombstones rather than removing the postings they hide. Neither shrinks a single byte on disk, and since bodies below maxInlineBody live in that same file, an install that captures heavily ends up holding far more than the traffic it still has.

The work is done in the background, in bounded steps that drop the write lock between them, because it is proportional to what was deleted — freeing several gigabytes under one lock would stall record(), which go-mitmproxy calls before it replies to the client, and so would stall the requests being recorded. Safe to call with wmu held: the background pass simply waits for it.

Best-effort throughout. Failing to reclaim costs disk space, never correctness, so errors are logged and the next deletion resumes the work. CancelReclaim asks an in-flight background reclamation to stop after its current bounded chunk. It is advisory: the pass may already be between chunks.

func (*Traffic) Close

func (t *Traffic) Close() error

Close waits for background tree reclamation to finish before closing the index, so shutdown never leaves a goroutine unlinking files out from under a removed data directory. Index-space reclamation is signalled to stop first: it holds a whole minutes-long budget, and finishing it is never worth delaying shutdown for — the next deletion resumes it.

func (*Traffic) Count

func (t *Traffic) Count() (int, error)

Count returns total recorded exchanges.

func (*Traffic) DB

func (t *Traffic) DB() *sql.DB

func (*Traffic) DeleteAll

func (t *Traffic) DeleteAll() (deleted int64, reclaimed int64, err error)

DeleteAll removes every recorded exchange — the page's clear-everything action. It differs from the host-scoped deletions in two ways. It sweeps host directories without consulting the index, because "clear everything" should leave nothing behind and a directory whose rows are already gone would otherwise survive. And it ends with a full compaction: VACUUM costs what it keeps, so an emptied index is the one moment it is free, and it is also the only way to switch on auto_vacuum for a database created without it.

Evidence already bound to a finding is untouched. Those bodies were copied into the evidence store when they were bound, precisely so that disposable traffic could be cleared without taking proof with it.

Returns the number of exchanges deleted and how many bytes of index the compaction handed back.

func (*Traffic) DeleteHost

func (t *Traffic) DeleteHost(host string) (int64, error)

DeleteHost removes every recorded exchange whose host contains the given substring — mirroring the UI's host filter, so what you filtered is what gets deleted. Everything lives in SQLite, so the deletion is one transaction across the index, bodies, full-text index and blob references. Content-addressed blobs are shared across hosts and so are garbage-collected afterwards rather than deleted by host. Returns rows deleted.

func (*Traffic) DeleteHostsBatched added in v0.4.123

func (t *Traffic) DeleteHostsBatched(ctx context.Context, hosts []string, cutoff int64, guard HostGuard, progress func(done, total int64)) (int64, error)

DeleteHostsBatched removes traffic for the given hosts in bounded SQLite transactions. cutoff is the unix second when the delete was requested; rows recorded after it are never touched, so a task that starts on the same host after the deletion keeps its fresh traffic.

func (*Traffic) DeleteHostsExact

func (t *Traffic) DeleteHostsExact(hosts []string) (int64, error)

DeleteHostsExact removes recorded exchanges for a set of EXACT hosts (the batch path for the page's multi-select delete): index rows + each host's file tree, then one blob-GC pass. Exact match — unlike DeleteHost's substring — so picking "api.example.com" never sweeps "api.example.com.cn". Returns rows deleted. Duplicate hosts are harmless (idempotent deletes, single tree pass).

func (*Traffic) DeleteUnreferencedBefore added in v0.4.120

func (t *Traffic) DeleteUnreferencedBefore(before time.Time, protected map[string]struct{}) (RetentionDeleteResult, error)

DeleteUnreferencedBefore removes exchanges older than before whose IDs are not in protected. It uses the same deleteWhere path as manual host deletion, so bodies, blob refs and the FTS index are removed in one SQLite transaction; blob GC + incremental vacuum run afterwards. The caller must supply a fail-closed protected set (a failed PG query must not become an empty map).

func (*Traffic) DiagnosticsStats added in v0.4.84

func (t *Traffic) DiagnosticsStats(since int64, topHosts int) map[string]any

DiagnosticsStats 汇总流量索引(只读、无正文):总量、时间范围、按 host/状态码 分布、5xx/连接失败主机。诊断包用它判断“捕获是否在工作、失败集中在哪”。

func (*Traffic) DirectRecordFallback added in v0.4.83

func (t *Traffic) DirectRecordFallback() bool

DirectRecordFallback reports the current fallback switch.

func (*Traffic) ExportHosts

func (t *Traffic) ExportHosts(hosts []string, dir string) (int64, error)

ExportHosts writes an exact-host snapshot to dir. It holds the traffic writer lock while reading SQLite and blobs, so each body and its index row come from one consistent point in time.

func (*Traffic) Get

func (t *Traffic) Get(id string) (req, resp string, err error)

Get returns the full request/response text of one exchange. Bodies come from the database; rows recorded before bodies moved into SQLite carry a non-empty path and are read from the legacy on-disk tree instead, so history stays readable without being migrated.

func (*Traffic) Hosts

func (t *Traffic) Hosts() ([]HostCount, error)

Hosts returns distinct recorded hosts with exchange counts, most recent activity first — powers the page's target picker.

func (*Traffic) ImportArchive

func (t *Traffic) ImportArchive(dir string) (int64, error)

ImportArchive imports only missing exchange IDs. Current hot rows always win, and repeated restore attempts are safe after a partial external failure.

func (*Traffic) Page

func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total int, err error)

Page returns one page of exchange metadata for the traffic list, filtered by the criteria in f (all optional, combined with AND) and ordered by the requested column. Query is the broad search box (metadata columns OR, when the term is long enough for the trigram index, captured request/response text); Body narrows to exchanges whose captured text matches, via that same index. Also returns the total number of rows matching the filter (for the UI's pagination). Bodies are never included in the rows.

func (*Traffic) PinEvidence added in v0.4.123

func (t *Traffic) PinEvidence(ids []string) error

PinEvidence marks exchanges referenced by a finding so evidence-only cleanup never removes them. Best-effort and idempotent: a later transaction rollback merely keeps a little extra traffic.

func (*Traffic) PreviewUnpinnedBefore added in v0.4.123

func (t *Traffic) PreviewUnpinnedBefore(cutoffUnix int64) (int64, error)

PreviewUnpinnedBefore is the read-only dry-run used by the storage page.

func (*Traffic) ProxyAddr

func (t *Traffic) ProxyAddr() string

ProxyAddr returns the address workers should set as HTTP(S)_PROXY. A bare ":port" means "bind all interfaces" (legacy default), so map it to loopback.

func (*Traffic) ProxyPoolAvailable added in v0.4.83

func (t *Traffic) ProxyPoolAvailable() int

ProxyPoolAvailable 返回当前未被熔断的上游数量(UI 用于提示「可用 N/M」)。

func (*Traffic) ProxyPoolClearBreak added in v0.4.83

func (t *Traffic) ProxyPoolClearBreak(proxyRaw string) bool

ProxyPoolClearBreak 清除某上游的熔断状态(导入验活/手动验活成功后调用)。 返回是否找到该条目;池为空时返回 false。

func (*Traffic) ProxyPoolConfigured added in v0.4.83

func (t *Traffic) ProxyPoolConfigured() bool

ProxyPoolConfigured 报告池里是否有启用的条目(全部熔断也算已配置)。

func (*Traffic) ProxyPoolEnabled

func (t *Traffic) ProxyPoolEnabled() bool

ProxyPoolEnabled reports whether the proxy pool is configured and running.

func (*Traffic) ProxyPoolMarkBad

func (t *Traffic) ProxyPoolMarkBad(proxyRaw string, cooldown time.Duration) string

ProxyPoolMarkBad 把某个上游立即熔断 cooldown(主动健康检查 / 手动验证失败时用)。 返回被熔断的掩码 URL,空串表示不在池里。

func (*Traffic) ProxyPoolPick added in v0.4.83

func (t *Traffic) ProxyPoolPick(host string) string

host 为空时按策略视作同一个「虚拟目标」;sticky_host_random 会因此把整台机器 钉在同一个出口上,符合「一个任务一个出口」的直觉。

func (*Traffic) ProxyPoolReportBad

func (t *Traffic) ProxyPoolReportBad(target string, cooldown time.Duration) string

ProxyPoolReportBad 让调用方(Agent)把某个目标「当前正在用的出口」立即熔断。 target 可以是完整 host:port —— MITM 侧按 host 记录了最近一次选中的上游, 所以不需要请求方知道它到底走了哪个代理。返回被熔断的掩码 URL,空串表示 池为空 / 该目标没走过池上游(例如直连或全局单代理)。

func (*Traffic) ProxyPoolReportFail

func (t *Traffic) ProxyPoolReportFail(proxyRaw string)

ProxyPoolReportFail 上报一次失败(只累计连败,不立刻熔断——被动路径的阈值是 5 次)。

func (*Traffic) ProxyPoolReportOK

func (t *Traffic) ProxyPoolReportOK(proxyRaw string)

ProxyPoolReportOK 上报一次成功(清零连败,记录时间)。

func (*Traffic) ProxyPoolStatus

func (t *Traffic) ProxyPoolStatus() []PoolEntry

ProxyPoolStatus 导出池内条目(掩码 URL + 熔断计数),供 UI 展示。

func (*Traffic) ProxyPoolStrategy added in v0.4.110

func (t *Traffic) ProxyPoolStrategy() string

ProxyPoolStrategy 返回选择器当前生效的轮换策略;池未装载时返回空串。 只读访问器,供出口回执等观测面使用,不影响 Pick/熔断行为。

func (*Traffic) PruneUnpinnedBefore added in v0.4.123

func (t *Traffic) PruneUnpinnedBefore(cutoffUnix int64) (int64, error)

PruneUnpinnedBefore removes exchanges older than cutoff that no finding has pinned. Evidence-only capture uses this instead of PruneBefore: findings keep their own snapshot copy, and the pin keeps the original searchable.

func (*Traffic) PruneUnpinnedToSize added in v0.4.123

func (t *Traffic) PruneUnpinnedToSize(maxBytes int64) (int64, error)

PruneUnpinnedToSize deletes the oldest unpinned exchanges until the index and blob files fall under maxBytes. Pinned (evidence-referenced) rows are never selected, so the cap can be exceeded when evidence itself is larger.

func (*Traffic) ReadEvidence

func (t *Traffic) ReadEvidence(ctx context.Context, ids []string, consume func(EvidenceExchange) error) error

func (*Traffic) RecoverHostDeleteStages

func (t *Traffic) RecoverHostDeleteStages(archiveCommitted func(int64, int64) (bool, error)) error

RecoverHostDeleteStages resolves filesystem moves left by a process exit. SQLite rolls open transactions back on restart, while the supplied callback identifies task archives whose PostgreSQL compaction already committed.

func (*Traffic) RestoreProxyBreaks added in v0.4.83

func (t *Traffic) RestoreProxyBreaks(state map[string]int64) int

RestoreProxyBreaks 应用持久化的熔断状态,返回恢复的条目数。

func (*Traffic) RetentionPreview added in v0.4.120

func (t *Traffic) RetentionPreview(before time.Time, protected map[string]struct{}) (RetentionStats, error)

RetentionPreview counts exchanges older than before, split into protected and deletable. It is read-only and takes no write lock.

func (*Traffic) Running added in v0.4.110

func (t *Traffic) Running() bool

Running reports whether the recording proxy is currently serving (Start has not returned). False means capture may be enabled in settings but the proxy is not listening — nothing would actually be recorded.

func (*Traffic) Search

func (t *Traffic) Search(host string, page, size int) ([]ExchangeMeta, error)

Search returns paged exchange metadata (never bodies).

func (*Traffic) SetDirectRecordFallback added in v0.4.83

func (t *Traffic) SetDirectRecordFallback(on bool)

SetDirectRecordFallback enables "direct dial but still record" when strict egress is on and every pool upstream is broken. Operators opt in explicitly; it trades real-IP exposure for continuous traffic evidence.

func (*Traffic) SetProxyPool

func (t *Traffic) SetProxyPool(items []PoolEntry, strategy string) error

SetProxyPool 原子替换代理池(Traffic 门面)。

func (*Traffic) SetStrictEgress added in v0.4.83

func (t *Traffic) SetStrictEgress(on bool)

SetStrictEgress 开关严格出口:池已配置但无可用上游时,MITM 与 Agent 均失败, 不回退直连。由 server 按设置项 egress_strict_proxy 注入。

func (*Traffic) SetUpstreamProxy

func (t *Traffic) SetUpstreamProxy(raw string) error

SetUpstreamProxy points every captured request at a global egress proxy (http/https/socks5, optional user:pass in the URL). An empty raw string clears it, restoring direct dialing. The change is atomic and takes effect on the next connection — no restart, no proxy rebuild. go-mitmproxy dials all three schemes itself, so socks5 works uniformly here regardless of the target tool. Validation failure leaves the previous value untouched (so a rejected global proxy never silently becomes the effective downstream).

func (*Traffic) SnapshotProxyBreaks added in v0.4.83

func (t *Traffic) SnapshotProxyBreaks() map[string]int64

SnapshotProxyBreaks 导出未到期的熔断状态(供 server 持久化,跨重启保留)。

func (*Traffic) StageDeleteHostsExact

func (t *Traffic) StageDeleteHostsExact(hosts []string) (*HostDeleteStage, error)

StageDeleteHostsExact prepares a reversible exact-host deletion. Callers must finish every successful stage with Commit or Rollback.

func (*Traffic) StageDeleteHostsExactForArchive

func (t *Traffic) StageDeleteHostsExactForArchive(hosts []string, archiveID, taskID int64) (*HostDeleteStage, error)

StageDeleteHostsExactForArchive ties the reversible traffic deletion to a persistent task archive. Startup recovery uses archiveCommitted to decide whether an interrupted stage must be completed or rolled back.

func (*Traffic) Start

func (t *Traffic) Start() error

Start runs the proxy (blocking); run in a goroutine.

func (*Traffic) Stats added in v0.4.123

func (t *Traffic) Stats() (TrafficStats, error)

Stats 汇总索引/blob/条数与时间范围。查询失败时返回已取得的磁盘大小。

func (*Traffic) StrictEgress added in v0.4.83

func (t *Traffic) StrictEgress() bool

StrictEgress 返回当前严格出口开关状态。

func (*Traffic) Tools

func (t *Traffic) Tools() []actool.CoreTool

Tools exposes traffic lookup to work agents so they query already-captured traffic instead of re-curling the same resource (token + dedup win).

func (*Traffic) UpstreamProxy added in v0.4.110

func (t *Traffic) UpstreamProxy() string

UpstreamProxy returns the global egress proxy the MITM actually holds, as a URL string. Empty means direct dialing. This is the authoritative value for "where captured traffic goes": a global proxy that failed validation when the manager loaded it was never stored here, so reading the persisted setting instead would misreport the effective upstream.

type TrafficStats added in v0.4.123

type TrafficStats struct {
	IndexBytes int64 `json:"index_bytes"`
	BlobBytes  int64 `json:"blob_bytes"`
	Exchanges  int64 `json:"exchanges"`
	OldestTS   int64 `json:"oldest_ts"`
	NewestTS   int64 `json:"newest_ts"`
}

TrafficStats 是存储页展示用的轻量统计。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL