runner

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 35 Imported by: ? modules, 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 runner 请求 / 响应缓存。

底层基于 otter.Cache(W-TinyLFU 自适应淘汰算法): TTL 由 ExpiryWriting 自动维护,条目权重同时限制响应字节和数量。 每次扫描的作用域记录自己写入的键,扫描结束时只删除这些键。

CacheManager 完全实例化,调用方持有独立缓存。

Package runner 指纹规则集(实例化)。

每个 Runner 持有独立的 *FingerStore;加载成功后整体发布只读规则快照。

Package runner sync.Pool 集合:RuleTask / varMap / FingerMatch。 进程级(无业务状态),任意 Runner 实例都可以安全复用。

Package runner 性能监控器。

基于 runtime/metrics 采集内存、GC、调度延迟等指标, sample 切片通过 sync.Pool 复用以避免分配。

PerformanceMonitor 完全实例化:调用方持有独立监控器, 可绑定自定义 onPressure 回调以实现降并发等响应策略。

Package runner 工作池抽象 + RulePool 实例。

底层基于 ants v2 的 PoolWithFunc,URL 池和规则池分别控制并发容量。 单池保持配置容量的精确语义,避免分桶取整导致实际容量超限。

Package runner 顶层 Runner 实例。

*Runner 是 GXX 引擎的核心运行时,持有:

  • *FingerStore:指纹规则集
  • *RulePool:规则评估协程池(ants v2 PoolWithFunc)
  • *CacheManager:请求 / 响应缓存(otter v2 W-TinyLFU)
  • *PerformanceMonitor:运行时指标监控
  • *network.HostRateLimiter:可选的 per-host 限流器
  • *network.HTTPClient:实例化 HTTP 客户端

NewRunner 在构造期完成所有资源初始化;Close 统一释放资源。

Package runner 单目标扫描流程(合并基础信息探测 + 指纹规则匹配)。

所有扫描方法都挂在 *Runner 上,资源句柄(FingerStore / RulePool / CacheManager / HostRateLimiter / HTTPClient)全部通过 Runner 字段访问,不依赖任何包级状态。

Package runner 提供指纹识别的运行时核心。

Index

Constants

View Source
const (
	ResourceRobots  = "robots"
	ResourceSitemap = "sitemap"
)

附属资源的类型。

View Source
const (
	DefaultURLWorkers  = 5
	DefaultRuleWorkers = 200
	MaxRuleWorkers     = 5000
	MinRuleWorkers     = 200
)

全局并发常量。

View Source
const DefaultResourceBytes = 64 << 10

DefaultResourceBytes 是每个附属资源默认保留的正文字节数。

Variables

This section is empty.

Functions

func EntryChain added in v1.6.1

func EntryChain(ctx context.Context, client *network.HTTPClient, target string, options network.OptionsRequest) ([]EntryPage, []Redirect, error)

EntryChain 按扫描时的方式请求入口并跟随跳转,返回链上各页(入口在前, 最后一页在后)与每一跳的记录。调试工具用它逐页评估规则,结果与扫描一致。

func IsEntryPageRule added in v1.6.1

func IsEntryPageRule(req finger.RuleRequest) bool

IsEntryPageRule 判断规则匹配的是否就是入口页:对根路径的、跟随跳转的普通 GET。 这类规则依次在入口跳转链的每一页上评估。

Types

type BaseInfo

type BaseInfo struct {
	Title      string
	Server     *types.ServerInfo
	StatusCode int32
	// contains filtered or unexported fields
}

BaseInfo 仅含规则匹配所需的少量基础字段,放入 varMap 给 CEL 使用。

type BaseInfoResponse

