geomatch

package module
v0.0.0-...-336d323 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 28 Imported by: 1 module, 0 packages

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

README

geomatch

Match 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 in Go.

  • No dependencies beyond the standard library, and builds on every Go port.
  • Rules compile into a Matcher safe for concurrent use; queries of lowercase hosts do not allocate.
  • Geodata files are indexed on first use, so a rule reads only its own entry of a file of tens of megabytes, and a Live picks up files updated while the program runs.
  • Matchers compiled with one GeoData share each compiled geoip: and geosite: entry, so many policies that use geosite:cn hold it once.
  • Geodata can come from the file system or any fs.FS, such as an embed.FS.

Install

go get github.com/djylb/geomatch

Usage

var compiler = geomatch.Compiler{
	GeoData: geomatch.NewGeoData(geomatch.GeoFiles{IP: "geoip.dat", Site: "geosite.dat"}),
}

func newMatcher() *geomatch.Matcher {
	m, err := compiler.Compile([]string{
		"geoip:cn",
		"geosite:cn",
		"10.0.0.0/8",
		"domain:example.com",
	})
	if err != nil {
		// Invalid rules, or rules whose geodata could not be read, were
		// skipped; m holds the others. err is a geomatch.RuleErrors with
		// the index of each.
		log.Print(err)
	}
	return m
}

func route(m *geomatch.Matcher, target string) string {
	if m.Match(target) { // "www.example.com:443", "10.1.2.3", "https://host/path"
		return "direct"
	}
	return "proxy"
}

geomatch.Compile compiles rules without geodata, and MustCompile panics on an invalid rule, for rules fixed in a program.

Rules are written as common routing rule lists write them, so such lists work as they are. Mind that a domain written without a kind, such as example.com, is a keyword: it matches every host that contains the text, notexample.com and example.com.evil.net too. Write domain:example.com for the domain and its subdomains, or set Compiler.PlainDomain for rules that your users write; see Restricting rules.

Every query comes in these forms, by what the caller holds. Levels have the methods of Policy, and a Router has Route… and, with the rule, Find… in the same forms:

Input Matcher Matcher, with the rule Policy Policy, with the rule
address, host:port or URL (string) Match Find Allows Decide
netip.Addr MatchIP FindIP AllowsIP DecideIP
domain name, never read as an IP MatchDomain FindDomain AllowsDomain DecideDomain
domain name and port MatchDomainPort FindDomainPort AllowsDomainPort DecideDomainPort
net.Addr, such as a RemoteAddr MatchNetAddr FindNetAddr AllowsNetAddr DecideNetAddr
domain name and the IP it resolved to MatchHostIP FindHostIP AllowsHostIP DecideHostIP
address and port (netip.AddrPort) MatchAddrPort FindAddrPort AllowsAddrPort DecideAddrPort

net.Addr values are matched without formatting them. MatchHostIP matches if either the name or the address does, so that an allowlist of geoip: rules allows a host by where it resolves. HostOf extracts the host that Match uses from an address or URL, ending it at a backslash as browsers do. Names are matched in their ASCII form, as TLS, DNS and geosite files hold them: internationalized names in queries, in the domains of full:, domain: and * rules, and in the full and domain entries of geosite files, are converted to their xn-- form, with full-width dots read as dots; keyword:, regexp: and dotless: rules are text that must be ASCII. A host in the legacy forms of IPv4 that system resolvers accept, such as 127.1, 2130706433 or 0x7f.0.0.1, is matched as the address it stands for, so that a denylist of addresses cannot be passed by spelling one differently.

Allowing and denying

A Policy allows or denies addresses by an allowlist, a denylist, or both. Decide also reports the rule that decided, and a Decision prints as denied by geoip:cn, for logs:

denylist := geomatch.Policy{Deny: blocked}
allowlist := geomatch.Policy{Allow: trusted}
denyWins := geomatch.Policy{Allow: trusted, Deny: blocked}
allowWins := geomatch.Policy{Allow: exceptions, Deny: blocked, Priority: geomatch.AllowFirst}

if d := denylist.DecideNetAddr(conn.RemoteAddr()); !d.Allowed {
	log.Printf("%v %v", conn.RemoteAddr(), d) // "192.0.2.7:51234 denied by geoip:cn"
}
Lists only on Allow only on Deny on both on neither
Allow allowed denied
Deny denied allowed
both, DenyFirst (zero) allowed denied denied denied
both, AllowFirst allowed denied allowed allowed
neither (zero Policy) allowed

Allow and Deny take any MatcherSource: a *Matcher, a *Live, an *IPSet, a set of prefixes that changes while it is used, such as the addresses that clients register at run time, or a type of your own whose Matcher method returns the current rules.

HasIPRules and HasDomainRules, on a Policy, Levels or Matcher, tell whether rules of that kind exist, so that a program resolves a host's address for AllowsHostIP only when an IP rule could change the answer:

ip := netip.Addr{}
if levels.HasIPRules() {
	ip = resolve(host)
}
allowed := levels.AllowsHostIP(host, ip)

