runner

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 36 Imported by: 0

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 CLI 风格批量扫描辅助函数:进度条、URL 工作池、汇总报告。

SDK 用户通常不使用本文件中的能力,而是直接调用 (*Runner).ScanTarget; 本文件是为 cmd/cli 入口提供的便捷封装。

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

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

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

Index

Constants

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

全局并发常量。

Variables

This section is empty.

Functions

func LoadTargets

func LoadTargets(options *types.CmdOptions) []string

LoadTargets 从命令行参数或目标文件中读取目标列表(带去重)。

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
	// contains filtered or unexported fields
}

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

type CacheManager

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

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

func NewCacheManager

func NewCacheManager(maxSize int, ttl time.Duration) *CacheManager

NewCacheManager 创建缓存管理器实例。 maxSize <= 0 时回退到 2048;ttl <= 0 时回退到 10 分钟。

func NewCacheManagerWithBudget

func NewCacheManagerWithBudget(maxSize int, ttl time.Duration, maxBytes uint64) *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 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) SetThresholds

func (pm *PerformanceMonitor) SetThresholds(highBytes, criticalBytes uint64)

SetThresholds 动态调整内存阈值。

func (*PerformanceMonitor) Snapshot

func (pm *PerformanceMonitor) Snapshot() MemoryStats

Snapshot 实时取一次内存快照(不依赖监控器是否启动)。

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 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) ResetStats

func (rp *RulePool) ResetStats()

ResetStats 把统计计数清零。

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) CacheStats

func (r *Runner) CacheStats() map[string]interface{}

CacheStats 缓存统计快照。

func (*Runner) Close

func (r *Runner) Close() error

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

func (*Runner) EnableMemoryMonitor

func (r *Runner) EnableMemoryMonitor(on bool)

EnableMemoryMonitor 运行期开关监控器。

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) HostRateLimiter

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

HostRateLimiter 返回当前 Runner 持有的限流器(可能为 nil)。

func (*Runner) IsClosed

func (r *Runner) IsClosed() bool

IsClosed Runner 是否已释放。

func (*Runner) LoadFingerOptions

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

LoadFingerOptions 重新加载指纹规则。

func (*Runner) MemoryStats

func (r *Runner) MemoryStats() MemoryStats

MemoryStats 实时内存快照。

func (*Runner) PoolStats

func (r *Runner) PoolStats() RulePoolStats

PoolStats 规则池任务统计快照。

func (*Runner) ResetPoolStats

func (r *Runner) ResetPoolStats()

ResetPoolStats 把规则池统计计数清零。

func (*Runner) RuleMetadata added in v1.2.0

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

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

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, options *types.CmdOptions) error

Run 执行批量扫描任务(CLI 入口)。

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) SetMemoryThresholds

func (r *Runner) SetMemoryThresholds(high, critical uint64)

SetMemoryThresholds 动态调整内存阈值。

type ScanConfig

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

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

	RateLimitQPS   float64
	RateLimitBurst int

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

ScanConfig 扫描配置参数。

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
}

TargetResult 单个目标的扫描结果。

Jump to

Keyboard shortcuts

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