type BaseInfoResponse struct {
	Url        string
	Title      string
	Server     *types.ServerInfo
	StatusCode int32
	Response   *http.Response
	Wappalyzer *wappalyzer.TypeWappalyzer
	BodyBytes  []byte
	ICP        string
	Certs      []*types.CertInfo
	// FinalURL 是跳转链最后一页的地址;RedirectTo 是页面里识别出的、指向其他资产而未跟随的跳转目标。
	FinalURL   string
	RedirectTo string
	Redirects  []Redirect
	// HeaderOrder 是最后一页的响应头名称,按服务器发送的顺序;TLS 是最后一页所在连接的握手摘要。
	HeaderOrder []string
	TLS         *network.TLSInfo
	// Icon 是最后一页图标的证据,开启 IconEvidence 时记录。
	Icon *finger.IconEvidence
	// Resources 是最后一页所在资产的附属资源,开启 Resources 时读取。
	Resources []Resource
	// contains filtered or unexported fields
}

BaseInfoResponse 包含目标基础信息和 HTTP 响应。

type CacheManager

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

CacheManager 请求 / 响应缓存管理器。

func (*CacheManager) ClearTarget

func (cm *CacheManager) ClearTarget(target string)

ClearTarget 删除某个 host 下所有缓存。

func (*CacheManager) Close

func (cm *CacheManager) Close()

Close 释放底层 otter 后台 goroutine。

func (*CacheManager) Get

func (cm *CacheManager) Get(key string) (*CacheRequest, bool)

Get 读取缓存条目;命中时返回 (entry, true)。

func (*CacheManager) Invalidate

func (cm *CacheManager) Invalidate(cacheKey string)

Invalidate 删除单条缓存。

func (*CacheManager) InvalidateAll

func (cm *CacheManager) InvalidateAll()

InvalidateAll 清空所有缓存。

func (*CacheManager) InvalidateTarget

func (cm *CacheManager) InvalidateTarget(targetKey string) int

InvalidateTarget 删除指定 host 下所有缓存条目,返回删除数量。

func (*CacheManager) Set

func (cm *CacheManager) Set(targetKey, cacheKey string, entry *CacheRequest)

Set 写入只读条目,超过单条字节预算时跳过缓存。

func (*CacheManager) ShouldUseCache

func (cm *CacheManager) ShouldUseCache(rule finger.RuleMap, target string) (bool, *proto.Request, *proto.Response)

ShouldUseCache 判断当前规则是否可命中缓存。命中条件:

  1. 协议为 HTTP/HTTPS(type 为空或 "http")
  2. 方法为 GET / POST
  3. headers 与 body 均为空
  4. 缓存中存在对应键且未过期

func (*CacheManager) Stats

func (cm *CacheManager) Stats() map[string]interface{}

Stats 返回缓存统计快照。

func (*CacheManager) UpdateTargetCache

func (cm *CacheManager) UpdateTargetCache(variableMap map[string]any, target string, followRedirects bool)

UpdateTargetCache 更新缓存:仅在 headers / body 为空且方法为 GET / POST 时生效。

type CacheRequest

type CacheRequest struct {
	Request  *proto.Request  `json:"request"`
	Response *proto.Response `json:"response"`

	Timestamp int64 `json:"timestamp"`
	// contains filtered or unexported fields
}

CacheRequest 缓存条目,保存原始 proto.Request / proto.Response。

type EntryPage added in v1.6.1

type EntryPage struct {
	URL      string
	Request  *proto.Request
	Response *proto.Response
}

EntryPage 是入口跳转链上的一页,以及规则在这一页上看到的请求与响应。

type EvaluationFailure added in v1.8.0

type EvaluationFailure struct {
	RuleID  string
	SubRule string
	Stage   FailureStage
	Message string
}

EvaluationFailure 是一处使结论不完整的原因。Message 是有界文本,不含响应正文。

type EvaluationReport added in v1.8.0

type EvaluationReport struct {
	Complete  bool
	Rules     []RuleEvaluation
	Truncated bool
}

EvaluationReport 报告一次扫描中每条规则是否完整求值,不改变普通匹配语义。 Complete 为 true 表示全部规则都已执行且没有任何失败;Truncated 表示记录超出上限被省略。

type FailureStage added in v1.8.0