So a denylist with exceptions is Deny and Allow with AllowFirst, and an allowlist with exceptions Allow and Deny with DenyFirst. Only a nil list is not set: leave the list nil when configuration has none. Any Matcher is a set list, also one whose rules were all skipped, rejected or filtered out by ParseRules, so that an allowlist of rules that fail allows nothing. Either list may be a Live, which the policy follows as geodata changes.

Mode (ModeOff, ModeAllowlist, ModeDenylist) and Priority (DenyFirst, AllowFirst) read and write their names in configuration files, as Rule does its text. Mode also reads whitelist, blacklist, allow, deny and the numbers 0 to 2, and Mode.Policy makes the policy of a mode and its rules, an allowlist without rules allowing nothing:

type ACL struct {
	Mode  geomatch.Mode   `json:"mode"`  // "allowlist", "denylist" or "off"
	Rules []geomatch.Rule `json:"rules"` // ["geoip:cn", "domain:example.com"]
}

func (acl ACL) Policy() (geomatch.Policy, error) {
	m, err := compiler.CompileRules(acl.Rules)
	// Even with err, m holds the rules that compiled, and an allowlist of
	// none allows nothing.
	return acl.Mode.Policy(m), err
}

type Lists struct {
	Allow    []geomatch.Rule   `json:"allow"`
	Deny     []geomatch.Rule   `json:"deny"`
	Priority geomatch.Priority `json:"priority"` // "deny-first" (default) or "allow-first"
}

func (l Lists) Policy() (geomatch.Policy, error) {
	p := geomatch.Policy{Priority: l.Priority}
	var errs []error
	if l.Allow != nil { // a list that configuration lacks stays nil
		m, err := compiler.CompileRules(l.Allow)
		p.Allow, errs = m, append(errs, err)
	}
	if l.Deny != nil {
		m, err := compiler.CompileRules(l.Deny)
		p.Deny, errs = m, append(errs, err)
	}
	return p, errors.Join(errs...)
}
Levels

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, so 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 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. A level's Allow then allows what it matches and leaves the rest to the next levels rather than denying it: a user level of Allow: full:a.com does not deny b.com.

A level that is not set, the zero Policy, changes nothing either way. Decision.Level tells which level decided, and a Policy with a Name names itself in its Decision and the Decision's text:

user := geomatch.Policy{Name: "user 7", Deny: userRules}
levels := geomatch.Levels{Policies: []geomatch.Policy{global, user, client, tunnel}}
if d := levels.DecideNetAddr(conn.RemoteAddr()); !d.Allowed {
	log.Printf("%v %v", conn.RemoteAddr(), d) // "192.0.2.7:51234 denied by geoip:cn (user 7)"
}
Routing

A Router maps addresses to targets by ordered routes: the first route that matches decides, and Default applies when none does. It routes traffic, and with bool targets it is an access list in any order of priority:

router := geomatch.Router[string]{
	Routes: []geomatch.Route[string]{
		{Matcher: ads, Target: "block"},
		{Matcher: china, Target: "direct"},
	},
	Default: "proxy",
}
outbound := router.Route(addr)
log.Print(router.Find(addr)) // "direct by geosite:cn (route 1)"

In short:

Need Use
an allowlist, a denylist, or both with exceptions Policy
levels that must all allow, later ones only narrowing Levels
levels where the first whose rules match decides Levels with FirstMatch
a target per address, or rules in any priority order Router[T]
any of these following geodata as it changes Live in place of a Matcher
Geodata
//go:embed geo/geoip.dat geo/geosite.dat
var geoFiles embed.FS

var geo = geomatch.NewGeoData(geomatch.GeoFiles{FS: geoFiles, IP: "geo/geoip.dat", Site: "geo/geosite.dat"})

Use one GeoData for the program, so that its compiled entries are shared. Without FS, the files are read from the operating system. A file updated in place or replaced is indexed again the next time a rule needs it; compile the rules again to pick up new data, which reuses everything compiled from files that did not change. Matcher.Stale reports when a file it was compiled from changed or appeared, and Matcher.Sources lists those files. GeoData.SetFiles changes the files while the program runs, such as when configuration is reloaded; Matchers of the old files then report Stale. GeoData.Check looks at every file it has read and returns a generation that grows when one changed. GeoData.LoadIP, LoadSite, IPCodes, SiteCodes and SiteAttrs read the files directly, for example to list the categories and attributes a geosite file offers; they name files as ext: rules do.

Updating geodata while running

A Live holds rules and their Matcher, and compiles them again when their geodata files change, so that a running program picks up new data without restarting. Queries take the current Matcher without locking, and a new one replaces it whole, so no query mixes old and new data:

live, err := geomatch.NewLive(compiler, rules)
if err != nil {
	log.Print(err) // rules skipped; live holds the others
}
go live.Watch(ctx, time.Minute, func(replaced bool, err error) {
	log.Printf("geodata reloaded: %v, %v", replaced, err)
})

live.Matcher().Match(addr)

// A Policy over a Live follows its Matcher by itself.
p := geomatch.ModeAllowlist.Policy(live)
p.Allows(addr)

