Documentation
¶
Overview ¶
Package geomatch matches IP addresses and domain names against routing rules, including geoip: and geosite: rules backed by geoip.dat and geosite.dat files, for access control and traffic routing. It depends only on the standard library.
Rules are compiled once into a Matcher, which is safe for concurrent use and answers a query with a binary search over merged address ranges, a hash table lookup per domain label, and a scan of any keywords and regular expressions:
geo := geomatch.NewGeoData(geomatch.GeoFiles{IP: "geoip.dat", Site: "geosite.dat"})
c := geomatch.Compiler{GeoData: geo}
m, err := c.Compile([]string{"geoip:cn", "geosite:cn", "10.0.0.0/8"})
if err != nil {
log.Print(err) // the rules that were skipped; m holds the others
}
m.Match("example.cn:443")
IP rules:
192.0.2.1, [2001:db8::1] an address
10.0.0.0/8, 2001:db8::/32 a CIDR prefix
10.*, 192.168.*.* an IPv4 address whose trailing octets are *
geoip:cn an entry of the geoip file, by code
geoip:!cn every address outside that entry
geoip:private private and special-use ranges, built in when
the file lacks them or there is no file
ext-ip:file.dat:code an entry of another geoip file
Domain rules, matched case-insensitively against the host:
full:example.com exactly example.com
domain:example.com example.com and its subdomains
*example.com the same
*.example.com the subdomains of example.com only
keyword:example, example hosts containing the text; a plain domain is a
keyword unless Compiler.PlainDomain says else
regexp:^ex.*\.com$ hosts matching the regular expression
dotless:, dotless:intra hosts without a dot, or those containing the text
geosite:google an entry of the geosite file, by code
geosite:google@cn the domains of that entry with every attribute
ext-domain:file.dat:code an entry of another geosite file
ext:file.dat:code reads an entry of either kind, telling the formats apart by their contents. Rule kinds are case-insensitive, a full-width colon is read as a colon, and lines starting with # or ; are comments. Hosts may be written as URLs. Rules but regexp: and ext ones may end in ports, as in example.com:443 or 10.0.0.0/8:22,3389, which queries with a port match; 10.0.0.1-10.0.0.50 is an address range, and *:25 every address on a port.
Compile compiles rules without geodata. A Compiler reads geodata, and can allow only some rule kinds, keep ext: rules to local files and limit the rules, for rules that untrusted users write. ParseRule and ParseRules read rules into Rule values without any geodata, to validate or normalize configuration, and CompileRules compiles them. A skipped rule's error is an ErrInvalidRule, a fault of the rule, or an ErrGeoData, a fault of the geodata at hand. Matcher.Stale tells when geodata changed, and Live compiles rules again when it does, to update geodata while running.
A Policy allows or denies addresses by an allowlist, a denylist, or both with a Priority, and Levels apply policies of several levels, such as global and per-user ones. A Router maps addresses to targets by ordered routes, the first that matches deciding, to route traffic. Their Decide and Find methods report the rule that decided.
Example ¶
package main
import (
"fmt"
"log"
"github.com/djylb/geomatch"
)
func main() {
m, err := geomatch.Compile([]string{
"10.0.0.0/8",
"192.168.*",
"domain:example.com",
"*.internal.test",
"geoip:private", // built in when no geoip.dat is configured
})
if err != nil {
log.Fatal(err)
}
for _, addr := range []string{"10.1.2.3:22", "www.example.com:443", "internal.test", "db.internal.test", "172.16.0.1", "8.8.8.8"} {
fmt.Println(addr, m.Match(addr))
}
}
Output: 10.1.2.3:22 true www.example.com:443 true internal.test false db.internal.test true 172.16.0.1 true 8.8.8.8 false
Index ¶
- Variables
- func HostOf(addr string) string
- func SplitLines(text string) []string
- type Compiler
- type Decision
- type Domain
- type DomainType
- type ExtAccess
- type GeoData
- func (g *GeoData) Check() uint64
- func (g *GeoData) Files() GeoFiles
- func (g *GeoData) Generation() uint64
- func (g *GeoData) IPCodes(file string) ([]string, error)
- func (g *GeoData) LoadIP(file, code string) (GeoIP, error)
- func (g *GeoData) LoadSite(file, code string) ([]Domain, error)
- func (g *GeoData) RefreshLives() RefreshResult
- func (g *GeoData) Reset()
- func (g *GeoData) SetFiles(files GeoFiles)
- func (g *GeoData) SiteAttrs(file, code string) ([]string, error)
- func (g *GeoData) SiteCodes(file string) ([]string, error)
- func (g *GeoData) WatchLives(ctx context.Context, interval time.Duration, report func(RefreshResult)) error
- type GeoFiles
- type GeoIP
- type GeoLimits
- type IPSet
- type KindError
- type KindSet
- type Levels
- func (l Levels) Allows(addr string) bool
- func (l Levels) AllowsAddrPort(ap netip.AddrPort) bool
- func (l Levels) AllowsDomain(host string) bool
- func (l Levels) AllowsDomainPort(host string, port uint16) bool
- func (l Levels) AllowsHostIP(host string, ip netip.Addr) bool
- func (l Levels) AllowsIP(ip netip.Addr) bool
- func (l Levels) AllowsNetAddr(a net.Addr) bool
- func (l Levels) Decide(addr string) Decision
- func (l Levels) DecideAddrPort(ap netip.AddrPort) Decision
- func (l Levels) DecideDomain(host string) Decision
- func (l Levels) DecideDomainPort(host string, port uint16) Decision
- func (l Levels) DecideHostIP(host string, ip netip.Addr) Decision
- func (l Levels) DecideIP(ip netip.Addr) Decision
- func (l Levels) DecideNetAddr(a net.Addr) Decision
- func (l Levels) HasDomainRules() bool
- func (l Levels) HasIPRules() bool
- func (l Levels) HasPortRules() bool
- type Limits
- type Live
- func (l *Live) Err() error
- func (l *Live) Matcher() *Matcher
- func (l *Live) Refresh() (bool, error)
- func (l *Live) RefreshErr() error
- func (l *Live) Rules() []string
- func (l *Live) SetTag(v any)
- func (l *Live) Tag() any
- func (l *Live) Update(rules []string) error
- func (l *Live) UpdateRules(rules []Rule) error
- func (l *Live) Watch(ctx context.Context, interval time.Duration, ...) error
- type Matcher
- func (m *Matcher) Find(addr string) (RuleView, bool)
- func (m *Matcher) FindAddrPort(ap netip.AddrPort) (RuleView, bool)
- func (m *Matcher) FindDomain(host string) (RuleView, bool)
- func (m *Matcher) FindDomainPort(host string, port uint16) (RuleView, bool)
- func (m *Matcher) FindHostIP(host string, ip netip.Addr) (RuleView, bool)
- func (m *Matcher) FindIP(ip netip.Addr) (RuleView, bool)
- func (m *Matcher) FindNetAddr(a net.Addr) (RuleView, bool)
- func (m *Matcher) HasDomainRules() bool
- func (m *Matcher) HasIPRules() bool
- func (m *Matcher) HasPortRules() bool
- func (m *Matcher) Len() int
- func (m *Matcher) Match(addr string) bool
- func (m *Matcher) MatchAddrPort(ap netip.AddrPort) bool
- func (m *Matcher) MatchDomain(host string) bool
- func (m *Matcher) MatchDomainPort(host string, port uint16) bool
- func (m *Matcher) MatchHostIP(host string, ip netip.Addr) bool
- func (m *Matcher) MatchIP(ip netip.Addr) bool
- func (m *Matcher) MatchNetAddr(a net.Addr) bool
- func (m *Matcher) Matcher() *Matcher
- func (m *Matcher) Rules() []Rule
- func (m *Matcher) Sources() []Source
- func (m *Matcher) Stale() bool
- type MatcherSource
- type Mode
- type Policy
- func (p Policy) Allows(addr string) bool
- func (p Policy) AllowsAddrPort(ap netip.AddrPort) bool
- func (p Policy) AllowsDomain(host string) bool
- func (p Policy) AllowsDomainPort(host string, port uint16) bool
- func (p Policy) AllowsHostIP(host string, ip netip.Addr) bool
- func (p Policy) AllowsIP(ip netip.Addr) bool
- func (p Policy) AllowsNetAddr(a net.Addr) bool
- func (p Policy) Decide(addr string) Decision
- func (p Policy) DecideAddrPort(ap netip.AddrPort) Decision
- func (p Policy) DecideDomain(host string) Decision
- func (p Policy) DecideDomainPort(host string, port uint16) Decision
- func (p Policy) DecideHostIP(host string, ip netip.Addr) Decision
- func (p Policy) DecideIP(ip netip.Addr) Decision
- func (p Policy) DecideNetAddr(a net.Addr) Decision
- func (p Policy) HasDomainRules() bool
- func (p Policy) HasIPRules() bool
- func (p Policy) HasPortRules() bool
- func (p Policy) WithName(name string) Policy
- type PortRange
- type Priority
- type RefreshResult
- type Route
- type Routed
- type Router
- func (r Router[T]) Find(addr string) Routed[T]
- func (r Router[T]) FindAddrPort(ap netip.AddrPort) Routed[T]
- func (r Router[T]) FindDomain(host string) Routed[T]
- func (r Router[T]) FindDomainPort(host string, port uint16) Routed[T]
- func (r Router[T]) FindHostIP(host string, ip netip.Addr) Routed[T]
- func (r Router[T]) FindIP(ip netip.Addr) Routed[T]
- func (r Router[T]) FindNetAddr(a net.Addr) Routed[T]
- func (r Router[T]) Route(addr string) T
- func (r Router[T]) RouteAddrPort(ap netip.AddrPort) T
- func (r Router[T]) RouteDomain(host string) T
- func (r Router[T]) RouteDomainPort(host string, port uint16) T
- func (r Router[T]) RouteHostIP(host string, ip netip.Addr) T
- func (r Router[T]) RouteIP(ip netip.Addr) T
- func (r Router[T]) RouteNetAddr(a net.Addr) T
- type Rule
- type RuleError
- type RuleErrors
- type RuleKind
- type RuleView
- type Source
- type SyntaxError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidRule is the cause of a rule that cannot be compiled // anywhere: invalid syntax, or a rule that the Compiler does not allow. ErrInvalidRule = errors.New("geomatch: invalid rule") // ErrKindDisabled is the cause of a rule whose kind Compiler.Kinds // leaves out, which a *KindError details. It is an ErrInvalidRule. ErrKindDisabled = classed("rule kind not allowed", ErrInvalidRule) // ErrExtDenied is the cause of an ext: rule whose file Compiler.ExtFiles // does not allow. It is an ErrInvalidRule. ErrExtDenied = classed("geodata file not allowed", ErrInvalidRule) // ErrPortsDisabled is the cause of a rule that names ports when // Compiler.NoPorts is set. It is an ErrInvalidRule. ErrPortsDisabled = classed("ports not allowed", ErrInvalidRule) // ErrLimit identifies an exceeded rule or geodata resource budget. ErrLimit = errors.New("limit exceeded") // ErrGeoData is the cause of a valid rule whose geodata cannot be read: // no file configured, a missing or malformed file, a missing code, or // an entry of the other kind. Other geodata may compile the rule. ErrGeoData = errors.New("geomatch: geodata unavailable") // ErrNoGeoData is returned when no geodata file is configured for a // geoip: or geosite: rule. It is an ErrGeoData. ErrNoGeoData = classed("no geodata file configured", ErrGeoData) // ErrCodeNotFound is returned when a geodata file has no entry for a // code. It is an ErrGeoData. ErrCodeNotFound = classed("code not found in geodata file", ErrGeoData) )
Causes of a skipped rule, which errors.Is reports for a RuleError. Every cause is either ErrInvalidRule, a fault of the rule wherever it compiles, or ErrGeoData, a fault of the geodata at hand.
Functions ¶
func HostOf ¶
HostOf returns the host of addr, which may be a bare host or IP address, host:port, [IPv6]:port, or a URL such as https://user@host:443/path or a scheme-relative //host/path. The host is lowercased, without brackets, IPv6 zone or trailing dot, with internationalized labels in their xn-- form. It returns "" if there is no host. A backslash ends the host, as browsers read it as a slash.
Match reads a host in the legacy forms of IPv4 that system resolvers accept, such as 127.1, 2130706433 or 0x7f.0.0.1, as the IPv4 address it stands for, so that IP rules see the address a program would connect to.
func SplitLines ¶
SplitLines splits text into lines for Compile or ParseRules, keeping their positions, so that RuleError.Index+1 is the line number. Lines may end in \n, \r\n or \r, and a byte order mark at the start is dropped; Compile skips the empty lines and comments.
Types ¶
type Compiler ¶
type Compiler struct {
// GeoData reads geoip:, geosite: and ext: rules. Every Matcher compiled
// with one GeoData shares the geodata entries compiled for it. Nil reads
// no geodata: geoip:private uses the built-in ranges, ext: rules read
// only absolute file names, and other geoip: and geosite: rules fail
// with ErrNoGeoData.
GeoData *GeoData
// Limits bound the rules of one call; rules beyond them fail with
// ErrLimit.
Limits Limits
// Kinds are the rule kinds allowed; the zero KindSet allows all. Other
// rules fail with a *KindError, which is an ErrKindDisabled.
Kinds KindSet
// PlainDomain is the kind of a domain written without a kind, such as
// example.com: RuleKeyword, the zero value, matches hosts containing
// it, as rule lists usually mean it; RuleDomain matches it and its
// subdomains; and RuleFull matches it exactly. With RuleDomain or
// RuleFull, a leading dot, as in .example.com, means the subdomains
// only. Rule.UnmarshalText and the package's functions read it as
// RuleKeyword.
PlainDomain RuleKind
// ExtFiles is which files ext:, ext-ip: and ext-domain: rules may name.
// The zero value, ExtAny, allows any; other rules fail with
// ErrExtDenied. Relative names are looked up as GeoFiles.Dir tells.
ExtFiles ExtAccess
// NoPorts rejects rules that name ports, port: rules included, with
// ErrPortsDisabled, for lists that match addresses whose port means
// nothing, such as those of clients.
NoPorts bool
}
Compiler parses and compiles rules with settings: the geodata to read, the rule kinds and ext: files to allow, and limits, for example for rules that untrusted users write. The zero Compiler allows every rule kind, uses default input budgets, and reads no geodata, as the package's functions do. A Compiler may be used concurrently, and holds no state between calls.
Rules that the settings do not allow are invalid: ParseRules rejects them as Compile does, so validating configuration catches them.
Example ¶
Accept rules from users without regular expressions or files outside the geodata directory, and tell their mistakes from missing data.
package main
import (
"errors"
"fmt"
"github.com/djylb/geomatch"
)
func main() {
c := geomatch.Compiler{
Kinds: geomatch.AllKinds.Without(geomatch.RuleRegexp),
ExtFiles: geomatch.ExtLocal,
Limits: geomatch.Limits{MaxRules: 100},
}
_, err := c.Compile([]string{"domain:example.com", "regexp:^ads", "ext:/etc/geo.dat:cn", "geosite:cn"})
if errs, ok := errors.AsType[geomatch.RuleErrors](err); ok {
for _, e := range errs.Filter(geomatch.ErrInvalidRule) {
fmt.Println("invalid:", e.Rule, "-", e.Err)
}
for _, e := range errs.Filter(geomatch.ErrGeoData) {
fmt.Println("no data:", e.Rule)
}
}
}
Output: invalid: regexp:^ads - regexp rules are not allowed here (allowed: ip, geoip, full, domain, subdomain, keyword, dotless, geosite, ext, port) invalid: ext:/etc/geo.dat:cn - geodata file not allowed: /etc/geo.dat is not a local name no data: geosite:cn
func (Compiler) Compile ¶
Compile is the package's Compile with the settings of c.
Example ¶
Allow only clients from China and private networks, by geodata files.
package main
import (
"fmt"
"log"
"github.com/djylb/geomatch"
)
func main() {
geo := geomatch.NewGeoData(geomatch.GeoFiles{IP: "/etc/geodata/geoip.dat", Site: "/etc/geodata/geosite.dat"})
text := "geoip:cn\ngeoip:private\n"
m, err := geomatch.Compiler{GeoData: geo}.Compile(geomatch.SplitLines(text))
if err != nil {
log.Println(err) // rules that were skipped, for example for a missing file
}
p := geomatch.Policy{Allow: m}
fmt.Println(p.Allows("192.168.1.10:51234"))
}
Output:
func (Compiler) CompileRules ¶
CompileRules is the package's CompileRules with the settings of c.
func (Compiler) Normalize ¶
Normalize returns rules as ParseRules reads them, in their canonical spelling and without duplicates, in order, for example to save configuration as it will be compiled. Empty rules and comments are dropped, and invalid rules, which the error lists as ParseRules does.
type Decision ¶
type Decision struct {
Allowed bool
// Matched reports whether a rule decided; Rule is that rule, of the
// allowlist if Allowed and of the denylist otherwise.
Matched bool
Rule RuleView
// Level is the index of the policy that decided among Levels, or -1 if
// none did. It is 0 for a single Policy.
Level int
// Name is the Name of the policy that decided, or "".
Name string
}
Decision is the answer of a Policy or Levels for an address, with the rule that decided.
type Domain ¶
type Domain struct {
Type DomainType
// Value is lowercase, except for regular expressions, which match
// regardless of case. The names of DomainRoot and DomainFull entries are
// in the form that hosts match in: without a trailing dot, and with
// internationalized labels in their xn-- form. Keywords also encode internationalized
// labels and preserve leading and trailing dots.
Value string
// Attrs are the lowercase attribute keys, such as "cn" or "ads", that
// geosite:code@attr rules select by.
Attrs []string
}
Domain is a geosite entry.
type DomainType ¶
type DomainType uint8
DomainType is the kind of a geosite entry.
const ( DomainKeyword DomainType = 0 // the value is a substring of the host DomainRegexp DomainType = 1 // the value is a regular expression DomainRoot DomainType = 2 // the host is the value or a subdomain of it DomainFull DomainType = 3 // the host is exactly the value )
Geosite entry kinds.
type ExtAccess ¶
type ExtAccess uint8
ExtAccess is which files ext:, ext-ip: and ext-domain: rules may name.
const ( // ExtAny allows any file. ExtAny ExtAccess = iota // ExtLocal allows relative names that stay within the directory they // are looked up in, as GeoFiles.Dir tells: no absolute path, volume name // or .. element. Without such a directory it allows none. ExtLocal // ExtNone allows no ext: rules, so that only the files of GeoData are // read. ExtNone )
Ext file access.
type GeoData ¶
type GeoData struct {
// contains filtered or unexported fields
}
GeoData reads geoip.dat and geosite.dat files, protobuf GeoIPList and GeoSiteList messages, for the rules of a Compiler. Opening a file indexes its entries by code, so a lookup reads only the entry it needs, and a file that changes on disk, or is replaced, is indexed again on the next lookup. A change is seen in the file's size, modification time or identity, so a file system without modification times, such as an embed.FS, is taken not to change in place with the same size.
The entries compiled for rules are kept while a Matcher uses them, so that every Matcher compiled with the same GeoData shares them: many policies using geosite:cn hold it once, and entries that no Matcher uses any more go. Use one GeoData for the program, made by NewGeoData; SetFiles changes its files while it runs. The methods are safe for concurrent use. The zero GeoData has no files.
func NewGeoData ¶
NewGeoData returns a GeoData that reads files.
func (*GeoData) Check ¶
Check checks currently tracked file versions and recent failed opens for changes and returns the generation. MaxFiles bounds the indexed files tracked. Eviction advances the generation and ends tracking of that file until it is indexed again.
func (*GeoData) Generation ¶
Generation returns a number that grows whenever g sees its files change: SetFiles, index eviction, a changed or accessible file, and changes that Check finds. RefreshLives uses it to refresh only the Lives whose files may have changed.
func (*GeoData) IPCodes ¶
IPCodes returns the codes of the geoip file named file as an ext-ip: rule names it, or of the IP file when file is empty, sorted and upper-case.
func (*GeoData) LoadIP ¶
LoadIP reads the entry for code, case-insensitive, of the geoip file named file as an ext-ip: rule names it, so relative to Dir as GeoFiles tells, or of the IP file when file is empty. The code PRIVATE falls back to the built-in private and special-use ranges when the file lacks it or is malformed. Access denials and resource limit errors are reported.
func (*GeoData) LoadSite ¶
LoadSite reads the entries for code, case-insensitive, of the geosite file named file as an ext-domain: rule names it, or of the site file when file is empty.
func (*GeoData) RefreshLives ¶
func (g *GeoData) RefreshLives() RefreshResult
RefreshLives checks the currently tracked files, as Check does, and refreshes, as Live.Refresh does, every Live compiled with g whose files may have changed since it last compiled or checked them, so that a program with many Lives, such as one per user, checks each file once rather than once per Live: a Live compares its files with the versions that Check saw, and looks again only at those that changed, did not exist or could not be read. Live.Tag tells the Lives of the result apart.
func (*GeoData) Reset ¶
func (g *GeoData) Reset()
Reset drops the indexes and compiled entries; Matchers already compiled keep theirs, and RefreshLives checks every Live again.
func (*GeoData) SetFiles ¶
SetFiles replaces the files of g, such as when configuration changes while the program runs. Matchers already compiled keep their entries, and report Stale, so that a Live compiles its rules again from the new files.
func (*GeoData) SiteAttrs ¶
SiteAttrs returns the attributes that the domains of the entry for code of a geosite file have, as LoadSite reads it, sorted and lowercase: those that geosite:code@attr rules can name, such as for a form that offers them.
func (*GeoData) SiteCodes ¶
SiteCodes returns the codes of the geosite file named file as an ext-domain: rule names it, or of the site file when file is empty, sorted and upper-case: the categories that geosite: rules can name.
Example ¶
package main
import (
"fmt"
"log"
"github.com/djylb/geomatch"
)
func main() {
geo := geomatch.NewGeoData(geomatch.GeoFiles{Site: "/etc/geodata/geosite.dat"})
codes, err := geo.SiteCodes("")
if err != nil {
log.Println(err)
return
}
fmt.Println(len(codes), "geosite categories")
}
Output:
func (*GeoData) WatchLives ¶
func (g *GeoData) WatchLives(ctx context.Context, interval time.Duration, report func(RefreshResult)) error
WatchLives calls RefreshLives every interval until ctx is done, and report, if not nil, with each result that Changed. It returns ctx.Err(), or an error at once if interval is not positive. Run it in its own goroutine, once for the GeoData of the program:
go geo.WatchLives(ctx, time.Minute, func(r geomatch.RefreshResult) {
for _, err := range r.Errors {
log.Printf("geodata: %v (kept the rules of %d lists)", err, len(r.Failed))
}
})
type GeoFiles ¶
type GeoFiles struct {
// IP is the geoip.dat file of geoip: rules.
IP string
// Site is the geosite.dat file of geosite: rules.
Site string
// Dir is where relative file names of ext: rules are looked up. Empty
// means the directory of the default file of the rule's kind, or of the
// other default file, or with FS the root of FS. Without any of them,
// relative names cannot be read, never relative to the working
// directory.
Dir string
// FS, if set, holds the files, such as an embed.FS or an fs.FS of data
// fetched at run time; the paths above are then slash-separated paths
// in it. Nil reads the operating system's files.
// A custom FS must enforce the directory boundary of ExtLocal, including symlinks.
FS fs.FS
// Limits bounds geodata reads and cache size. Zero fields use the defaults.
Limits GeoLimits
}
GeoFiles are the files of a GeoData.
type GeoIP ¶
type GeoIP struct {
Prefixes []netip.Prefix
// Inverse marks an entry that matches the addresses outside Prefixes
// (reverse_match in the file).
Inverse bool
}
GeoIP is a geoip entry.
type GeoLimits ¶
type GeoLimits struct {
// MaxFileBytes defaults to 512 MiB. MaxRecordBytes defaults to 64 MiB.
MaxFileBytes, MaxRecordBytes int64
// MaxIndexBytes budgets code bytes and per-entry overhead, default 16 MiB.
MaxIndexBytes int64
// MaxFiles bounds cached indexes and open files per compile, default 256.
MaxFiles int
}
GeoLimits bounds resources used for untrusted files. Positive fields override defaults.
type IPSet ¶
type IPSet struct {
// contains filtered or unexported fields
}
IPSet is a set of IP prefixes that changes while it is used, such as the addresses that clients register at run time, and a MatcherSource of them for a Policy, Levels or Router, which see each change at their next query. The rules of its Matcher are the prefixes, as Find and Decide report them.
Updates rebuild the immutable matcher once per batch. The zero IPSet is ready for use.
func (*IPSet) Add ¶
Add adds prefixes, and single addresses as prefixes of their full length, such as netip.PrefixFrom(addr, addr.BitLen()). Prefixes are masked, and IPv4-mapped ones are IPv4; invalid ones are ignored.
func (*IPSet) Matcher ¶
Matcher returns a Matcher of the prefixes as they are now, built again on each change and taken without locking; it implements MatcherSource. A nil IPSet has none.
type KindError ¶
KindError is the cause of a rule whose kind Compiler.Kinds leaves out, with the kind read and the kinds allowed, for messages such as "only IP rules are allowed here". It is an ErrKindDisabled and an ErrInvalidRule.
type KindSet ¶
type KindSet uint32
KindSet is a set of rule kinds. The zero KindSet stands for every kind.
const ( // NoKinds disables every rule kind. NoKinds KindSet = 1 << 31 // AllKinds holds every kind. AllKinds KindSet = 1<<(RulePort+1) - 1<<RuleIP // IPKinds holds the kinds that match IP addresses only, for rules about // addresses such as those of clients. IPKinds KindSet = 1<<RuleIP | 1<<RuleGeoIP // DomainKinds holds the kinds that match domain names only. DomainKinds KindSet = 1<<(RuleGeoSite+1) - 1<<RuleFull // GeoKinds holds the kinds that read geodata files: AllKinds &^ GeoKinds // leaves the rules that need no geodata. GeoKinds KindSet = 1<<RuleGeoIP | 1<<RuleGeoSite | 1<<RuleExt )
Sets of rule kinds. RuleExt, whose kind depends on its file, and RulePort, which matches both, are in neither IPKinds nor DomainKinds.
func (KindSet) String ¶
String lists the kinds of s, as "ip, geoip"; the zero KindSet lists every kind.
type Levels ¶
type Levels struct {
Policies []Policy
// FirstMatch lets the first level whose rules match decide, rather than
// requiring every level to allow.
FirstMatch bool
// DenyUnmatched, with FirstMatch, denies addresses that no level's rules
// match, which are otherwise allowed.
DenyUnmatched bool
}
Levels apply policies of several levels, such as global, per-user, per-client and per-resource ones, in one of two ways:
- By default every level must allow an address, so that a level can only narrow what those before it allow: an administrator's global denylist binds every user.
- With FirstMatch the first level whose rules match an address decides, overriding the levels after it either way. List the levels most authoritative first, or most specific first for settings that override general ones. Addresses that no level's rules match are allowed, or denied with DenyUnmatched.
With FirstMatch a level is a list of decisions rather than a policy of its own: an Allow list there allows what it matches and leaves the rest to the next levels, rather than denying it. A user level of Allow: full:a.com then still lets the other levels, or DenyUnmatched, decide b.com; to deny what a level's allowlist leaves out, use the default, every level must allow, or give the level a Deny list of what it denies.
A level that is not set, the zero Policy, never matches and allows everything, so it changes nothing either way. Decision.Level tells which level decided, and Decision.Name its Policy.Name. The methods take the forms of those of Policy, and read the address once. Levels are safe for concurrent use while their fields are not changed.
Example ¶
Every level must allow: a global denylist binds the levels after it.
package main
import (
"fmt"
"github.com/djylb/geomatch"
)
func main() {
levels := geomatch.Levels{Policies: []geomatch.Policy{
{Deny: geomatch.MustCompile([]string{"geoip:private"})}, // global
{Allow: geomatch.MustCompile([]string{"1.1.1.0/24", "8.8.8.0/24"})}, // user
{Deny: geomatch.MustCompile([]string{"8.8.8.8"})}, // tunnel
{}, // a level that is not set changes nothing
}}
for _, addr := range []string{"1.1.1.1:443", "10.0.0.1", "8.8.8.8", "9.9.9.9"} {
fmt.Println(addr, levels.Decide(addr))
}
}
Output: 1.1.1.1:443 allowed by 1.1.1.0/24 (level 1) 10.0.0.1 denied by geoip:private 8.8.8.8 denied by 8.8.8.8 (level 2) 9.9.9.9 denied: no rule matched (level 1)
Example (FirstMatch) ¶
The first level whose rules match decides: here the global level overrides a user's, and the user's a tunnel's.
package main
import (
"fmt"
"github.com/djylb/geomatch"
)
func main() {
levels := geomatch.Levels{FirstMatch: true, Policies: []geomatch.Policy{
{Allow: geomatch.MustCompile([]string{"10.1.0.0/16"})}, // global
{Deny: geomatch.MustCompile([]string{"10.0.0.0/8"})}, // user
{Allow: geomatch.MustCompile([]string{"10.2.0.0/16"})}, // tunnel
}}
for _, addr := range []string{"10.1.1.1", "10.2.1.1", "192.0.2.1"} {
fmt.Println(addr, levels.Decide(addr))
}
}
Output: 10.1.1.1 allowed by 10.1.0.0/16 10.2.1.1 denied by 10.0.0.0/8 (level 1) 192.0.2.1 allowed: no rule matched
func (Levels) AllowsAddrPort ¶
AllowsAddrPort reports whether the levels allow the address and port of ap.
func (Levels) AllowsDomain ¶
AllowsDomain reports whether the levels allow host.
func (Levels) AllowsDomainPort ¶
AllowsDomainPort reports whether the levels allow a domain name and port.
func (Levels) AllowsHostIP ¶
AllowsHostIP reports whether the levels allow a domain name and its IP address.
func (Levels) AllowsNetAddr ¶
AllowsNetAddr reports whether the levels allow a.
func (Levels) Decide ¶
Decide is Allows that also reports the level and rule that decided: the level that denied, or the first whose rule matched; Level is -1 if no level's rule matched and none denied.
func (Levels) DecideAddrPort ¶
DecideAddrPort is Decide for an address and port.
func (Levels) DecideDomain ¶
DecideDomain is Decide for a domain name.
func (Levels) DecideDomainPort ¶
DecideDomainPort is Decide for a domain name and port.
func (Levels) DecideHostIP ¶
DecideHostIP is Decide for a domain name and its IP address.
func (Levels) DecideNetAddr ¶
DecideNetAddr is Decide for a net.Addr.
func (Levels) HasDomainRules ¶
HasDomainRules reports whether a level has rules that match domain names.
func (Levels) HasIPRules ¶
HasIPRules reports whether a level has rules that match IP addresses, so that a caller with a host name resolves it, for AllowsHostIP, only when an address could change the answer.
func (Levels) HasPortRules ¶
HasPortRules reports whether a level has rules with ports.
type Limits ¶
type Limits struct {
// MaxLines bounds input entries including comments and invalid rules. The first excess index is reported once. Zero uses one million lines.
MaxLines int
// MaxRules counts successful parses in ParseRules and successful rules
// in Compile and CompileRules. Zero allows any count within MaxLines.
MaxRules int
// MaxRuleLen bounds the length of a rule in bytes, without surrounding
// spaces. Zero uses 64 KiB.
MaxRuleLen int
// MaxRegexps bounds the number of regexp: rules, which cost every
// query some time.
MaxRegexps int
}
Limits bound the input and accepted rules of one ParseRules or Compile call.
type Live ¶
type Live struct {
// contains filtered or unexported fields
}
Live holds rules and the Matcher compiled from them, and compiles them again when their geodata files change or the rules do, so that a running program picks up new geodata. Queries take the current Matcher without locking; a new one replaces it whole, so no query sees a mix of old and new data. Live starts no goroutines: call Refresh when the files may have changed, or run Watch; a program with many Lives on one GeoData refreshes them all with GeoData.RefreshLives or GeoData.WatchLives.
Replace a geodata file by renaming a new file over it rather than by writing it in place, so that a compile never reads a file half written and the change is seen even if size and time stay the same.
The methods are safe for concurrent use.
Example ¶
Keep rules up to date with geodata files that are updated while the program runs.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/djylb/geomatch"
)
func main() {
geo := geomatch.NewGeoData(geomatch.GeoFiles{IP: "/etc/geodata/geoip.dat", Site: "/etc/geodata/geosite.dat"})
live, err := geomatch.NewLive(geomatch.Compiler{GeoData: geo}, []string{"geoip:cn", "geosite:cn"})
if err != nil {
log.Println(err) // rules that were skipped
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
_ = live.Watch(ctx, time.Minute, func(replaced bool, err error) {
log.Printf("geodata reloaded: %v, %v", replaced, err)
})
}()
// The policy follows the Live as geodata changes.
p := geomatch.Policy{Allow: live}
fmt.Println(p.Allows("www.qq.com:443"))
}
Output:
func NewLive ¶
NewLive compiles rules with c, as c.Compile does: the error lists the rules skipped, and the Live holds the others.
func NewLiveRules ¶
NewLiveRules is NewLive for parsed or built rules, which it compiles as c.CompileRules does.
func (*Live) Err ¶
Err returns the error of the compile that gave the current Matcher: the rules it skipped, or nil.
func (*Live) Matcher ¶
Matcher returns the current Matcher, for queries, such as live.Matcher().Match(addr). Take it once for queries that belong together. A Policy or Router given the Live follows it by itself:
p := geomatch.Policy{Allow: live}
func (*Live) Refresh ¶
Refresh compiles the rules again if a geodata file that the current Matcher was compiled from has changed, and reports whether it replaced the Matcher. It checks the files' metadata only, so it is cheap to call often.
A rule that compiled before but whose new geodata cannot be read, such as a file removed or replaced by a broken one, keeps the current Matcher: Refresh returns false and the error of the new compile, and compiles again once the files change again. Otherwise the error is that of the new compile, as Err returns it, or nil.
func (*Live) RefreshErr ¶
RefreshErr returns the error of the last Refresh, or GeoData.RefreshLives, that kept the current Matcher because new geodata broke a rule that compiled before, such as a file replaced by a broken one; or nil once the Matcher follows the files again. Err, of the current Matcher, does not report it, so health checks should look at both.
func (*Live) Rules ¶
Rules returns the rules that the Live compiles; rules given as Rule values in the spelling of Rule.String. Text is trimmed. The slice ends at MaxLines, and entries exceeding the size budget have empty spellings.
func (*Live) SetTag ¶
SetTag attaches v to the Live, such as the user or the list it holds the rules of, for reports of GeoData.RefreshLives; a map from Lives to such values would keep the Lives that the program dropped.
func (*Live) Update ¶
Update replaces the rules and compiles them, replacing the Matcher even if rules are skipped, which the error lists as Compile's does.
Update compiles every rule, also to change one: the Matcher merges all address rules into one sorted set and all domain rules into one table, so a change rebuilds them whole either way, and geoip: and geosite: entries are compiled once and shared through the GeoData. Parsing the rule text again is a small share of a compile, which takes time and memory linear in the number of rules, and a cache of parsed rules would hold a second copy of every rule to save it.
func (*Live) UpdateRules ¶
UpdateRules is Update for parsed or built rules, which it compiles as Compiler.CompileRules does.
func (*Live) Watch ¶
func (l *Live) Watch(ctx context.Context, interval time.Duration, report func(replaced bool, err error)) error
Watch calls Refresh every interval until ctx is done, and report, if not nil, with the result of each Refresh that replaced the Matcher or failed. It returns ctx.Err(), or an error at once if interval is not positive. Run it in its own goroutine:
go live.Watch(ctx, time.Minute, func(replaced bool, err error) {
if err != nil {
log.Printf("geodata: replaced=%v: %v", replaced, err)
}
})
type Matcher ¶
type Matcher struct {
// contains filtered or unexported fields
}
Matcher matches IP addresses and domain names against compiled rules. It is safe for concurrent use. A nil *Matcher matches nothing.
Each query comes in seven forms, by what the caller holds: a string that HostOf reads, such as host:port or a URL; a netip.Addr; a domain name that is never read as an IP address, alone or with a port; a net.Addr, such as a connection's RemoteAddr; a domain name with the IP address it resolved to; and a netip.AddrPort. The Match methods report whether a rule matches, and the Find methods which rule, at more cost.
Rules with ports (Rule.Ports) match a query by its port as well: the port of a host:port or [IPv6]:port string, of a URL, explicit or the default of http, https, ws, wss and ftp, of a *net.TCPAddr or *net.UDPAddr, or of a netip.AddrPort, which MatchAddrPort and FindAddrPort take, or given with a domain name to MatchDomainPort and FindDomainPort. A query without a port, such as a bare host, a netip.Addr or a *net.IPAddr, matches no rule with ports, and one whose port cannot be read, such as host:https, matches them by address alone, so that a denylist fails closed; a Policy's Allow list reads both the other way round. So do not use a bare Matcher with port rules as an allowlist: a port that cannot be read would pass it. Use Policy{Allow: m}. Rules without ports match every query as before.
func Compile ¶
Compile compiles rules into a Matcher without geodata; Compiler.Compile reads geodata. The package documentation lists the syntax.
Empty rules and comments, starting with # or ;, are skipped. Invalid rules, and rules whose geodata cannot be read, are skipped too: the returned error is then a RuleErrors, and the Matcher holds the other rules. Since Index is the position in rules, Compile(SplitLines(text)) reports errors by line, Index+1 being the line number.
func CompileRules ¶
CompileRules is Compile for parsed rules, such as those ParseRules returns or a program builds. Each rule is checked and normalized as its String form would be.
func MustCompile ¶
MustCompile is Compile that panics if a rule is skipped, for rules fixed in a program.
func (*Matcher) Find ¶
Find returns the first rule, in the order given to Compile, that addr matches as Match reads it, for example to log why a Policy allowed or denied it, or to choose a route by rule. It uses the explanation index built during compilation.
Example ¶
package main
import (
"fmt"
"github.com/djylb/geomatch"
)
func main() {
m := geomatch.MustCompile([]string{"keyword:ads", "domain:example.com", "10.0.0.0/8"})
for _, addr := range []string{"ads.example.com", "www.example.com", "10.1.2.3:443", "8.8.8.8"} {
rule, ok := m.Find(addr)
fmt.Println(addr, rule, ok)
}
}
Output: ads.example.com keyword:ads true www.example.com domain:example.com true 10.1.2.3:443 10.0.0.0/8 true 8.8.8.8 false
func (*Matcher) FindAddrPort ¶
FindAddrPort is Find for an address and port, as MatchAddrPort reads them.
func (*Matcher) FindDomain ¶
FindDomain is Find for a domain name, as MatchDomain reads it.
func (*Matcher) FindDomainPort ¶
FindDomainPort is Find for a domain name and port, as MatchDomainPort reads them.
func (*Matcher) FindHostIP ¶
FindHostIP is Find for a domain name and its IP address, as MatchHostIP reads them.
func (*Matcher) FindNetAddr ¶
FindNetAddr is Find for a net.Addr, as MatchNetAddr reads it.
func (*Matcher) HasDomainRules ¶
HasDomainRules reports whether m holds rules that match domain names.
func (*Matcher) HasIPRules ¶
HasIPRules reports whether m holds rules that match IP addresses, for callers that only see one kind of address.
func (*Matcher) HasPortRules ¶
HasPortRules reports whether m holds rules with ports, so that a caller passes the port of an address, such as with MatchAddrPort, only when it could change the answer.
func (*Matcher) Match ¶
Match reports whether addr matches: its host, as HostOf extracts it, is matched as an IP address or else as a domain name.
func (*Matcher) MatchAddrPort ¶
MatchAddrPort reports whether the address and port of ap match, as MatchIP matches the address and rules with ports also the port.
func (*Matcher) MatchDomain ¶
MatchDomain reports whether host, a domain name or host:port, matches a domain rule. IP addresses, also in the legacy forms of IPv4, match no domain rule. Internationalized names are matched in their xn-- form.
func (*Matcher) MatchDomainPort ¶
MatchDomainPort reports whether host, a domain name, and port match: as MatchDomain reads host, by port as well for the rules with ports, as MatchAddrPort does for an address.
func (*Matcher) MatchHostIP ¶
MatchHostIP reports whether a domain name or the IP address it resolved to matches: host as MatchDomain reads it, or ip as MatchIP does. Either may be empty, as "" or the zero netip.Addr. Unlike checking the two in turn, an allowlist then allows a host by either its name or its address.
func (*Matcher) MatchIP ¶
MatchIP reports whether ip matches an IP rule. IPv4-mapped IPv6 addresses match as IPv4.
func (*Matcher) MatchNetAddr ¶
MatchNetAddr reports whether a, such as a connection's RemoteAddr, matches: *net.TCPAddr, *net.UDPAddr and *net.IPAddr are matched by IP address without formatting them, Unix socket addresses match no rule, and other addresses are matched as Match matches their String.
func (*Matcher) Sources ¶
Sources returns the geodata files that m was compiled from, in the order its rules first read them, for example to log which version of the data is in use.
type MatcherSource ¶
type MatcherSource interface {
Matcher() *Matcher
}
MatcherSource provides a Matcher to a Policy or a Router: a *Matcher provides itself, and a *Live its current Matcher. Use a pointer for a custom dynamic source shared between roles so its identity is comparable.
type Mode ¶
type Mode uint8
Mode is how one list of rules is used, as configuration that has a mode and rules describes it; Mode.Policy makes the Policy.
const ( // ModeOff allows everything. ModeOff Mode = iota // ModeAllowlist allows only what matches; with no rules it allows // nothing. ModeAllowlist // ModeDenylist allows everything except what matches. ModeDenylist )
Modes. Their values are stable, for configuration files.
func ParseMode ¶
ParseMode parses a mode from its name, its number, or a common synonym: off, none, disabled or 0; allowlist, allow, whitelist or 1; denylist, deny, blocklist, blacklist or 2. Case, surrounding spaces, and - or _ in names are ignored, as in allow-list.
func (Mode) MarshalText ¶
MarshalText returns the name of m, for configuration files.
func (Mode) Policy ¶
func (m Mode) Policy(rules MatcherSource) Policy
Policy returns the Policy of mode m over rules: an allowlist, a denylist, or for ModeOff one that allows everything. Unknown modes deny everything. An allowlist with nil rules allows nothing.
func (*Mode) UnmarshalJSON ¶
UnmarshalJSON sets m from a JSON string that ParseMode reads or from a JSON number 0 to 2. A JSON null leaves m unchanged.
func (*Mode) UnmarshalText ¶
UnmarshalText sets m from what ParseMode reads. Like time.Time, Mode has a pointer receiver here only, so that values print and marshal by name.
type Policy ¶
type Policy struct {
// Name, if set, names the policy, as "global" or "user 7", in its
// Decisions and their text, such as for the levels of Levels.
Name string
// Allow and Deny are the lists: a *Matcher, or a *Live, whose Matcher
// the policy then follows as geodata changes.
Allow MatcherSource
Deny MatcherSource
// Priority decides for an address that both lists match.
Priority Priority
}
Policy allows or denies addresses by an allowlist, a denylist, or both:
- With only Allow, it allows the addresses that Allow matches.
- With only Deny, it allows all but those that Deny matches.
- With both, an address that one matches gets that list's answer, and Priority decides for one that both match. Addresses that neither matches are denied with DenyFirst, as an allowlist with exceptions denies them, and allowed with AllowFirst, as a denylist with exceptions allows them.
- With neither, as the zero Policy, it allows everything.
A list is not set only if it is nil or a nil *Matcher: leave the list of configuration that has none nil. Any Matcher is a set list, also one of no rules, such as one whose rules were all skipped or rejected for missing geodata or kinds a Compiler does not allow: an allowlist then allows nothing rather than everything, so that failing rules fail closed. Mode.Policy makes the Policy of configuration that has a mode and rules, where an allowlist without rules allows nothing too.
Like those of Matcher, its methods come in seven forms, by the kind of address. Allows reports whether an address is allowed, and Decide also which rule decided, at more cost when a rule matches.
Rules with ports (Rule.Ports) decide only addresses whose port the query has: for an address without a port, such as a bare host or a netip.Addr, a rule with ports of Deny does not match, and one of Allow matches by its address, so that a program that checks addresses only is not denied by ports; Decide then reports that rule of Allow. An address whose port cannot be read, such as host:https, matches the rules with ports of Deny by address and none of Allow, so that it is denied either way.
Example ¶
Deny a range but for an exception: with both lists, Priority decides for addresses on both.
package main
import (
"fmt"
"github.com/djylb/geomatch"
)
func main() {
p := geomatch.Policy{
Deny: geomatch.MustCompile([]string{"192.0.2.0/24"}),
Allow: geomatch.MustCompile([]string{"192.0.2.7"}),
Priority: geomatch.AllowFirst, // the exception wins; addresses on neither list are allowed
}
for _, addr := range []string{"192.0.2.7", "192.0.2.8", "198.51.100.1"} {
fmt.Println(addr, p.Decide(addr))
}
}
Output: 192.0.2.7 allowed by 192.0.2.7 192.0.2.8 denied by 192.0.2.0/24 198.51.100.1 allowed: no rule matched
func (Policy) Allows ¶
Allows reports whether the policy allows addr, as Matcher.Match reads it. An address that cannot be read matches no rule.
func (Policy) AllowsAddrPort ¶
AllowsAddrPort reports whether the policy allows the address and port of ap, as Matcher.MatchAddrPort reads them.
func (Policy) AllowsDomain ¶
AllowsDomain reports whether the policy allows host, as Matcher.MatchDomain reads it.
func (Policy) AllowsDomainPort ¶
AllowsDomainPort reports whether the policy allows a domain name and port, as Matcher.MatchDomainPort reads them.
func (Policy) AllowsHostIP ¶
AllowsHostIP reports whether the policy allows a domain name and the IP address it resolved to, as Matcher.MatchHostIP reads them: a list matches them if it matches either.
func (Policy) AllowsNetAddr ¶
AllowsNetAddr reports whether the policy allows a, such as a connection's RemoteAddr, as Matcher.MatchNetAddr reads it.
func (Policy) DecideAddrPort ¶
DecideAddrPort is Decide for an address and port.
func (Policy) DecideDomain ¶
DecideDomain is Decide for a domain name.
func (Policy) DecideDomainPort ¶
DecideDomainPort is Decide for a domain name and port.
func (Policy) DecideHostIP ¶
DecideHostIP is Decide for a domain name and its IP address.
func (Policy) DecideNetAddr ¶
DecideNetAddr is Decide for a net.Addr.
Example ¶
package main
import (
"fmt"
"net"
"github.com/djylb/geomatch"
)
func main() {
mode, _ := geomatch.ParseMode("blacklist")
p := mode.Policy(geomatch.MustCompile([]string{"192.0.2.0/24"}))
remote := &net.TCPAddr{IP: net.ParseIP("192.0.2.7"), Port: 51234}
fmt.Println(mode, p.DecideNetAddr(remote))
}
Output: denylist denied by 192.0.2.0/24
func (Policy) HasDomainRules ¶
HasDomainRules reports whether a list of p has rules that match domain names.
func (Policy) HasIPRules ¶
HasIPRules reports whether a list of p has rules that match IP addresses, so that a caller with a host name resolves it, for AllowsHostIP, only when an address could change the answer.
func (Policy) HasPortRules ¶
HasPortRules reports whether a list of p has rules with ports, so that a caller passes the port of an address only when it could change the answer.
type PortRange ¶
type PortRange struct {
First, Last uint16
}
PortRange is a range of ports, First to Last inclusive, of Rule.Ports.
type Priority ¶
type Priority uint8
Priority decides for an address on both lists of a Policy. Unknown priorities count as DenyFirst.
Example ¶
Choose which list wins for addresses on both.
package main
import (
"fmt"
"github.com/djylb/geomatch"
)
func main() {
allow := geomatch.MustCompile([]string{"10.0.0.0/8"})
deny := geomatch.MustCompile([]string{"10.9.0.0/16", "192.0.2.0/24"})
for _, priority := range []geomatch.Priority{geomatch.DenyFirst, geomatch.AllowFirst} {
p := geomatch.Policy{Allow: allow, Deny: deny, Priority: priority}
fmt.Println(priority, p.Allows("10.1.1.1"), p.Allows("10.9.1.1"), p.Allows("192.0.2.1"), p.Allows("198.51.100.1"))
}
}
Output: deny-first true false false false allow-first true true false true
const ( // DenyFirst lets the denylist win: an address is allowed only if it is // on the allowlist and not on the denylist. Addresses on neither list // are denied, as an allowlist does. DenyFirst Priority = iota // AllowFirst lets the allowlist win: an address is denied only if it is // on the denylist and not on the allowlist. Addresses on neither list // are allowed, as a denylist does; otherwise the denylist would change // nothing. AllowFirst )
Priorities. Their values are stable, for configuration files.
func ParsePriority ¶
ParsePriority parses a priority from its name or the list that wins: deny-first, deny, denylist, blacklist or 0; allow-first, allow, allowlist, whitelist or 1. Case, surrounding spaces, and - or _ in names are ignored; an empty string is DenyFirst.
func (Priority) MarshalText ¶
MarshalText returns the name of p, for configuration files.
func (*Priority) UnmarshalJSON ¶
UnmarshalJSON sets p from a JSON string that ParsePriority reads or from a JSON number 0 or 1. A JSON null leaves p unchanged.
func (*Priority) UnmarshalText ¶
UnmarshalText sets p from what ParsePriority reads.
type RefreshResult ¶
type RefreshResult struct {
// Replaced are the Lives whose Matcher was compiled again.
Replaced []*Live
// Failed are the Lives that kept their Matcher because new geodata broke
// rules that compiled before, as their RefreshErr reports.
Failed []*Live
// Errors are the distinct geodata errors of the Failed Lives, one per
// file and cause however many Lives it broke, for a log.
Errors []error
}
RefreshResult reports a round of GeoData.RefreshLives.
func (RefreshResult) Changed ¶
func (r RefreshResult) Changed() bool
Changed reports whether the round replaced or kept a Matcher.
type Route ¶
type Route[T any] struct { Matcher MatcherSource Target T }
Route is a route of a Router: addresses that Matcher matches go to Target. Matcher may be a *Matcher, or a *Live that the route then follows as geodata changes; nil matches nothing.
type Routed ¶
type Routed[T any] struct { Target T // Matched reports whether a route matched; otherwise Target is the // Router's Default. Matched bool // Index is the position of the route in Routes, or -1 for the default. Index int // Rule is the first rule of the route that matched. Rule RuleView }
Routed is the answer of a Router for an address, with the route and rule that decided.
type Router ¶
Router maps addresses to targets by ordered routes: the first route whose rules match decides, and Default applies when none does, as in routing traffic to "direct", "proxy" or "block":
r := geomatch.Router[string]{
Routes: []geomatch.Route[string]{
{Matcher: ads, Target: "block"},
{Matcher: china, Target: "direct"},
},
Default: "proxy",
}
Like those of Matcher, its methods come in seven forms, by the kind of address. Route returns the target, and Find also which route and rule decided, at more cost when a route matches. Rules with ports match as Matcher matches them: a query without a port takes no route by a rule with ports. A Router is safe for concurrent use while its fields are not changed.
Example ¶
Route traffic by ordered rules; the first route that matches decides.
package main
import (
"fmt"
"github.com/djylb/geomatch"
)
func main() {
r := geomatch.Router[string]{
Routes: []geomatch.Route[string]{
{Matcher: geomatch.MustCompile([]string{"keyword:ads"}), Target: "block"},
{Matcher: geomatch.MustCompile([]string{"domain:example.cn", "10.0.0.0/8"}), Target: "direct"},
},
Default: "proxy",
}
for _, addr := range []string{"ads.example.cn", "www.example.cn:443", "10.1.2.3", "example.com"} {
fmt.Println(addr, r.Find(addr))
}
}
Output: ads.example.cn block by keyword:ads (route 0) www.example.cn:443 direct by domain:example.cn (route 1) 10.1.2.3 direct by 10.0.0.0/8 (route 1) example.com proxy by default
func (Router[T]) Find ¶
Find is Route that also reports the route and rule that decided, for logging.
func (Router[T]) FindAddrPort ¶
FindAddrPort is Find for an address and port.
func (Router[T]) FindDomain ¶
FindDomain is Find for a domain name.
func (Router[T]) FindDomainPort ¶
FindDomainPort is Find for a domain name and port.
func (Router[T]) FindHostIP ¶
FindHostIP is Find for a domain name and its IP address.
func (Router[T]) FindNetAddr ¶
FindNetAddr is Find for a net.Addr.
func (Router[T]) RouteAddrPort ¶
RouteAddrPort returns the target of an address and port, as Matcher.MatchAddrPort reads them.
func (Router[T]) RouteDomain ¶
RouteDomain returns the target of host, as Matcher.MatchDomain reads it.
func (Router[T]) RouteDomainPort ¶
RouteDomainPort returns the target of a domain name and port, as Matcher.MatchDomainPort reads them.
func (Router[T]) RouteHostIP ¶
RouteHostIP returns the target of a domain name and the IP address it resolved to, as Matcher.MatchHostIP reads them.
func (Router[T]) RouteNetAddr ¶
RouteNetAddr returns the target of a, as Matcher.MatchNetAddr reads it.
type Rule ¶
type Rule struct {
// Prefix is the address range of RuleIP, or with Last the first address
// of its range.
Prefix netip.Prefix
// Last, if valid, is the last address of a RuleIP that holds the
// addresses from Prefix, a single address, to Last, as in
// 10.0.0.1-10.0.0.50. A range that is a CIDR prefix is written as the
// prefix instead.
Last netip.Addr
// Value is the domain, text or regular expression of the domain kinds.
Value string
// File is the geodata file of RuleExt, and of RuleGeoIP and RuleGeoSite
// when they name one (ext-ip: and ext-domain:); empty means the default
// file of GeoData.
File string
// Code is the upper-case code of the geo kinds.
Code string
// Attrs are the attributes that every domain of a geosite entry must
// have, lowercase and sorted.
Attrs []string
// Ports, if any, are the ports the rule matches, sorted and merged;
// none means every port, but for RulePort. Regexp: and ext rules have
// none. See Matcher for how queries without a port match them.
Ports []PortRange
// Kind is what the rule matches and how its value reads.
Kind RuleKind
// Negate inverts a geoip entry: the rule matches the addresses outside it.
Negate bool
// Plain marks a domain written without a kind, such as example.com,
// whose kind the PlainDomain of the Compiler that compiles it decides:
// String writes it without a kind again, so that a rule decoded from
// configuration, as JSON, keeps its meaning for any Compiler. ParseRule
// reads it as RuleKeyword, as rule lists mean it.
Plain bool
}
Rule is a parsed rule. ParseRule returns rules in a normal form: lowercase domains, codes with upper-case ASCII letters, sorted attributes and masked prefixes, so that String gives a rule one spelling however it was written.
A Rule reads and writes itself as text, so that configuration can hold []Rule, checked as it is decoded, for CompileRules.
func ParseRule ¶
ParseRule parses one rule, in the syntax the package documentation lists, without reading any geodata. It fails for an empty rule or a comment.
Example ¶
package main
import (
"fmt"
"github.com/djylb/geomatch"
)
func main() {
for _, s := range []string{"*Example.COM", "GEOSITE:Google@CN", "10.1.2.3/8", "foo*bar"} {
r, err := geomatch.ParseRule(s)
if err != nil {
fmt.Println(err)
continue
}
fmt.Println(r)
}
}
Output: domain:example.com geosite:google@cn 10.0.0.0/8 geomatch: rule "foo*bar": a wildcard must be a leading * of a domain or trailing octets of an IPv4 address
func ParseRules ¶
ParseRules parses rules as Compile reads them, without reading any geodata, for example to check configuration: empty rules and comments are skipped, and so are invalid rules, which the returned error lists as a RuleErrors. Rules that parse may still fail to compile if their geodata cannot be read.
Example ¶
Check configuration lines without reading geodata, reporting errors by line number.
package main
import (
"errors"
"fmt"
"github.com/djylb/geomatch"
)
func main() {
text := "# rules\ndomain:example.com\nfull:\nfoo*bar\n"
_, err := geomatch.ParseRules(geomatch.SplitLines(text))
if errs, ok := errors.AsType[geomatch.RuleErrors](err); ok {
for _, e := range errs {
fmt.Printf("line %d: %v\n", e.Index+1, e.Err)
}
}
}
Output: line 3: empty value line 4: a wildcard must be a leading * of a domain or trailing octets of an IPv4 address
func (Rule) IsIP ¶
IsIP reports whether the rule matches IP addresses. RuleExt depends on its file, so it counts as both kinds.
func (Rule) MarshalText ¶
MarshalText validates the fields, syntax and length with the default compiler and returns the canonical spelling.
func (Rule) String ¶
String returns the rule in the syntax ParseRule reads, or "" for the zero Rule.
func (*Rule) UnmarshalText ¶
UnmarshalText sets r to the rule that ParseRule reads from text.
type RuleError ¶
type RuleError struct {
// Index is the position of the rule in the slice given to ParseRules or
// Compile.
Index int
// Rule is the trimmed spelling, or empty when it exceeds MaxRuleLen.
Rule string
Err error
}
RuleError reports a rule that was rejected or skipped, and why. errors.Is tells ErrInvalidRule from ErrGeoData.
type RuleErrors ¶
type RuleErrors []*RuleError
RuleErrors is the error of ParseRules, Compile and CompileRules: one *RuleError for each rule they skipped, in order. Get it with errors.As to go through the rules, or test for one cause with errors.Is.
func (RuleErrors) Error ¶
func (e RuleErrors) Error() string
func (RuleErrors) Filter ¶
func (e RuleErrors) Filter(target error) RuleErrors
Filter returns the errors whose cause is target, such as ErrInvalidRule to report configuration errors or ErrGeoData to report missing data.
func (RuleErrors) Unwrap ¶
func (e RuleErrors) Unwrap() []error
Unwrap returns the errors for errors.Is and errors.As.
type RuleKind ¶
type RuleKind uint8
RuleKind is the kind of a Rule.
const ( // RuleIP matches the addresses of Prefix: an address, a CIDR prefix or // an IPv4 wildcard such as 10.*. RuleIP RuleKind = iota + 1 // RuleGeoIP matches the addresses of a geoip entry, or those outside it // with Negate. RuleGeoIP // RuleFull matches the host Value exactly. RuleFull // RuleDomain matches Value and its subdomains. RuleDomain // RuleSubdomain matches the subdomains of Value only. RuleSubdomain // RuleKeyword matches hosts containing Value. RuleKeyword // RuleRegexp matches hosts matching the regular expression Value, // regardless of case. RuleRegexp // RuleDotless matches hosts without a dot that contain Value, or all of // them when Value is empty. RuleDotless // RuleGeoSite matches the domains of a geosite entry. RuleGeoSite // RuleExt matches an entry of File, which may be a geoip or a geosite // file. RuleExt // RulePort matches every IP address and domain name on Ports, as in // *:25 or *:8000-9000; without Ports it means every port. RulePort )
Rule kinds. The zero RuleKind is not a rule.
type RuleView ¶
type RuleView struct {
// contains filtered or unexported fields
}
RuleView refers to an immutable compiled rule. A retained view keeps the compiled probes and their geodata alive. Use Copy or String to keep one rule independently.
func (RuleView) MarshalText ¶
MarshalText writes the same text as the compiled rule.
func (*RuleView) UnmarshalText ¶
UnmarshalText replaces the view with an independently parsed rule. Other views of the same matched rule keep their original value.
type Source ¶
type Source struct {
File string
// Missing reports that compilation could obtain no file metadata,
// for example because the file was absent or access was denied.
Missing bool
Size int64
ModTime time.Time
}
Source is a geodata file that a Matcher was compiled from.
type SyntaxError ¶
SyntaxError is the cause of a rule whose ports or address range cannot be read, and where: Offset is the byte offset in the rule as RuleError.Rule quotes it.
func (*SyntaxError) Error ¶
func (e *SyntaxError) Error() string