type FailureStage string

FailureStage 是规则求值不完整的原因。

const (
	StageRequest      FailureStage = "request"       // 子规则的请求失败
	StageExpression   FailureStage = "expression"    // 表达式运行错误
	StageNonBool      FailureStage = "non_bool"      // 表达式结果不是布尔值
	StageExtract      FailureStage = "extract"       // 输出提取失败
	StageRegexTimeout FailureStage = "regex_timeout" // 正则匹配超时,按未命中处理
	StagePanic        FailureStage = "panic"         // 求值过程 panic
	StageBudget       FailureStage = "budget"        // 超出资源预算:正文截断、计算成本或记录上限
)

type FingerMatch

type FingerMatch struct {
	Finger           *finger.Finger
	Result           bool
	Request          *proto.Request
	Response         *proto.Response
	MatchedRules     []SubRuleMatch
	ProductVersion   string
	ProductVersions  []string
	VersionConflict  bool
	DetailsTruncated bool
}

FingerMatch 单条指纹匹配结果。

type FingerStore

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

FingerStore 指纹规则集合实例。

func NewFingerStore

func NewFingerStore(logs ...logger.Sink) *FingerStore

NewFingerStore 创建空 store。

func (*FingerStore) Count

func (fs *FingerStore) Count() int

Count 返回当前指纹数量。

func (*FingerStore) Load

func (fs *FingerStore) Load(options types.YamlFingerType) error

Load 加载指纹规则。解析失败时保留原规则集,成功后整体替换。

func (*FingerStore) Metadata added in v1.2.0

func (fs *FingerStore) Metadata() []finger.Metadata

Metadata 返回独立的元数据副本,不暴露可修改的执行规则。

type MemoryStats

type MemoryStats struct {
	HeapAlloc      uint64
	HeapSys        uint64
	HeapIdle       uint64
	HeapInUse      uint64
	NumGC          uint32
	GCCPUFraction  float64
	LastGCTime     time.Time
	MemoryUsage    float64
	NumGoroutine   int
	GoSchedLatency float64
}

MemoryStats 内存统计快照。

type PerformanceMonitor

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

PerformanceMonitor 性能监控器实例。

监控器周期性采样运行时指标,并通过两类回调驱动调用方做出反应:

  • onPressure:HeapAlloc 超过高阈值或占用率过高时触发,用于降并发等止血动作;
  • onRelief: 连续 reliefThreshold 个 tick 处于低压状态时触发, 调用方可据此逐步恢复 worker 容量,避免压力消除后并发度单调衰减。

func NewPerformanceMonitor

func NewPerformanceMonitor(highBytes, criticalBytes uint64, onPressure func(*MemoryStats)) *PerformanceMonitor

NewPerformanceMonitor 创建监控器实例。

  • highBytes / criticalBytes: 内存阈值,<= 0 时使用默认 2GB / 4GB
  • onPressure: 内存压力到达高阈值时的回调;nil 表示仅记录告警

默认 reliefThreshold = 4(连续 4 tick / ~60s 低压力触发恢复), reliefUsageLimit = 0.6(HeapAlloc 占 HeapSys 比例 ≤ 60% 且 < highMem 视为低压力)。

func (*PerformanceMonitor) EnableProactiveGC

func (pm *PerformanceMonitor) EnableProactiveGC(on bool)

EnableProactiveGC 控制压力时是否主动 runtime.GC()。

func (*PerformanceMonitor) SetReliefCallback

func (pm *PerformanceMonitor) SetReliefCallback(onRelief func(*MemoryStats), streakThreshold int, usageLimit float64)

SetReliefCallback 设置低压恢复回调,可在内存压力解除后逐步恢复 worker 容量等。 通过 streakThreshold 控制需要连续多少个低压 tick 才触发(默认 4), usageLimit 设定低压阈值上限(HeapAlloc / HeapSys,默认 0.6)。 streakThreshold <= 0 / usageLimit <= 0 时保留默认值。