Refresh checks once, for programs that know when files change, and Update replaces the rules; NewLiveRules and UpdateRules take parsed rules. Update compiles the whole list, also to change one rule, since the rules are merged into shared sets that a change rebuilds anyway; its cost is linear in the number of rules. A program with many Lives on one GeoData, such as one for each user, refreshes them all with one goroutine, which looks at each file once per round and recompiles only the Lives whose files changed; a Live the program drops leaves it by itself. Live.SetTag names a Live for the report, and each broken file is reported once however many Lives it broke:

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

If new geodata breaks a rule that compiled before, such as a file removed or replaced by a broken one, Live keeps the previous Matcher and reports the error, which Live.RefreshErr returns for health checks, and tries again once the files change. Replace a file by renaming a new one over it rather than writing it in place, so that no compile reads it half written.

Ports

Migration. Rules that name a port now match that port only, and rules with ports decide only queries that carry a port:

  • A deny rule 10.0.0.5:22 used to deny the whole host; it now denies port 22 only. Write 10.0.0.5 to deny every port.
  • Queries without a port, such as AllowsIP or a bare host, are not restricted by rules with ports: a deny rule with ports does not match them.
  • Allow: *:443, like any allow rule with ports, admits queries without a port. Pass the port, as with AllowsAddrPort, wherever it is known.
  • A bare Matcher matches a query whose port cannot be read, such as example.com:+22, by address, so that a denylist fails closed; used as an allowlist it would then admit it. Use a Policy with Allow, which reads such ports the other way round.

Rules may name ports, address ranges, and ports of every address:

m, err := compiler.Compile([]string{
	"example.com:443",
	"10.0.0.0/8:22,3389",
	"[2001:db8::/32]:1000-2000",
	"10.0.0.1-10.0.0.50",
	"geoip:cn:25",
	"*:8000-9000",
})
m.Match("example.com:443")                                 // true
m.MatchAddrPort(netip.MustParseAddrPort("10.1.2.3:3389")) // true

A rule without ports matches every port. A query is matched by its port when it has one: the port of a host:port or [IPv6]:port string, of a URL, written or the default of http, https, ws, wss and ftp, of a *net.TCPAddr or *net.UDPAddr, of a netip.AddrPort, and the port given with a domain name to MatchDomainPort and its kin. Queries without a port, such as a bare host, a netip.Addr or a *net.IPAddr, leave the port open, so that a program that checks addresses only is not denied by port rules; a port that cannot be read, such as host:https, is denied either way:

Rule with ports in query port in the rule's other port no port port that cannot be read
Matcher, Router, Deny matches no match no match matches
Allow of a Policy matches no match matches no match

So a policy with Allow: example.com:443 allows example.com, and reports that rule from Decide, and one with Allow: *:443 allows every address without a port; pass the port wherever it is known. HasPortRules, on a Matcher, Policy or Levels, tells whether a port could change an answer.

The syntax adds to that of the rules table:

rule      = kind ":" value [":" ports]     ; full, domain, keyword, dotless
          | "geoip:" ["!"] code [":" ports]
          | "geosite:" code *("@" attr) [":" ports]
          | "regexp:" pattern               ; no ports: a pattern may hold ":"
          | ext-kind ":" file ":" code      ; ext, ext-ip, ext-domain: no ports
          | "*:" ports                      ; every address on the ports
          | "[" ip "]" [":" ports]          ; brackets for IPv6 with ports, allowed for IPv4
          | ip-no-brackets                  ; IPv6 without brackets never has ports
          | host [":" ports]                ; IPv4, CIDR, IPv4 range, 10.*, domain, *domain, *.domain, .domain
          | url                             ; scheme://host[:port]/…, //host[:port]/…
ip        = address | cidr | address "-" address   ; one family, first ≤ last
ports     = item *("," item)
item      = port | port "-" port            ; decimal 0–65535

Ports are sorted and merged, 0-65535 is no port condition but in *:, a range that is one CIDR prefix is written as it, and String writes IPv6 with ports in brackets. A URL rule takes its written port only. keyword: and dotless: text cannot hold :, and a domain named as a rule kind, such as geoip, needs a kind when it has ports. Errors in ports and ranges are a *SyntaxError, whose Offset is the byte in the rule where it failed: geomatch: rule "10.0.0.0/8:22,99999": at byte 14: port 99999 out of range. Rule.Ports, Rule.Last, the end of an address range, and RulePort write and read themselves as text like other rules.

Earlier versions read the port of a rule such as example.com:443 or [2001:db8::1]:443 and dropped it, and rejected address ranges; such rules now match their port only.

Restricting rules

A Compiler can restrict the rules it accepts, for example for rules that untrusted users write. The zero Compiler accepts every rule, without limits. Common settings:

// Rules about client addresses: domain rules could never match them, and
// a client's source port says nothing about the client.
clients := geomatch.Compiler{GeoData: geo, Kinds: geomatch.IPKinds, NoPorts: true}

