diff options
| author | Handingkang <[email protected]> | 2023-08-31 11:21:58 +0800 |
|---|---|---|
| committer | Handingkang <[email protected]> | 2023-08-31 11:21:58 +0800 |
| commit | 5e110d8c330b49739ddee1f73b51ad510c85790a (patch) | |
| tree | ef84fe6a6e21edbd21160a5702bbb0afebf7fad7 | |
| parent | 010dc055a3b7a166dfdaf29f1bd9783b0abb17c0 (diff) | |
解决组件之间循环依赖的问题
| -rw-r--r-- | Ohmyfile | 30 | ||||
| -rw-r--r-- | core/dnsserver/zdirectives.go | 1 | ||||
| -rw-r--r-- | core/plug/zplugin.go | 3 | ||||
| -rw-r--r-- | core/prober/pdirectives.go | 9 | ||||
| -rw-r--r-- | core/prober/prober_http.go | 6 | ||||
| -rw-r--r-- | core/prober/prober_serve.go | 46 | ||||
| -rw-r--r-- | core/prober/register.go | 129 | ||||
| -rw-r--r-- | plugin.cfg | 3 | ||||
| -rw-r--r-- | plugin/atk/atk.go | 13 | ||||
| -rw-r--r-- | plugin/atk/setup.go | 2 | ||||
| -rw-r--r-- | plugin/pkg/prober/prober.go | 59 | ||||
| -rw-r--r-- | plugin/pkg/prober/prober_config.go (renamed from core/prober/prober_config.go) | 66 | ||||
| -rw-r--r-- | plugin/pkg/prober/prober_meta.go | 11 | ||||
| -rw-r--r-- | plugin/prober/probe53/probe53.go | 2 | ||||
| -rw-r--r-- | plugin/prober/probe53/setup.go | 1 | ||||
| -rw-r--r-- | plugin/prober/qname/qname.go | 2 | ||||
| -rw-r--r-- | plugin/prober/qname/setup.go | 1 | ||||
| -rw-r--r-- | plugin_gen.go | 7 |
18 files changed, 176 insertions, 215 deletions
@@ -1,16 +1,20 @@ -.:53 { - v64dns n64.top { - v4ns ns4-1 8.217.120.200 - v6ns ns6-1 240b:4001:21b:d301:951b:8de:3cd7:c0e5 - chain v4-1 v6-1 - ip-embed - chain-mlen 4 - analyze neo4j http://localhost:7447 neo4j hdk19990815 - } -} +#.:53 { +# v64dns n64.top { +# v4ns ns4-1 8.217.120.200 +# v6ns ns6-1 240b:4001:21b:d301:951b:8de:3cd7:c0e5 +# chain v4-1 v6-1 +# ip-embed +# chain-mlen 4 +# analyze neo4j http://localhost:7447 neo4j hdk19990815 +# } +#} + +#prober:2115 { +# qname +# probe53 +#} -prober:2115 { - qname - probe53 +.:53 { + atk comm.a.net ns.a.net 1.2.3.4 v6.b.net ns.b.net fe80::6cc1:aafd:5039:7b2b 10 }
\ No newline at end of file diff --git a/core/dnsserver/zdirectives.go b/core/dnsserver/zdirectives.go index 11b7f41..6844d1f 100644 --- a/core/dnsserver/zdirectives.go +++ b/core/dnsserver/zdirectives.go @@ -18,4 +18,5 @@ var Directives = []string{ "metadata", "v64dns", "whoami", + "atk", } diff --git a/core/plug/zplugin.go b/core/plug/zplugin.go index 14a8c93..13c77c0 100644 --- a/core/plug/zplugin.go +++ b/core/plug/zplugin.go @@ -4,11 +4,14 @@ package plugin import ( // Include all plugins. + _ "ohmydns2/plugin/atk" _ "ohmydns2/plugin/debug" _ "ohmydns2/plugin/dnstap" _ "ohmydns2/plugin/forward" _ "ohmydns2/plugin/log" _ "ohmydns2/plugin/metadata" + _ "ohmydns2/plugin/prober/probe53" + _ "ohmydns2/plugin/prober/qname" _ "ohmydns2/plugin/prometheus" _ "ohmydns2/plugin/v64dns" _ "ohmydns2/plugin/whoami" diff --git a/core/prober/pdirectives.go b/core/prober/pdirectives.go index 11edd54..98b4a5b 100644 --- a/core/prober/pdirectives.go +++ b/core/prober/pdirectives.go @@ -1,3 +1,5 @@ +// generated by plugin_gen.go; DO NOT EDIT + package prober // Directives are registered in the order they should be @@ -8,9 +10,6 @@ package prober // (after) them during a request, but they must not // care what plugin above them are doing. var Directives = []string{ - "log", - "dnstap", - "debug", - "prometheus", - "metadata", + "qname", + "probe53", } diff --git a/core/prober/prober_http.go b/core/prober/prober_http.go index 062808b..4d61902 100644 --- a/core/prober/prober_http.go +++ b/core/prober/prober_http.go @@ -59,7 +59,7 @@ func (l *loggerAdapter) Write(p []byte) (n int, err error) { type HTTPRequestKey struct{} // NewProberHTTP returns a new ohmydns prober(可用HTTP调用参数) and compiles all plugins in to it. -func NewProberHTTP(addr string, conf *PBConfig) (*ProberHTTP, error) { +func NewProberHTTP(addr string, conf *prober.PBConfig) (*ProberHTTP, error) { s, err := NewServer(addr, conf) if err != nil { return nil, err @@ -101,7 +101,7 @@ func (p *ProberHTTP) Serve(l net.Listener) error { } // ServePacket implements caddy.UDPServer interface. -func (p *ProberHTTP) ServePacket(pc net.PacketConn) error { return nil } +func (p *ProberHTTP) ServePacket(net.PacketConn) error { return nil } // Listen implements caddy.TCPServer interface. func (p *ProberHTTP) Listen() (net.Listener, error) { @@ -228,7 +228,7 @@ func (p *ProberHTTP) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // 无参数指定则停止所有探测任务 - for pid, _ := range p.proberlist.Pl { + for pid := range p.proberlist.Pl { err := p.proberlist.DeleteProberById(pid) if err != nil { return diff --git a/core/prober/prober_serve.go b/core/prober/prober_serve.go index 01d9906..a2716d6 100644 --- a/core/prober/prober_serve.go +++ b/core/prober/prober_serve.go @@ -36,16 +36,16 @@ type ProbeServer struct { server *http.Server // http服务 m sync.Mutex // protects the servers - conf *PBConfig // zones keyed by their port - httpWg sync.WaitGroup // used to wait on outstanding connections - graceTimeout time.Duration // the maximum duration of a graceful shutdown - trace trace.Trace // the trace plugin for the server - debug bool // disable recover() - stacktrace bool // enable stacktrace in recover error log - classChaos bool // allow non-INET class queries - idleTimeout time.Duration // Idle timeout for TCP - readTimeout time.Duration // Read timeout for TCP - writeTimeout time.Duration // Write timeout for TCP + conf *prober.PBConfig // zones keyed by their port + httpWg sync.WaitGroup // used to wait on outstanding connections + graceTimeout time.Duration // the maximum duration of a graceful shutdown + trace trace.Trace // the trace plugin for the server + debug bool // disable recover() + stacktrace bool // enable stacktrace in recover error log + classChaos bool // allow non-INET class queries + idleTimeout time.Duration // Idle timeout for TCP + readTimeout time.Duration // Read timeout for TCP + writeTimeout time.Duration // Write timeout for TCP proberlist *prober.ProberAndGoroutList //探测器列表 @@ -58,13 +58,8 @@ type response struct { Msg string `json:"msg"` } -// MetadataCollector is a plugin that can retrieve metadata functions from all metadata providing plugins -type ProberMetadataCollector interface { - Collect(context.Context, request.HTTPRequest) context.Context -} - // NewServer returns a new OhmyDNS2 probe server and compiles all plugins in to it. -func NewServer(addr string, conf *PBConfig) (*ProbeServer, error) { +func NewServer(addr string, conf *prober.PBConfig) (*ProbeServer, error) { s := &ProbeServer{ Addr: addr, graceTimeout: 5 * time.Second, @@ -119,12 +114,12 @@ func NewServer(addr string, conf *PBConfig) (*ProbeServer, error) { stack = conf.Plugin[i](stack) // register the *handler* also - conf.registerProber(stack) + conf.RegisterProber(stack) // If the current plugin is a MetadataCollector, bookmark it for later use. This loop traverses the plugin // list backwards, so the first MetadataCollector plugin wins. - if mdc, ok := stack.(ProberMetadataCollector); ok { - conf.metaCollector = mdc + if mdc, ok := stack.(prober.ProberMetadataCollector); ok { + conf.MetaCollector = mdc } if s.trace == nil && stack.Name() == "trace" { @@ -180,7 +175,7 @@ func (ps *ProbeServer) Serve(l net.Listener) error { // ServePacket starts the server with an existing packetconn. It blocks until the server stops. // This implements caddy.UDPServer interface. -func (ps *ProbeServer) ServePacket(p net.PacketConn) error { +func (ps *ProbeServer) ServePacket(net.PacketConn) error { return nil } @@ -283,9 +278,9 @@ func (ps *ProbeServer) ServeProbe(ctx context.Context, w http.ResponseWriter, re errorAndMetricsFunc(ps.Addr, w, "探测器缺少插件链", http.StatusNotImplemented) return errors.New("探测器缺少插件链"), "探测器缺少插件链" } - if pcf.metaCollector != nil { + if pcf.MetaCollector != nil { // Collect metadata now, so it can be used before we send a request down the plugin chain. - ctx = pcf.metaCollector.Collect(ctx, request.HTTPRequest{Req: req, W: w}) + ctx = pcf.MetaCollector.Collect(ctx, request.HTTPRequest{Req: req, W: w}) } // 生成目标,开始探测 targets, targetNum := getTarget(param[rangeParam]) @@ -329,7 +324,7 @@ func (ps *ProbeServer) ServeProbe(ctx context.Context, w http.ResponseWriter, re } // passAllFilterFuncs returns true if all filter funcs evaluate to true for the given request -func passAllFilterFuncs(ctx context.Context, filterFuncs []FilterFunc, req *request.HTTPRequest) bool { +func passAllFilterFuncs(ctx context.Context, filterFuncs []prober.FilterFunc, req *request.HTTPRequest) bool { for _, ff := range filterFuncs { if !ff(ctx, req) { return false @@ -388,11 +383,6 @@ func getTarget(s []string) (chan net.IP, int) { return ipchan, len(s) } -const ( - Paramkey = "httpparam" - Target = "targetip" -) - type ( // Key is the context key for the current server added to the context. Key struct{} diff --git a/core/prober/register.go b/core/prober/register.go index 2cd6994..f20bd02 100644 --- a/core/prober/register.go +++ b/core/prober/register.go @@ -7,6 +7,7 @@ import ( "ohmydns2/core/dnsserver" "ohmydns2/plugin" "ohmydns2/plugin/pkg/parse" + "ohmydns2/plugin/pkg/prober" "ohmydns2/plugin/pkg/transport" ) @@ -26,29 +27,29 @@ func init() { }) } -func newPBContext(i *caddy.Instance) caddy.Context { - return &probeContext{keysToConfigs: make(map[string]*PBConfig)} +func newPBContext(*caddy.Instance) caddy.Context { + return &ProbeContext{keysToConfigs: make(map[string]*prober.PBConfig)} } -type probeContext struct { - keysToConfigs map[string]*PBConfig +type ProbeContext struct { + keysToConfigs map[string]*prober.PBConfig // configs is the master list of all site configs. - configs []*PBConfig + configs []*prober.PBConfig } -func (p *probeContext) saveConfig(key string, cfg *PBConfig) { +func (p *ProbeContext) saveConfig(key string, cfg *prober.PBConfig) { p.configs = append(p.configs, cfg) p.keysToConfigs[key] = cfg } // Compile-time check to ensure dnsContext implements the caddy.Context interface -var _ caddy.Context = &probeContext{} +var _ caddy.Context = &ProbeContext{} // InspectServerBlocks make sure that everything checks out before // executing directives and otherwise prepares the directives to // be parsed and executed. -func (p *probeContext) InspectServerBlocks(sourceFile string, serverBlocks []caddyfile.ServerBlock) ([]caddyfile.ServerBlock, error) { +func (p *ProbeContext) InspectServerBlocks(_ string, serverBlocks []caddyfile.ServerBlock) ([]caddyfile.ServerBlock, error) { // Normalize and check all the zone names and check for duplicates for ib, s := range serverBlocks { Addrs := []addr{} @@ -70,13 +71,13 @@ func (p *probeContext) InspectServerBlocks(sourceFile string, serverBlocks []cad serverBlocks[ib].Keys = s.Keys // important to save back the new keys that are potentially created here. - var firstConfigInBlock *PBConfig + var firstConfigInBlock *prober.PBConfig for ik := range s.Keys { a := Addrs[ik] s.Keys[ik] = a.String() // Save the config to our master list, and key it for lookups. - cfg := &PBConfig{ + cfg := &prober.PBConfig{ ListenHosts: []string{""}, Port: a.Port, Transport: a.Transport, @@ -88,9 +89,9 @@ func (p *probeContext) InspectServerBlocks(sourceFile string, serverBlocks []cad if ik == 0 { firstConfigInBlock = cfg } - cfg.firstConfigInBlock = firstConfigInBlock + cfg.FirstConfigInBlock = firstConfigInBlock - keyConfig := keyForConfig(ib, ik) + keyConfig := prober.KeyForConfig(ib, ik) p.saveConfig(keyConfig, cfg) } } @@ -98,23 +99,23 @@ func (p *probeContext) InspectServerBlocks(sourceFile string, serverBlocks []cad } // MakeServers uses the newly-created siteConfigs to create and return a list of server instances. -func (p *probeContext) MakeServers() ([]caddy.Server, error) { +func (p *ProbeContext) MakeServers() ([]caddy.Server, error) { // Copy the Plugin, ListenHosts and Debug from first config in the block // to all other config in the same block . Doing this results in zones // sharing the same plugin instances and settings as other zones in // the same block. for _, c := range p.configs { - c.Plugin = c.firstConfigInBlock.Plugin - c.ListenHosts = c.firstConfigInBlock.ListenHosts - c.Debug = c.firstConfigInBlock.Debug - c.Stacktrace = c.firstConfigInBlock.Stacktrace + c.Plugin = c.FirstConfigInBlock.Plugin + c.ListenHosts = c.FirstConfigInBlock.ListenHosts + c.Debug = c.FirstConfigInBlock.Debug + c.Stacktrace = c.FirstConfigInBlock.Stacktrace // Fork TLSConfig for each encrypted connection - c.TLSConfig = c.firstConfigInBlock.TLSConfig.Clone() - c.ReadTimeout = c.firstConfigInBlock.ReadTimeout - c.WriteTimeout = c.firstConfigInBlock.WriteTimeout - c.IdleTimeout = c.firstConfigInBlock.IdleTimeout - c.TsigSecret = c.firstConfigInBlock.TsigSecret + c.TLSConfig = c.FirstConfigInBlock.TLSConfig.Clone() + c.ReadTimeout = c.FirstConfigInBlock.ReadTimeout + c.WriteTimeout = c.FirstConfigInBlock.WriteTimeout + c.IdleTimeout = c.FirstConfigInBlock.IdleTimeout + c.TsigSecret = c.FirstConfigInBlock.TsigSecret } // we must map (group) each config to a bind address @@ -160,80 +161,24 @@ func (p *probeContext) MakeServers() ([]caddy.Server, error) { return servers, nil } -// AddPlugin adds a plugin to a site's plugin stack. -func (pc PBConfig) AddPlugin(m plugin.Pplugin) { - pc.Plugin = append(pc.Plugin, m) -} - -// registerHandler adds a prober to a site's prober registration. -func (pc PBConfig) registerProber(p plugin.Prober) { - if pc.registry == nil { - pc.registry = make(map[string]plugin.Prober) - } - - // Just overwrite... - pc.registry[p.Name()] = p -} - -// Handler returns the plugin handler that has been added to the config under its name. -// This is useful to inspect if a certain plugin is active in this server. -// Note that this is order dependent and the order is defined in directives.go, i.e. if your plugin -// comes before the plugin you are checking; it will not be there (yet). -func (pc PBConfig) Handler(name string) plugin.Prober { - if pc.registry == nil { - return nil +// GetConfig gets the Config that corresponds to c. +// If none exist nil is returned. +func GetPBConfig(c *caddy.Controller) *prober.PBConfig { + ctx := c.Context().(*ProbeContext) + key := prober.KeyForConfig(c.ServerBlockIndex, c.ServerBlockKeyIndex) + if cfg, ok := ctx.keysToConfigs[key]; ok { + return cfg } - if h, ok := pc.registry[name]; ok { - return h - } - return nil -} - -// Handlers returns a slice of plugins that have been registered. This can be used to -// inspect and interact with registered plugins but cannot be used to remove or add plugins. -// Note that this is order dependent and the order is defined in directives.go, i.e. if your plugin -// comes before the plugin you are checking; it will not be there (yet). -func (pc PBConfig) Handlers() []plugin.Prober { - if pc.registry == nil { - return nil - } - hs := make([]plugin.Prober, 0, len(pc.registry)) - for k := range pc.registry { - hs = append(hs, pc.registry[k]) - } - return hs + // we should only get here during tests because directive + // actions typically skip the server blocks where we make + // the configs. + ctx.saveConfig(key, &prober.PBConfig{ListenHosts: []string{""}}) + return GetPBConfig(c) } -//func (p *probeContext) validateZonesAndListeningAddresses() error { -// //Validate addresses -// checker := newOverlapZone() -// for _, conf := range p.configs { -// for _, h := range conf.ListenHosts { -// // Validate the overlapping of ZoneAddr -// akey := addr{Transport: conf.Transport, Address: h, Port: conf.Port} -// var existZone, overlapZone *addr -// if len(conf.FilterFuncs) > 0 { -// // This config has filters. Check for overlap with other (unfiltered) configs. -// existZone, overlapZone = checker.check(akey) -// } else { -// // This config has no filters. Check for overlap with other (unfiltered) configs, -// // and register the zone to prevent subsequent zones from overlapping with it. -// existZone, overlapZone = checker.registerAndCheck(akey) -// } -// if existZone != nil { -// return fmt.Errorf("cannot serve %s - it is already defined", akey.String()) -// } -// if overlapZone != nil { -// return fmt.Errorf("cannot serve %s - zone overlap listener capacity with %v", akey.String(), overlapZone.String()) -// } -// } -// } -// return nil -//} - // groupConfigsByListenPort 建立监听端口和配置文件之间的映射,与服务端不同的是,一个监听地址端口只对应一个配置文件 -func groupConfigsByListenPort(configs []*PBConfig) (map[string]*PBConfig, error) { - groups := make(map[string]*PBConfig) +func groupConfigsByListenPort(configs []*prober.PBConfig) (map[string]*prober.PBConfig, error) { + groups := make(map[string]*prober.PBConfig) for _, conf := range configs { for _, h := range conf.ListenHosts { tcpaddr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort(h, conf.Port)) @@ -7,4 +7,5 @@ metadata:metadata v64dns:v64dns whoami:whoami qname:qname -probe53:probe53
\ No newline at end of file +probe53:probe53 +atk:atk
\ No newline at end of file diff --git a/plugin/atk/atk.go b/plugin/atk/atk.go index d24583a..e513606 100644 --- a/plugin/atk/atk.go +++ b/plugin/atk/atk.go @@ -19,9 +19,8 @@ type Atk struct { ip4Addr string } -func (a Atk) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) { +func (a Atk) ServeDNS(_ context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) { state := request.Request{W: w, Req: r} - msg := new(dns.Msg) msg.SetReply(r) msg.Authoritative = true @@ -54,11 +53,13 @@ func (a Atk) Name() string { func (a Atk) Response(msg *dns.Msg, iptype int) *dns.Msg { if iptype == 0 { // 放大 - rec := new(dns.NS) - rec.Hdr = dns.RR_Header{Class: dns.ClassINET, Ttl: 10, Rrtype: dns.TypeNS} - rec.Hdr.Name = msg.Question[0].Name for i := 0; i < a.magni; i++ { - rec.Ns = strings.ToLower(randstr.RandomAlphanumeric(10)) + a.zoneip6 + rec := new(dns.NS) + rec.Hdr = dns.RR_Header{Class: dns.ClassINET, Ttl: 10, Rrtype: dns.TypeNS} + rec.Hdr.Name = msg.Question[0].Name + ns := strings.ToLower(randstr.RandomAlphanumeric(10)) + "." + a.zoneip6 + "." + log.Infof("生成NS: %v", ns) + rec.Ns = ns msg.Ns = append(msg.Ns, rec) } } else { diff --git a/plugin/atk/setup.go b/plugin/atk/setup.go index 2e79801..48d963d 100644 --- a/plugin/atk/setup.go +++ b/plugin/atk/setup.go @@ -8,7 +8,7 @@ import ( "strconv" ) -func init() { plugin.Register("Atk", setup) } +func init() { plugin.Register("atk", setup) } func setup(c *caddy.Controller) error { atk := new(Atk) diff --git a/plugin/pkg/prober/prober.go b/plugin/pkg/prober/prober.go index 45571a1..a63113b 100644 --- a/plugin/pkg/prober/prober.go +++ b/plugin/pkg/prober/prober.go @@ -7,7 +7,6 @@ import ( "github.com/panjf2000/ants/v2" "math" "net" - "ohmydns2/core/prober" olog "ohmydns2/plugin/pkg/log" "sync" ) @@ -61,35 +60,6 @@ func NewProber(ctx context.Context) *Prober { return p } -//// SetArg 设定prober -//func (p *Prober) SetArg(arg map[string][]string) { -// if v, ok := arg[prange]; ok { -// p.Prange = v -// p.AllAddr = len(v) -// } else { -// // 默认全网探测 -// p.Prange = []string{defaultPrange} -// p.AllAddr = math.MaxInt32 -// } -// if v, ok := arg[ptype]; ok { -// p.Ptype = v[0] -// } else { -// // 默认v64 CNAME关联 -// p.Ptype = defaultPtype -// } -// // 是否持续探测,默认只探测一次 -// if v, ok := arg[ploop]; ok && v[0] == "1" { -// p.Loop = true -// } else { -// p.Loop = defaultPloop -// } -// p.stop = make(chan bool) -// p.ScannedAddr = 0 -// p.c = new(dns.Client) -// p.c.DialTimeout = defaultMaxDial * time.Second -// p.c.ReadTimeout = p.c.DialTimeout -//} - // Start 探测代码 func (p *Prober) Start(ctx context.Context, target chan net.IP, pool *ants.Pool) { @@ -154,22 +124,27 @@ func (p *Prober) addScanAddrNum() { // Probe 所有探测方法的封装方法 func (p *Prober) Probe(ctx context.Context, ip net.IP, wg *sync.WaitGroup) func() { msg := new(dns.Msg) - pcf := ctx.Value(Pchain).(*prober.PBConfig) + pcf := ctx.Value(Pchain).(*PBConfig) return func() { // 将目标IP传入上下文 - ctx = context.WithValue(ctx, prober.Target, ip) + ctx = context.WithValue(ctx, Target, ip) _, _ = pcf.PluginChain.ProbeDNS(ctx, p.c, msg) wg.Done() } } -func (p *Prober) Probev64(ip net.IP) error { - msg := new(dns.Msg) - msg.SetQuestion(dns.Fqdn(p.makeProbe(ip)), dns.TypeTXT) - // TODO:展示响应内容 - _, _, err := p.c.Exchange(msg, ip.String()+":53") - if err != nil { - return err - } - return nil -} +//func (p *Prober) Probev64(ip net.IP) error { +// msg := new(dns.Msg) +// msg.SetQuestion(dns.Fqdn(p.makeProbe(ip)), dns.TypeTXT) +// // TODO:展示响应内容 +// _, _, err := p.c.Exchange(msg, ip.String()+":53") +// if err != nil { +// return err +// } +// return nil +//} + +const ( + Paramkey = "httpparam" + Target = "targetip" +) diff --git a/core/prober/prober_config.go b/plugin/pkg/prober/prober_config.go index 43cba37..edcb142 100644 --- a/core/prober/prober_config.go +++ b/plugin/pkg/prober/prober_config.go @@ -4,7 +4,6 @@ import ( "context" "crypto/tls" "fmt" - "github.com/coredns/caddy" "net/http" "ohmydns2/plugin" "ohmydns2/plugin/pkg/request" @@ -69,33 +68,62 @@ type PBConfig struct { // Handler's Name method. registry map[string]plugin.Prober - // firstConfigInBlock is used to reference the first config in a server block, for the + // FirstConfigInBlock is used to reference the first config in a server block, for the // purpose of sharing single instance of each plugin among all zones in a server block. - firstConfigInBlock *PBConfig + FirstConfigInBlock *PBConfig - // metaCollector references the first MetadataCollector plugin, if one exists - metaCollector ProberMetadataCollector + // MetaCollector references the first MetadataCollector plugin, if one exists + MetaCollector ProberMetadataCollector } // FilterFunc is a function that filters requests from the Config type FilterFunc func(context.Context, *request.HTTPRequest) bool -// keyForConfig builds a key for identifying the configs during setup time -func keyForConfig(blocIndex int, blocKeyIndex int) string { +// KeyForConfig builds a key for identifying the configs during setup time +func KeyForConfig(blocIndex int, blocKeyIndex int) string { return fmt.Sprintf("%d:%d", blocIndex, blocKeyIndex) } -// GetConfig gets the Config that corresponds to c. -// If none exist nil is returned. -func GetPBConfig(c *caddy.Controller) *PBConfig { - ctx := c.Context().(*probeContext) - key := keyForConfig(c.ServerBlockIndex, c.ServerBlockKeyIndex) - if cfg, ok := ctx.keysToConfigs[key]; ok { - return cfg +// AddPlugin adds a plugin to a site's plugin stack. +func (pc PBConfig) AddPlugin(m plugin.Pplugin) { + pc.Plugin = append(pc.Plugin, m) +} + +// registerHandler adds a prober to a site's prober registration. +func (pc PBConfig) RegisterProber(p plugin.Prober) { + if pc.registry == nil { + pc.registry = make(map[string]plugin.Prober) + } + + // Just overwrite... + pc.registry[p.Name()] = p +} + +// Handler returns the plugin handler that has been added to the config under its name. +// This is useful to inspect if a certain plugin is active in this server. +// Note that this is order dependent and the order is defined in directives.go, i.e. if your plugin +// comes before the plugin you are checking; it will not be there (yet). +func (pc PBConfig) Handler(name string) plugin.Prober { + if pc.registry == nil { + return nil + } + if h, ok := pc.registry[name]; ok { + return h + } + return nil +} + +// Handlers returns a slice of plugins that have been registered. This can be used to +// inspect and interact with registered plugins but cannot be used to remove or add plugins. +// Note that this is order dependent and the order is defined in directives.go, i.e. if your plugin +// comes before the plugin you are checking; it will not be there (yet). +func (pc PBConfig) Handlers() []plugin.Prober { + if pc.registry == nil { + return nil + } + hs := make([]plugin.Prober, 0, len(pc.registry)) + for k := range pc.registry { + hs = append(hs, pc.registry[k]) } - // we should only get here during tests because directive - // actions typically skip the server blocks where we make - // the configs. - ctx.saveConfig(key, &PBConfig{ListenHosts: []string{""}}) - return GetPBConfig(c) + return hs } diff --git a/plugin/pkg/prober/prober_meta.go b/plugin/pkg/prober/prober_meta.go new file mode 100644 index 0000000..162895a --- /dev/null +++ b/plugin/pkg/prober/prober_meta.go @@ -0,0 +1,11 @@ +package prober + +import ( + "context" + "ohmydns2/plugin/pkg/request" +) + +// MetadataCollector is a plugin that can retrieve metadata functions from all metadata providing plugins +type ProberMetadataCollector interface { + Collect(context.Context, request.HTTPRequest) context.Context +} diff --git a/plugin/prober/probe53/probe53.go b/plugin/prober/probe53/probe53.go index 456ff1e..b39bda2 100644 --- a/plugin/prober/probe53/probe53.go +++ b/plugin/prober/probe53/probe53.go @@ -4,7 +4,7 @@ import ( "context" "github.com/miekg/dns" "net" - "ohmydns2/core/prober" + "ohmydns2/plugin/pkg/prober" ) type Probe53 struct { diff --git a/plugin/prober/probe53/setup.go b/plugin/prober/probe53/setup.go index eea50ab..cb3fb2b 100644 --- a/plugin/prober/probe53/setup.go +++ b/plugin/prober/probe53/setup.go @@ -5,6 +5,7 @@ import ( "ohmydns2/core/prober" "ohmydns2/plugin" "ohmydns2/plugin/pkg/log" + //"ohmydns2/plugin/pkg/prober" ) func init() { diff --git a/plugin/prober/qname/qname.go b/plugin/prober/qname/qname.go index 3907e61..1776f73 100644 --- a/plugin/prober/qname/qname.go +++ b/plugin/prober/qname/qname.go @@ -6,8 +6,8 @@ import ( "github.com/miekg/dns" "github.com/pochard/commons/randstr" "net" - "ohmydns2/core/prober" "ohmydns2/plugin" + "ohmydns2/plugin/pkg/prober" "strconv" "strings" ) diff --git a/plugin/prober/qname/setup.go b/plugin/prober/qname/setup.go index ccce12e..13dbba5 100644 --- a/plugin/prober/qname/setup.go +++ b/plugin/prober/qname/setup.go @@ -5,6 +5,7 @@ import ( "ohmydns2/core/prober" "ohmydns2/plugin" olog "ohmydns2/plugin/pkg/log" + //"ohmydns2/plugin/pkg/prober" ) func init() { plugin.ProbeRegister("qname", setup) } diff --git a/plugin_gen.go b/plugin_gen.go index 0384e69..094236a 100644 --- a/plugin_gen.go +++ b/plugin_gen.go @@ -47,6 +47,7 @@ func main() { pmd = append(pmd, name) continue } else { + panic(err.Error()) mi[name] = repo } } else { @@ -117,9 +118,9 @@ func formatAndWrite(file string, data string) error { const ( pluginPath = "ohmydns2/plugin/" - proberPluginPath = "ohmydns2/plugin/prober" + proberPluginPath = "ohmydns2/plugin/prober/" pluginFile = "plugin.cfg" - pluginFSPath = "plugin/" // Where the plugins are located on the file system - proberPluginFSPath = "plugin/prober" // 探测器插件在文件系统中的位置 + pluginFSPath = "plugin/" // Where the plugins are located on the file system + proberPluginFSPath = "plugin/prober/" // 探测器插件在文件系统中的位置 header = "// generated by plugin_gen.go; DO NOT EDIT\n\n" ) |