func (*PerformanceMonitor) Start

func (pm *PerformanceMonitor) Start()

Start 启动监控(线程安全,重复调用 noop)。

func (*PerformanceMonitor) Stop

func (pm *PerformanceMonitor) Stop()

type Pool

type Pool interface {
	Invoke(args interface{}) error
	Tune(size int)
	Release(ctx context.Context) error
}

Pool 工作池统一接口。

func NewWorkPoolWithFunc

func NewWorkPoolWithFunc(
	workerCount int,
	handler func(interface{}),
	maxBlockingTasks int,
	expiry time.Duration,
	panicHandler func(interface{}),
) (Pool, error)

NewWorkPoolWithFunc 创建单池 ants.PoolWithFunc 包装,适合 worker 数较少的场景。

type Redirect added in v1.5.0

type Redirect struct {
	Type     string // http / refresh / javascript
	Status   int32  // 发出跳转的响应的状态码
	From     string
	To       string
	Followed bool
}

Redirect 入口跳转链上的一跳。Followed 为 false 表示页面里识别出的跳转指向其他资产,没有访问。

type Resource added in v1.8.0

type Resource struct {
	Kind       string
	URL        string
	StatusCode int
	Body       []byte
	BodyBytes  int64
	SHA256     string
	Truncated  bool
}

Resource 是一个附属资源。Body 是正文的前 MaxBytes 字节;BodyBytes 与 SHA256 覆盖实际 读取的正文(受引擎正文读取上限约束);Truncated 表示 Body 短于实际正文或正文超过读取上限。

type ResourceOptions added in v1.8.0

type ResourceOptions struct {
	Robots   bool
	Sitemap  bool
	MaxBytes int
}

ResourceOptions 选择要读取的附属资源。MaxBytes 是每个资源保留的正文上限,0 取默认值。

type RuleDebug added in v1.8.0

type RuleDebug struct {
	Match      *FingerMatch
	SubRules   []SubRuleDebug
	Evaluation RuleEvaluation
	// Result 是只执行这条规则的扫描结果(入口跳转链、标题、证书等与普通扫描相同)。
	Result *TargetResult
}

RuleDebug 是单条规则按扫描方式执行一次的完整中间结果。Match 为 nil 表示未命中。 入口跳转链上有多页时,SubRules 描述决定结果的那次评估:命中的那一页,未命中时为最后一页。

type RuleEvaluation added in v1.8.0

type RuleEvaluation struct {
	RuleID       string
	SourceSHA256 string
	Completed    bool
	Matched      bool
	Failures     []EvaluationFailure
}

RuleEvaluation 是一条规则的求值情况。Completed 为 true 表示每个子规则都取得了响应 并正常求值;Matched 与普通扫描的命中结果一致。

type RulePool

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

RulePool 规则评估协程池实例。

func NewRulePool

func NewRulePool(workerCount int, taskHandler func(*RuleTask), logs ...logger.Sink) (*RulePool, error)

NewRulePool 创建规则池实例。

  • workerCount: 总 worker 容量
  • taskHandler: 处理 *RuleTask 的回调

func (*RulePool) CurrentWorkers

func (rp *RulePool) CurrentWorkers() int

CurrentWorkers 当前规则池总 worker 容量。

func (*RulePool) IsClosed

func (rp *RulePool) IsClosed() bool

IsClosed 是否已 Release。

func (*RulePool) Release

func (rp *RulePool) Release(ctx context.Context) error

Release 释放规则池资源(使用 ctx 控制 graceful 退出超时)。

func (*RulePool) Stats

func (rp *RulePool) Stats() RulePoolStats

Stats 返回任务统计快照。

func (*RulePool) Submit

func (rp *RulePool) Submit(task *RuleTask) error

Submit 把任务提交到规则池。

func (*RulePool) Tune

func (rp *RulePool) Tune(totalWorkers int)

Tune 按总 worker 容量下调/上调(内部维持实例总容量)。