// Rules that users write: no regular expressions, geodata files only from
// the geodata directory, and bounded in number and size.
users := geomatch.Compiler{
	GeoData:  geo,
	Kinds:    geomatch.AllKinds.Without(geomatch.RuleRegexp),
	ExtFiles: geomatch.ExtLocal, // ext: names within the geodata directory; ExtNone disables ext:
	Limits:   geomatch.Limits{MaxRules: 1000, MaxRuleLen: 256},
}

// A program without geodata, which should refuse geo rules up front rather
// than skip them when compiling.
plain := geomatch.Compiler{Kinds: geomatch.AllKinds &^ geomatch.GeoKinds}

IPKinds, DomainKinds, GeoKinds and AllKinds are sets of the kinds in the rules table; KindsOf builds others. Restricted rules are invalid: ParseRules rejects them as Compile does, so validating configuration catches them. Every skipped rule's error is an ErrInvalidRule, a fault of the rule, or an ErrGeoData, a fault of the geodata at hand, such as a missing file; RuleErrors.Filter picks either. A rule of a kind left out fails with a *KindError, which holds the kind read and the kinds allowed, and says so: keyword rules are not allowed here (allowed: ip, geoip).

A domain written without a kind, such as example.com, matches hosts that contain it, as rule lists usually mean it. That is the widest reading, so PlainDomain can make it domain: (the domain and its subdomains) or full: instead. Note that *example.com is domain:example.com, the domain and its subdomains, not any name that ends in the text:

users.PlainDomain = geomatch.RuleDomain // "example.com" is domain:example.com

A misspelt kind, such as ful:example.com, and an IP range that does not parse, such as 1.1.1.1-1.1.1.300, are invalid rather than read as keywords.

Parsed rules

ParseRule and ParseRules, or those of a Compiler, check rules without reading any geodata, for example to validate configuration input, and return them in a normal form whose String is the canonical spelling. Normalize returns them as canonical text without duplicates, to save. CompileRules compiles parsed or built rules, and Matcher.Rules returns the rules of a Matcher. ParseRule fails with a *RuleError, and ParseRules with a RuleErrors of them:

// validate checks rules that users write against the restrictions of
// users, the Compiler that will compile them.
func validate(text string) error {
	_, err := users.ParseRules(geomatch.SplitLines(text))
	var errs geomatch.RuleErrors
	if errors.As(err, &errs) {
		e := errs[0]
		return fmt.Errorf("line %d: %q: %w", e.Index+1, e.Rule, e.Err)
	}
	return nil
}

SplitLines splits rule text, such as a file, into lines whose positions it keeps, whether they end in \n, \r\n or \r, and drops a byte order mark; rules are trimmed of spaces and a byte order mark however they were split.

A Rule reads and writes itself as text, so configuration can hold []geomatch.Rule, checked as it is decoded, in JSON, YAML or any format that uses encoding.TextUnmarshaler; the Compiler's restrictions and PlainDomain apply when CompileRules compiles them, as a domain written without a kind stays so (Rule.Plain).

Rules

Rule Matches Kind
192.0.2.1, 2001:db8::1 the address RuleIP
10.0.0.0/8, 2001:db8::/32 the CIDR prefix RuleIP
10.0.0.1-10.0.0.50 the addresses from the first to the last RuleIP
10.*, 192.168.*.* IPv4 addresses with those leading octets RuleIP
geoip:cn an entry of the geoip file, GeoFiles.IP RuleGeoIP
geoip:!cn every address outside that entry RuleGeoIP
geoip:private private and special-use ranges, built in if the file lacks it RuleGeoIP
ext-ip:file.dat:code an entry of another geoip file RuleGeoIP
full:example.com exactly example.com RuleFull
domain:example.com, *example.com example.com and its subdomains RuleDomain
*.example.com the subdomains of example.com only RuleSubdomain
keyword:ads, ads hosts containing the text (see PlainDomain) RuleKeyword
regexp:^ads?\. hosts matching the regular expression, case-insensitively RuleRegexp
dotless:, dotless:intra hosts without a dot, or those of them containing the text RuleDotless
geosite:google an entry of the geosite file, GeoFiles.Site RuleGeoSite
geosite:google@cn@ads its domains having every listed attribute RuleGeoSite
ext-domain:file.dat:code an entry of another geosite file RuleGeoSite
ext:file.dat:code an entry of either kind, told apart by the file's contents RuleExt
*:25, *:8000-9000 every address on the ports RulePort

Rules but regexp: and ext ones may end in ports, as in example.com:443, 10.0.0.0/8:22,3389 or [2001:db8::/32]:1000-2000; see Ports.

Rule kinds and codes are case-insensitive, a full-width colon (:) is read as a colon, hosts may be written as URLs, and lines starting with # or ; are comments. Relative file names of ext rules are looked up in GeoFiles.Dir, or next to the default file of the rule's kind, or the other one, or in the root of FS, never in the working directory. IP rules never match domain names and domain rules never match IP addresses; IPv4-mapped IPv6 addresses match as IPv4. regexp: matches regardless of case, dotless: takes plain text without a dot, and an attribute after @ must not be empty. Domains of full:, domain: and * rules may be written as internationalized names, which are converted to their xn-- form; rules that no host could match are invalid rather than silently dead: non-ASCII keyword:, regexp: and dotless: text, and domains that are IPv4 addresses in a legacy form, such as 127.1, which queries read as addresses.

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

Examples

Constants

This section is empty.

Variables

View Source
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 is the cause of a rule beyond Compiler.Limits. It is an
	// ErrInvalidRule.
	ErrLimit = classed("rule limit exceeded", ErrInvalidRule)

	// 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

func HostOf(addr string) string

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

func SplitLines(text string) []string

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, without limits, 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

func (c Compiler) Compile(rules []string) (*Matcher, error)

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"))
}

func (Compiler) CompileRules

func (c Compiler) CompileRules(rules []Rule) (*Matcher, error)

CompileRules is the package's CompileRules with the settings of c.

func (Compiler) Normalize

func (c Compiler) Normalize(rules []string) ([]string, error)

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.

func (Compiler) ParseRule

func (c Compiler) ParseRule(s string) (Rule, error)

ParseRule is the package's ParseRule with the settings of c. Its error is a *RuleError, as ParseRules gives for each rule, with Index 0.

func (Compiler) ParseRules

func (c Compiler) ParseRules(rules []string) ([]Rule, error)

ParseRules is the package's ParseRules with the settings of c.

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    Rule
	// 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.

func (Decision) String

func (d Decision) String() string

String describes d for logs, as "denied by geoip:cn (user)" or "allowed: no rule matched"; it names the policy by Name, or else among Levels by number after the first.

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.
	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

func NewGeoData(files GeoFiles) *GeoData

NewGeoData returns a GeoData that reads files.

func (*GeoData) Check

func (g *GeoData) Check() uint64

Check looks at the metadata of every file that g has read, or failed to find, and returns the generation, which grows if one changed or appeared.

func (*GeoData) Files

func (g *GeoData) Files() GeoFiles

Files returns the files of g; a nil g has none.

func (*GeoData) Generation

func (g *GeoData) Generation() uint64

Generation returns a number that grows whenever g sees its files change: SetFiles, a file indexed again because it changed, and changes that Check finds. RefreshLives uses it to refresh only the Lives whose files may have changed.

func (*GeoData) IPCodes

func (g *GeoData) IPCodes(file string) ([]string, error)

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

func (g *GeoData) LoadIP(file, code string) (GeoIP, error)

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 cannot be read.

func (*GeoData) LoadSite

func (g *GeoData) LoadSite(file, code string) ([]Domain, error)

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 files that g has read, 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

func (g *GeoData) SetFiles(files GeoFiles)

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

func (g *GeoData) SiteAttrs(file, code string) ([]string, error)

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

func (g *GeoData) SiteCodes(file string) ([]string, error)

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")
}

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.
	FS fs.FS
}

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 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.

A change costs little; the next Matcher builds the set again, in time that grows as n log n with its size, once for any number of changes before it. For sets of many thousands of prefixes that change between most queries, apply changes in batches, as with one Add of many prefixes, so that queries do not build it each time. The zero IPSet is empty and ready to use, and its methods are safe for concurrent use.

func (*IPSet) Add

func (s *IPSet) Add(prefixes ...netip.Prefix)

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

func (s *IPSet) Len() int

Len returns the number of prefixes of the set.

func (*IPSet) Matcher

func (s *IPSet) Matcher() *Matcher

Matcher returns a Matcher of the prefixes as they are now, built again when they changed since the last one, and taken without locking while they did not; it implements MatcherSource. A nil IPSet has none.

func (*IPSet) Prefixes

func (s *IPSet) Prefixes() []netip.Prefix

Prefixes returns the prefixes of the set, sorted.

func (*IPSet) Remove

func (s *IPSet) Remove(prefixes ...netip.Prefix)

Remove removes prefixes as Add added them.

type KindError

type KindError struct {
	Kind    RuleKind
	Allowed KindSet
}

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.

func (*KindError) Error

func (e *KindError) Error() string

func (*KindError) Is

func (e *KindError) Is(target error) bool

Is reports whether target is ErrKindDisabled or ErrInvalidRule.

type KindSet

type KindSet uint32

KindSet is a set of rule kinds. The zero KindSet stands for every kind.

const (
	// 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 KindsOf

func KindsOf(kinds ...RuleKind) KindSet

KindsOf returns the set of kinds. With none it returns the zero KindSet, which stands for every kind.

func (KindSet) Has

func (s KindSet) Has(k RuleKind) bool

Has reports whether s holds k; the zero KindSet holds every kind.

func (KindSet) String

func (s KindSet) String() string

String lists the kinds of s, as "ip, geoip"; the zero KindSet lists every kind.

func (KindSet) Without

func (s KindSet) Without(kinds ...RuleKind) KindSet

Without returns s without kinds, as in AllKinds.Without(RuleRegexp); the zero KindSet counts as AllKinds. Remove a set with &^, as in AllKinds &^ GeoKinds. A KindSet left empty is the zero KindSet, which holds 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) Allows

func (l Levels) Allows(addr string) bool

Allows reports whether the levels allow addr, as Matcher.Match reads it.