type RulePoolStats

type RulePoolStats struct {
	TotalTasks     int64
	CompletedTasks int64
	FailedTasks    int64
}

RulePoolStats 规则池任务统计。

type RuleTask

type RuleTask struct {
	Ctx        context.Context
	Target     string
	Finger     *finger.Finger
	BaseInfo   *BaseInfo
	Proxy      string
	Timeout    time.Duration
	ResultChan chan<- *FingerMatch
	WaitGroup  *sync.WaitGroup
	DoneHook   func()
	// contains filtered or unexported fields
}

RuleTask 规则处理任务结构。

type Runner

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

Runner 指纹识别运行时。

func NewRunner

func NewRunner(cfg ScanConfig, pocOptions types.YamlFingerType) (*Runner, error)

NewRunner 创建并初始化 Runner 实例。

pocOptions 指定指纹规则文件 / 目录;空值时使用嵌入式指纹库。 调用方应在不再使用时执行 Runner.Close() 释放资源。

func (*Runner) Close

func (r *Runner) Close() error

Close 释放 Runner 持有的所有资源(线程安全,可重复调用)。

func (*Runner) DebugRule added in v1.8.0

func (r *Runner) DebugRule(ctx context.Context, target, ruleID string, opts ScanOptions) (*RuleDebug, error)

DebugRule 按扫描的方式对 target 只执行规则 ruleID,返回每条子规则的表达式结果、 交换记录、证据、输出与失败原因。结论与普通扫描一致:入口跳转链、请求缓存、 网络策略与求值规则完全相同,只是强制采集证据。

func (*Runner) FingerCount

func (r *Runner) FingerCount() int

FingerCount 当前加载的指纹数量。

func (*Runner) GetBaseInfo

func (r *Runner) GetBaseInfo(ctx context.Context, target string) (*BaseInfoResponse, error)

GetBaseInfo 仅获取目标基础信息(不跑指纹)。

func (*Runner) HTTPClient

func (r *Runner) HTTPClient() *network.HTTPClient

HTTPClient 返回 Runner 持有的 HTTP 客户端。

func (*Runner) LoadFingerOptions

func (r *Runner) LoadFingerOptions(opts types.YamlFingerType) error

LoadFingerOptions 重新加载指纹规则。

func (*Runner) PoolStats

func (r *Runner) PoolStats() RulePoolStats

PoolStats 规则池任务统计快照。

func (*Runner) ResolveTarget added in v1.5.0

func (r *Runner) ResolveTarget(ctx context.Context, target string) (string, error)

ResolveTarget 确定目标所属的资产地址:已带协议时原样返回,否则请求一次入口 以确定 https 还是 http。

func (*Runner) RuleMetadata added in v1.2.0

func (r *Runner) RuleMetadata() []finger.Metadata

RuleMetadata 返回当前规则快照的元数据。

func (*Runner) ScanTarget

func (r *Runner) ScanTarget(ctx context.Context, target string) (*TargetResult, error)

ScanTarget 对单目标执行完整指纹识别。

流程:

  1. 获取实例共享的目标并发名额
  2. 对 HTTP 规则执行探活,提取标题 / 证书 / Server / ICP / Wappalyzer
  3. warmUpRequestCache:把基础请求 / 响应写入缓存供后续规则复用
  4. executeFingerprintMatching:把所有适用指纹提交到规则池并发评估
  5. 清理本目标的缓存条目

func (*Runner) ScanTargetWith added in v1.8.0

func (r *Runner) ScanTargetWith(ctx context.Context, target string, opts ScanOptions) (*TargetResult, error)

ScanTargetWith 与 ScanTarget 相同,并应用本次扫描的附加配置。

type ScanConfig