func (Levels) AllowsAddrPort

func (l Levels) AllowsAddrPort(ap netip.AddrPort) bool

AllowsAddrPort reports whether the levels allow the address and port of ap.

func (Levels) AllowsDomain

func (l Levels) AllowsDomain(host string) bool

AllowsDomain reports whether the levels allow host.

func (Levels) AllowsDomainPort

func (l Levels) AllowsDomainPort(host string, port uint16) bool

AllowsDomainPort reports whether the levels allow a domain name and port.

func (Levels) AllowsHostIP

func (l Levels) AllowsHostIP(host string, ip netip.Addr) bool

AllowsHostIP reports whether the levels allow a domain name and its IP address.

func (Levels) AllowsIP

func (l Levels) AllowsIP(ip netip.Addr) bool

AllowsIP reports whether the levels allow ip.

func (Levels) AllowsNetAddr

func (l Levels) AllowsNetAddr(a net.Addr) bool

AllowsNetAddr reports whether the levels allow a.

func (Levels) Decide

func (l Levels) Decide(addr string) Decision

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

func (l Levels) DecideAddrPort(ap netip.AddrPort) Decision

DecideAddrPort is Decide for an address and port.

func (Levels) DecideDomain

func (l Levels) DecideDomain(host string) Decision

DecideDomain is Decide for a domain name.

func (Levels) DecideDomainPort

func (l Levels) DecideDomainPort(host string, port uint16) Decision

DecideDomainPort is Decide for a domain name and port.

func (Levels) DecideHostIP

func (l Levels) DecideHostIP(host string, ip netip.Addr) Decision

DecideHostIP is Decide for a domain name and its IP address.

func (Levels) DecideIP

func (l Levels) DecideIP(ip netip.Addr) Decision

DecideIP is Decide for an IP address.

func (Levels) DecideNetAddr

func (l Levels) DecideNetAddr(a net.Addr) Decision

DecideNetAddr is Decide for a net.Addr.

func (Levels) HasDomainRules

func (l Levels) HasDomainRules() bool

HasDomainRules reports whether a level has rules that match domain names.

func (Levels) HasIPRules

func (l Levels) HasIPRules() bool

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

func (l Levels) HasPortRules() bool

HasPortRules reports whether a level has rules with ports.

type Limits

type Limits struct {
	// MaxRules bounds the number of rules, not counting empty rules,
	// comments and rules skipped for other reasons.
	MaxRules int
	// MaxRuleLen bounds the length of a rule in bytes, without surrounding
	// spaces.
	MaxRuleLen int
	// MaxRegexps bounds the number of regexp: rules, which cost every
	// query some time.
	MaxRegexps int
}

Limits bound the rules of one ParseRules or Compile call. Zero fields do not limit.

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"))
}

func NewLive

func NewLive(c Compiler, rules []string) (*Live, error)

NewLive compiles rules with c, as c.Compile does: the error lists the rules skipped, and the Live holds the others.

func NewLiveRules

func NewLiveRules(c Compiler, rules []Rule) (*Live, error)

NewLiveRules is NewLive for parsed or built rules, which it compiles as c.CompileRules does.

func (*Live) Err

func (l *Live) Err() error

Err returns the error of the compile that gave the current Matcher: the rules it skipped, or nil.

func (*Live) Matcher

func (l *Live) Matcher() *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

func (l *Live) Refresh() (bool, error)

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

func (l *Live) RefreshErr() error

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

func (l *Live) Rules() []string

Rules returns the rules that the Live compiles; rules given as Rule values in the spelling of Rule.String.

func (*Live) SetTag

func (l *Live) SetTag(v any)

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

func (l *Live) Tag() any

Tag returns the value of SetTag, or nil.

func (*Live) Update

func (l *Live) Update(rules []string) error

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

func (l *Live) UpdateRules(rules []Rule) error

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

func Compile(rules []string) (*Matcher, error)

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

func CompileRules(rules []Rule) (*Matcher, error)

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

func MustCompile(rules []string) *Matcher

MustCompile is Compile that panics if a rule is skipped, for rules fixed in a program.

func (*Matcher) Find

func (m *Matcher) Find(addr string) (Rule, bool)

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 costs as much as Match when nothing matches; otherwise it tests the rules one by one.

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

func (m *Matcher) FindAddrPort(ap netip.AddrPort) (Rule, bool)

FindAddrPort is Find for an address and port, as MatchAddrPort reads them.

func (*Matcher) FindDomain

func (m *Matcher) FindDomain(host string) (Rule, bool)

FindDomain is Find for a domain name, as MatchDomain reads it.

func (*Matcher) FindDomainPort

func (m *Matcher) FindDomainPort(host string, port uint16) (Rule, bool)

FindDomainPort is Find for a domain name and port, as MatchDomainPort reads them.

func (*Matcher) FindHostIP

func (m *Matcher) FindHostIP(host string, ip netip.Addr) (Rule, bool)

FindHostIP is Find for a domain name and its IP address, as MatchHostIP reads them.

func (*Matcher) FindIP

func (m *Matcher) FindIP(ip netip.Addr) (Rule, bool)