type ScanConfig struct {
	CaptureEvidence   bool
	Reverse           types.ReverseConfig
	Proxy             string
	Timeout           time.Duration
	URLWorkerCount    int
	FingerWorkerCount int

	Logger           logger.Sink
	CacheMaxBytes    uint64
	CacheMaxSize     int
	CacheTTL         time.Duration
	MemHighBytes     uint64
	MemCriticalBytes uint64
	EnableMonitor    bool
	EnableProactive  bool

	RateLimitQPS   float64
	RateLimitBurst int
	// RateLimitPerPort 为 true 时每主机限速按“主机:端口”区分,默认按主机合并。
	RateLimitPerPort bool
	// GlobalRateLimit 是实例全部请求的总速率上限(次/秒),0 表示不限制。
	GlobalRateLimit      float64
	GlobalRateLimitBurst int

	DisableKeepAlives  bool
	InsecureSkipVerify bool
	CustomHeaders      map[string]string
	Debug              bool

	// Policy 是引擎级网络策略,约束全部出站连接。
	Policy network.Policy
	// BodyLimit 是响应正文的读取上限(字节),0 表示 network.MaxDefaultBody。
	BodyLimit int64
	// ResponseCacheBudget 是每次扫描的响应归一化缓存预算(字节),0 表示默认 8 MiB。
	ResponseCacheBudget int64
	// IconEvidence 为 true 时记录最终页面图标的证据,原始字节最多保留 IconEvidenceData。
	IconEvidence     bool
	IconEvidenceData int
	// JARM 为 true 时为 HTTPS 目标计算 JARM 指纹(另发 10 个 TLS 探测)。
	JARM bool
	// Resources 选择要读取的附属资源,默认全关。
	Resources ResourceOptions
	// RulePolicy 在加载与重新加载规则时检查,违反即加载失败。
	RulePolicy finger.RulePolicy
	// RuleCheck 在规则策略之后检查整个规则集(如同一产品的声明一致),返回错误即加载失败,
	// 原规则集保持不变。
	RuleCheck func([]*finger.Finger) error
}

ScanConfig 扫描配置参数。

type ScanOptions added in v1.8.0

type ScanOptions struct {
	// Policy 逐字段覆盖引擎级网络策略,只作用于本次扫描。
	Policy network.Policy
	// Report 非 nil 时,扫描结束(含失败与取消)后写入求值报告。
	Report *EvaluationReport
	// Observer 非 nil 时,每次交换完成后串行回调。
	Observer       func(network.Exchange)
	ExchangeLimits network.ExchangeLimits
}

ScanOptions 是单次扫描的附加配置,零值与普通扫描相同。

type SubRuleDebug added in v1.8.0

type SubRuleDebug struct {
	Key        string
	Expression string
	Result     *bool
	Exchanges  []network.Exchange
	Evidence   []cel.Evidence
	Outputs    map[string]string
	Failure    *EvaluationFailure
}

SubRuleDebug 是单条子规则在一次评估中的中间结果。Result 为 nil 表示没有得到 布尔结论(请求失败、表达式出错或扫描取消)。Exchanges 是该子规则使用的交换记录, 复用本次扫描已有响应时为 Cached 记录。

type SubRuleMatch added in v1.2.0

type SubRuleMatch struct {
	Key               string
	Expression        string
	Method            string
	Path              string
	URL               string
	StatusCode        int32
	Evidence          []cel.Evidence
	EvidenceTruncated bool
	Outputs           map[string]string
}

SubRuleMatch 只记录成功匹配的子规则,不保留原始响应。

type TargetResult

type TargetResult struct {
	URL          string
	StatusCode   int32
	Title        string
	Server       *types.ServerInfo
	Matches      []*FingerMatch
	Wappalyzer   *wappalyzer.TypeWappalyzer
	LastRequest  *proto.Request
	LastResponse *proto.Response
	ICP          string
	Certs        []*types.CertInfo
	FinalURL     string
	RedirectTo   string
	Redirects    []Redirect
	HeaderOrder  []string
	TLS          *network.TLSInfo
	Icon         *finger.IconEvidence
	Resources    []Resource
}

TargetResult 单个目标的扫描结果。

Jump to

Keyboard shortcuts

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