FindIP is Find for an IP address, as MatchIP reads it.

func (*Matcher) FindNetAddr

func (m *Matcher) FindNetAddr(a net.Addr) (Rule, bool)

FindNetAddr is Find for a net.Addr, as MatchNetAddr reads it.

func (*Matcher) HasDomainRules

func (m *Matcher) HasDomainRules() bool

HasDomainRules reports whether m holds rules that match domain names.

func (*Matcher) HasIPRules

func (m *Matcher) HasIPRules() bool

HasIPRules reports whether m holds rules that match IP addresses, for callers that only see one kind of address.

func (*Matcher) HasPortRules

func (m *Matcher) HasPortRules() bool

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

func (m *Matcher) Len() int

Len returns the number of rules compiled into m.

func (*Matcher) Match

func (m *Matcher) Match(addr string) bool

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

func (m *Matcher) MatchAddrPort(ap netip.AddrPort) bool

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

func (m *Matcher) MatchDomain(host string) bool

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

func (m *Matcher) MatchDomainPort(host string, port uint16) bool

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

func (m *Matcher) MatchHostIP(host string, ip netip.Addr) bool

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

func (m *Matcher) MatchIP(ip netip.Addr) bool

MatchIP reports whether ip matches an IP rule. IPv4-mapped IPv6 addresses match as IPv4.

func (*Matcher) MatchNetAddr

func (m *Matcher) MatchNetAddr(a net.Addr) bool

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

func (m *Matcher) Matcher() *Matcher

Matcher returns m, so that a *Matcher is the MatcherSource of a Policy.

func (*Matcher) Rules

func (m *Matcher) Rules() []Rule

Rules returns the rules compiled into m, in order.

func (*Matcher) Sources

func (m *Matcher) Sources() []Source

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.

func (*Matcher) Stale

func (m *Matcher) Stale() bool

Stale reports whether a geodata file that m was compiled from has changed since, or appeared after it did not exist, or GeoData.SetFiles replaced the files, so that compiling the rules again would give a different Matcher. It checks the files' metadata only.

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.

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

func ParseMode(s string) (Mode, error)

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

func (m Mode) MarshalText() ([]byte, error)

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 and unknown modes one that allows everything. An allowlist with nil rules allows nothing.

func (Mode) String

func (m Mode) String() string

func (*Mode) UnmarshalJSON

func (m *Mode) UnmarshalJSON(b []byte) error

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

func (m *Mode) UnmarshalText(text []byte) error

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

func (p Policy) Allows(addr string) bool

Allows reports whether the policy allows addr, as Matcher.Match reads it. An address that cannot be read matches no rule.

func (Policy) AllowsAddrPort

func (p Policy) AllowsAddrPort(ap netip.AddrPort) bool

AllowsAddrPort reports whether the policy allows the address and port of ap, as Matcher.MatchAddrPort reads them.

func (Policy) AllowsDomain

func (p Policy) AllowsDomain(host string) bool

AllowsDomain reports whether the policy allows host, as Matcher.MatchDomain reads it.

func (Policy) AllowsDomainPort

func (p Policy) AllowsDomainPort(host string, port uint16) bool

AllowsDomainPort reports whether the policy allows a domain name and port, as Matcher.MatchDomainPort reads them.

func (Policy) AllowsHostIP

func (p Policy) AllowsHostIP(host string, ip netip.Addr) bool

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

func (p Policy) AllowsIP(ip netip.Addr) bool

AllowsIP reports whether the policy allows ip.

func (Policy) AllowsNetAddr

func (p Policy) AllowsNetAddr(a net.Addr) bool

AllowsNetAddr reports whether the policy allows a, such as a connection's RemoteAddr, as Matcher.MatchNetAddr reads it.

func (Policy) Decide

func (p Policy) Decide(addr string) Decision

Decide is Allows that also reports the rule that decided, for logging.

func (Policy) DecideAddrPort

func (p Policy) DecideAddrPort(ap netip.AddrPort) Decision

DecideAddrPort is Decide for an address and port.

func (Policy) DecideDomain

func (p Policy) DecideDomain(host string) Decision

DecideDomain is Decide for a domain name.

func (Policy) DecideDomainPort

func (p Policy) DecideDomainPort(host string, port uint16) Decision

DecideDomainPort is Decide for a domain name and port.

func (Policy) DecideHostIP

func (p Policy) DecideHostIP(host string, ip netip.Addr) Decision

DecideHostIP is Decide for a domain name and its IP address.

func (Policy) DecideIP

func (p Policy) DecideIP(ip netip.Addr) Decision

DecideIP is Decide for an IP address.

func (Policy) DecideNetAddr

func (p Policy) DecideNetAddr(a net.Addr) Decision

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

func (p Policy) HasDomainRules() bool

HasDomainRules reports whether a list of p has rules that match domain names.

func (Policy) HasIPRules

func (p Policy) HasIPRules() bool

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

func (p Policy) HasPortRules() bool

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.

func (Policy) WithName

func (p Policy) WithName(name string) Policy

WithName returns p named name, as in ModeAllowlist.Policy(rules).WithName("user 7").

type PortRange

type PortRange struct {
	First, Last uint16
}

PortRange is a range of ports, First to Last inclusive, of Rule.Ports.

func (PortRange) String

func (r PortRange) String() string

String returns the range as a rule writes it: 443 or 8000-9000.

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

func ParsePriority(s string) (Priority, error)

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

func (p Priority) MarshalText() ([]byte, error)

MarshalText returns the name of p, for configuration files.

func (Priority) String

func (p Priority) String() string

func (*Priority) UnmarshalJSON

func (p *Priority) UnmarshalJSON(b []byte) error

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

func (p *Priority) UnmarshalText(text []byte) error

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 Rule
}

Routed is the answer of a Router for an address, with the route and rule that decided.

func (Routed[T]) String

func (r Routed[T]) String() string

String describes r for logs, as "proxy by geosite:google (route 2)" or "direct by default".

type Router

type Router[T any] struct {
	Routes  []Route[T]
	Default T
}

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

func (r Router[T]) Find(addr string) Routed[T]

Find is Route that also reports the route and rule that decided, for logging.

func (Router[T]) FindAddrPort

func (r Router[T]) FindAddrPort(ap netip.AddrPort) Routed[T]

FindAddrPort is Find for an address and port.

func (Router[T]) FindDomain

func (r Router[T]) FindDomain(host string) Routed[T]

FindDomain is Find for a domain name.

func (Router[T]) FindDomainPort

func (r Router[T]) FindDomainPort(host string, port uint16) Routed[T]

FindDomainPort is Find for a domain name and port.

func (Router[T]) FindHostIP

func (r Router[T]) FindHostIP(host string, ip netip.Addr) Routed[T]

FindHostIP is Find for a domain name and its IP address.

func (Router[T]) FindIP

func (r Router[T]) FindIP(ip netip.Addr) Routed[T]

FindIP is Find for an IP address.

func (Router[T]) FindNetAddr

func (r Router[T]) FindNetAddr(a net.Addr) Routed[T]

FindNetAddr is Find for a net.Addr.

func (Router[T]) Route

func (r Router[T]) Route(addr string) T

Route returns the target of addr, as Matcher.Match reads it.

func (Router[T]) RouteAddrPort

func (r Router[T]) RouteAddrPort(ap netip.AddrPort) T

RouteAddrPort returns the target of an address and port, as Matcher.MatchAddrPort reads them.

func (Router[T]) RouteDomain

func (r Router[T]) RouteDomain(host string) T

RouteDomain returns the target of host, as Matcher.MatchDomain reads it.

func (Router[T]) RouteDomainPort

func (r Router[T]) RouteDomainPort(host string, port uint16) T

RouteDomainPort returns the target of a domain name and port, as Matcher.MatchDomainPort reads them.

func (Router[T]) RouteHostIP

func (r Router[T]) RouteHostIP(host string, ip netip.Addr) T

RouteHostIP returns the target of a domain name and the IP address it resolved to, as Matcher.MatchHostIP reads them.

func (Router[T]) RouteIP

func (r Router[T]) RouteIP(ip netip.Addr) T

RouteIP returns the target of ip.

func (Router[T]) RouteNetAddr

func (r Router[T]) RouteNetAddr(a net.Addr) T

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. The rules that Find and Decide return share it with
	// their Matcher, so that they do not allocate: copy it to change it.
	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

func ParseRule(s string) (Rule, error)

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

func ParseRules(rules []string) ([]Rule, error)

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

func (r Rule) IsDomain() bool

IsDomain reports whether the rule matches domain names.

func (Rule) IsIP

func (r Rule) IsIP() bool

IsIP reports whether the rule matches IP addresses. RuleExt depends on its file, so it counts as both kinds.

func (Rule) MarshalText

func (r Rule) MarshalText() ([]byte, error)

MarshalText returns the rule as String writes it, or an error for the zero Rule or an unknown kind.

func (Rule) String

func (r Rule) String() string

String returns the rule in the syntax ParseRule reads, or "" for the zero Rule.

func (*Rule) UnmarshalText

func (r *Rule) UnmarshalText(text []byte) error

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  string
	Err   error
}

RuleError reports a rule that was rejected or skipped, and why. errors.Is tells ErrInvalidRule from ErrGeoData.

func (*RuleError) Error

func (e *RuleError) Error() string

Error describes the rule and the cause, without Index, which RuleErrors adds for each rule of a list.

func (*RuleError) Unwrap

func (e *RuleError) Unwrap() error

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.

func (RuleKind) String

func (k RuleKind) String() string

String returns the name of k, the prefix of its rules: ip, geoip, full, domain, subdomain, keyword, regexp, dotless, geosite or ext.

type Source

type Source struct {
	File string
	// Missing reports that the file did not exist, so that the rules
	// needing it were skipped.
	Missing bool
	Size    int64
	ModTime time.Time
}

Source is a geodata file that a Matcher was compiled from.

type SyntaxError

type SyntaxError struct {
	Offset int
	Msg    string
}

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

Jump to

Keyboard shortcuts

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