Documentation
¶
Index ¶
- Constants
- Variables
- type AllCheckpoints
- type Checkpoint
- type DataSource
- type DbNameValidator
- type FsStorageDriver
- func (s *FsStorageDriver) ReadCheckpoints() (*AllCheckpoints, error)
- func (s *FsStorageDriver) ReadDatabase(name string) (io.ReadCloser, error)
- func (s *FsStorageDriver) ValidateDatabaseName(name string) error
- func (s *FsStorageDriver) WriteCheckpoints(checkpoints *AllCheckpoints) error
- func (s *FsStorageDriver) WriteDatabase(name string, input io.ReadCloser) error
- type HttpStatusError
- type Ipdb
- func (s *Ipdb) Close() error
- func (s *Ipdb) DownloadAndLoadGeoIpv4Mmdb() error
- func (s *Ipdb) DownloadAndLoadGeoIpv6Mmdb() error
- func (s *Ipdb) DownloadAndLoadRangeDatabase(name string) error
- func (s *Ipdb) IsIpInRangeDb(dbName string, ip netip.Addr) (bool, error)
- func (s *Ipdb) ResolveIpIsoCountry(ip netip.Addr, defaultCc string) (string, error)
- type NoSuchDatabaseError
- type NotInitializedError
- type Options
- type RetryAction
- type RetryDecision
- type RetryPolicy
- type SourceFailure
- type StorageDriver
Constants ¶
const ( // DefaultHttpTimeout is the default HTTP client's timeout for an entire download, including reading the body. // It is used as http.Client.Timeout when Options.HttpClient is nil. DefaultHttpTimeout = 5 * time.Minute // DefaultHttpResponseHeaderTimeout is the default HTTP client's timeout for receiving response headers after // sending a request. // It is used as http.Transport.ResponseHeaderTimeout when Options.HttpClient is nil. DefaultHttpResponseHeaderTimeout = 30 * time.Second )
const DbNameGeoIpv4 = "__ipdb_geo_ipv4"
DbNameGeoIpv4 is the database name used for the GeoIP database for IPv4 addresses. Do not name any database with this name.
const DbNameGeoIpv6 = "__ipdb_geo_ipv6"
DbNameGeoIpv6 is the database name used for the GeoIP database for IPv6 addresses. Do not name any database with this name.
const DbNameMaxSize = 64
DbNameMaxSize is the max size of the database name, in bytes.
const DefaultMaxDatabaseSize int64 = 1 * 1024 * 1024 * 1024 // 1GiB
DefaultMaxDatabaseSize is the default maximum size of a single database, in bytes. See Options.MaxDatabaseSize.
Variables ¶
var ErrAllUrlsFailed = errors.New("all URLs in data source failed")
ErrAllUrlsFailed is returned when all URLs in a data source failed.
var ErrDataSourceNoSource = errors.New("data source has no sources: len(Urls) == 0 or Get method is nil")
ErrDataSourceNoSource is returned when a data source has no sources. "No sources" means that the data source has no URLs and the Get method is nil.
var ErrDatabaseTooLarge = errors.New("database is too large")
ErrDatabaseTooLarge is returned when a database is larger than the maximum database size. See Options.MaxDatabaseSize.
var ErrDbNameTooLong = fmt.Errorf("database name too long, must be at most %d bytes long", DbNameMaxSize)
ErrDbNameTooLong is returned when a database name exceeds DbNameMaxSize bytes.
var ErrFailedByRetryPolicy = errors.New("database update was failed by the retry policy")
ErrFailedByRetryPolicy is returned when a database update was failed by the RetryPolicy returning RetryActionFail. The error also wraps the error of the source that failed.
var ErrInvalidDbName = errors.New("invalid database name")
ErrInvalidDbName is returned when a database name is empty, reserved or otherwise unusable.
var ErrInvalidRefreshInterval = errors.New("data source RefreshInterval must be positive")
ErrInvalidRefreshInterval is returned when a data source's RefreshInterval is not positive while downloading is enabled.
var ErrIpdbClosed = errors.New("ipdb closed")
ErrIpdbClosed is returned when an operation is attempted on a closed IP database.
var ErrNoCacheAndNoDownload = errors.New("no cached copy of database existed, and downloading is disabled")
ErrNoCacheAndNoDownload is returned when there is no cached database, and downloading is disabled so there is no way to get the database.
var ErrNoRanges = errors.New("range database contains no IP addresses or CIDR ranges")
ErrNoRanges is returned when a range database contains no IP addresses or CIDR ranges. A source that yields an empty list is treated as broken, rather than replacing existing data with nothing.
Functions ¶
This section is empty.
Types ¶
type AllCheckpoints ¶
type AllCheckpoints struct {
// All checkpoints.
// Key is the database name, value is the checkpoint.
Checkpoints map[string]Checkpoint `json:"checkpoints"`
}
AllCheckpoints is information for all database checkpoints.
type Checkpoint ¶
type Checkpoint struct {
// When the database was last updated from source.
// Unix epoch second timestamp.
LastUpdatedUnix int64 `json:"last_updated_unix"`
}
Checkpoint is checkpoint information for a database.
type DataSource ¶
type DataSource struct {
// Urls are the URLs where the IP data is located.
// Either Get or Urls must be provided; Get takes precedence over Urls.
//
// For range databases, the contents of all URLs are merged into a single database.
// URLs that fail to download or do not contain a valid list are handled by Options.RetryPolicy.
// If Options.RetryPolicy is not set, the failed URL is logged and skipped, and the database is updated from the
// remaining URLs.
//
// For geoIP databases, the URLs are mirrors that are tried in order; the first one that yields a valid database is
// used.
Urls []*url.URL
// Get is a function to get the IP data.
// Either Get or Urls must be provided; Get takes precedence over Urls.
// The returned reader is closed by the Ipdb instance.
//
// Get should return within a reasonable amount of time; Ipdb.Close waits for running calls to finish.
Get func() (io.ReadCloser, error)
// RefreshInterval is the interval between updating the data from the source.
// Required and must be positive, unless Options.DisableDownload is true.
RefreshInterval time.Duration
}
DataSource stores source information for IP data. It includes the URLs the data can be fetched from and the time to wait between updating the data from them.
type DbNameValidator ¶ added in v1.1.0
type DbNameValidator interface {
// ValidateDatabaseName returns an error if a database with the specified name cannot be stored.
ValidateDatabaseName(name string) error
}
DbNameValidator can optionally be implemented by a StorageDriver to reject database names it cannot store. If implemented, NewIpdb validates all range database names with it and fails early if any are rejected.
type FsStorageDriver ¶
type FsStorageDriver struct {
// contains filtered or unexported fields
}
FsStorageDriver implements StorageDriver by storing databases and checkpoints inside a data directory. Use NewFsStorageDriver to create an instance.
func NewFsStorageDriver ¶
func NewFsStorageDriver(dataDir string) (*FsStorageDriver, error)
NewFsStorageDriver creates a new instance of StorageDriver. The specified directory must exist and be readable and writable by the current user. If the directory does not exist, returns an error matching fs.ErrNotExist (and syscall.ENOENT on Unix-like systems). If the path is not a directory, returns a wrapped syscall.ENOTDIR.
func (*FsStorageDriver) ReadCheckpoints ¶
func (s *FsStorageDriver) ReadCheckpoints() (*AllCheckpoints, error)
func (*FsStorageDriver) ReadDatabase ¶
func (s *FsStorageDriver) ReadDatabase(name string) (io.ReadCloser, error)
func (*FsStorageDriver) ValidateDatabaseName ¶ added in v1.1.0
func (s *FsStorageDriver) ValidateDatabaseName(name string) error
ValidateDatabaseName returns an error if a database with the specified name cannot be stored by the driver. If the name exceeds DbNameMaxSize bytes, returns ErrDbNameTooLong. If the name is empty or would collide with files used internally by the driver, returns a wrapped ErrInvalidDbName.
func (*FsStorageDriver) WriteCheckpoints ¶
func (s *FsStorageDriver) WriteCheckpoints(checkpoints *AllCheckpoints) error
func (*FsStorageDriver) WriteDatabase ¶
func (s *FsStorageDriver) WriteDatabase(name string, input io.ReadCloser) error
type HttpStatusError ¶ added in v1.1.0
type HttpStatusError struct {
// The response status code.
StatusCode int
// The start of the response body, which may help explain the error.
BodyPreview string
}
HttpStatusError is returned when downloading a source yields a response with a status code other than 200.
func (*HttpStatusError) Error ¶ added in v1.1.0
func (err *HttpStatusError) Error() string
type Ipdb ¶
type Ipdb struct {
// contains filtered or unexported fields
}
Ipdb stores and updates IP databases.
Includes functionality to:
- Resolve ISO 3166 country codes for an IP address
- Check if an IP address appears in a specific list of ranges (such as Tor exit nodes or datacenter ranges)
Databases are cached on disk and updated periodically from data sources. At runtime, databases are stored in-memory.
Caches are not aware of which data sources were used to create them, so adding, removing or changing data source URLs or Get method implementations should be followed by clearing the cache.
Create an instance with NewIpdb; do not create an empty Ipdb struct and attempt to use it.
There should only be one instance of Ipdb per storage driver or storage location, and ideally only one per process. It is safe to use a single instance of Ipdb across multiple goroutines.
func NewIpdb ¶
NewIpdb creates a new Ipdb instance. Blocks until the databases are loaded, unless Options.LoadDatabasesInBackground is true. If loading fails, returns the error, or with Options.LoadDatabasesInBackground, closes the returned instance. There should only be one instance of Ipdb per storage driver or storage location, and ideally only one per process. If error is nil, the returned Ipdb instance will never be nil.
func (*Ipdb) Close ¶
Close stops all background updates and frees all databases. Running downloads are canceled, and Close waits for background work to stop before returning. The Ipdb instance is no longer usable after closure; its methods return ErrIpdbClosed.
It is safe to call Close multiple times and from multiple goroutines. Subsequent calls do nothing. The returned error is currently always nil.
func (*Ipdb) DownloadAndLoadGeoIpv4Mmdb ¶
DownloadAndLoadGeoIpv4Mmdb downloads the GeoIPv4 MMDB, loads it into memory and writes it to the cache. You most likely do not need to call this function, as loading databases is handled automatically by the Ipdb instance.
If the download fails or yields invalid data, the existing database is left untouched. If Options.GeoIpv4Source was nil, returns an error wrapping ErrDataSourceNoSource. If the Ipdb instance has been closed, returns ErrIpdbClosed.
func (*Ipdb) DownloadAndLoadGeoIpv6Mmdb ¶
DownloadAndLoadGeoIpv6Mmdb downloads the GeoIPv6 MMDB, loads it into memory and writes it to the cache. You most likely do not need to call this function, as loading databases is handled automatically by the Ipdb instance.
If the download fails or yields invalid data, the existing database is left untouched. If Options.GeoIpv6Source was nil, returns an error wrapping ErrDataSourceNoSource. If the Ipdb instance has been closed, returns ErrIpdbClosed.
func (*Ipdb) DownloadAndLoadRangeDatabase ¶ added in v1.0.0
DownloadAndLoadRangeDatabase downloads the database with the specified name, loads it into memory and writes it to the cache. You most likely do not need to call this function, as loading databases is handled automatically by the Ipdb instance.
If the download fails or yields invalid data, the existing database is left untouched. If the database does not exist, returns a NoSuchDatabaseError. If the Ipdb instance has been closed, returns ErrIpdbClosed.
func (*Ipdb) IsIpInRangeDb ¶ added in v1.0.0
IsIpInRangeDb returns whether an IP was found in the specified IP range database. IPv4-mapped IPv6 addresses are treated as IPv4 addresses. If the database does not exist, returns a NoSuchDatabaseError. If the database has not been initialized, returns a NotInitializedError. If the Ipdb instance has been closed, returns ErrIpdbClosed.
func (*Ipdb) ResolveIpIsoCountry ¶
ResolveIpIsoCountry resolves the ISO 3166 country code for the specified IP address. The country code is uppercase. IPv4-mapped IPv6 addresses are treated as IPv4 addresses. If no country can be found, defaults to defaultCc. If the required database is not initialized, returns a NotInitializedError. If the Ipdb instance has been closed, returns ErrIpdbClosed.
To avoid returning an invalid ISO 3166 country code, the defaultCc parameter should ideally be a valid ISO 3166 country code. A good placeholder value is "AQ", which is the ISO 3166 country code for Antarctica.
type NoSuchDatabaseError ¶ added in v1.0.0
type NoSuchDatabaseError struct {
// The name of database that did not exist.
Name string
}
NoSuchDatabaseError is returned when trying to access a IP range database that does not exist. Includes the requested database name that did not exist.
func NewNoSuchDatabaseError ¶ added in v1.0.0
func NewNoSuchDatabaseError(name string) *NoSuchDatabaseError
NewNoSuchDatabaseError creates a new NoSuchDatabaseError instance with the specified database name.
func (*NoSuchDatabaseError) Error ¶ added in v1.0.0
func (err *NoSuchDatabaseError) Error() string
type NotInitializedError ¶
type NotInitializedError struct {
// The type of database that was not initialized.
Name string
// The message.
Msg string
}
NotInitializedError is returned when a function is run that required an IP database to be initialized, but it was not initialized. Includes the IP database type that was required but not initialized.
func NewNotInitializedError ¶
func NewNotInitializedError(name string, msg string) *NotInitializedError
NewNotInitializedError creates a new NotInitializedError instance with the specified database name and message.
func (*NotInitializedError) Error ¶
func (err *NotInitializedError) Error() string
type Options ¶
type Options struct {
// The storage driver used to store cached databases and checkpoint information.
// Unless you have a custom driver you want to use, you should most likely use FsStorageDriver.
// Required.
StorageDriver StorageDriver
// By default, Ipdb uses slog.Default.
// If Logger is specified, it will use it instead.
Logger *slog.Logger
// Overrides the default HTTP client if not nil.
// If nil, uses a default HTTP client based on http.DefaultTransport, with a timeout of DefaultHttpTimeout per
// download and a timeout of DefaultHttpResponseHeaderTimeout for receiving response headers.
HttpClient *http.Client
// If true, disables downloading from sources and only uses cached database files.
//
// Important: You must still provide sources for the databases you want to use, regardless of whether download is
// disabled.
DisableDownload bool
// If true, NewIpdb returns without waiting for databases to be loaded, and they are loaded in the background instead.
//
// This option is intended for speeding up startup during development, where waiting for databases to load or
// download every time the program starts gets in the way. It is unsuitable for production, because:
// - Any methods on Ipdb that require databases return a NotInitializedError until the databases have loaded.
// - If loading fails, the error is only logged, and the Ipdb instance is closed. Loading is not retried, and
// the instance's methods return ErrIpdbClosed from then on. Without this option, NewIpdb would instead
// return the error, so the program can handle it.
LoadDatabasesInBackground bool
// The maximum size of a single database, in bytes.
// Downloads and cached files larger than this are rejected with ErrDatabaseTooLarge.
// For range databases with multiple URLs, the limit applies to the merged database.
// If zero or negative, DefaultMaxDatabaseSize is used.
MaxDatabaseSize int64
// Decides what happens when a source of a database fails to download: retry it, skip it, or fail the update of the
// whole database.
// See RetryPolicy.
// A download that completes but does not contain a valid database also counts as a failure.
//
// If nil, failed sources are logged and skipped without retrying, so a broken URL never stops a database
// from being updated from its other URLs.
// See SkipAllSources.
RetryPolicy RetryPolicy
// A mapping of database names to their underlying IP range sources.
// Each source must yield a newline-separated list of IP addresses and/or CIDR ranges.
// Empty lines and lines that start with "#" are ignored.
//
// Names must not be empty, must be at most DbNameMaxSize bytes long, and must not be DbNameGeoIpv4 or
// DbNameGeoIpv6. The storage driver may impose additional restrictions.
RangeSources map[string]*DataSource
// The source for the IPv4 country database.
// It must yield a MaxMindDB (.mmdb) file that stores the ISO 3166 country code in either a top-level "country_code"
// field (as used by many third-party mirrors) or in "country.iso_code" (as used by MaxMind's GeoLite2 and GeoIP2
// databases).
// See: https://dev.maxmind.com/geoip/geolite2-free-geolocation-data/
//
// Resolving IPv4 country codes will be disabled if this field is nil.
GeoIpv4Source *DataSource
// The source for the IPv6 country database.
// It must yield a MaxMindDB (.mmdb) file that stores the ISO 3166 country code in either a top-level "country_code"
// field (as used by many third-party mirrors) or in "country.iso_code" (as used by MaxMind's GeoLite2 and GeoIP2
// databases).
// See: https://dev.maxmind.com/geoip/geolite2-free-geolocation-data/
//
// Resolving IPv6 country codes will be disabled if this field is nil.
GeoIpv6Source *DataSource
}
Options are options for creating an Ipdb instance. Any omitted DataSource fields will be disabled and unavailable, even if cached files for them exist.
type RetryAction ¶ added in v1.1.0
type RetryAction int
RetryAction is the action to take after a source fails to download.
const ( // RetryActionSkip gives up on the source for the current update. // // For range databases with multiple URLs, the database is updated from the remaining URLs, // and the ranges from the skipped URL are left out until it works again. // For geoIP databases with multiple URLs, the next mirror is tried. // If every source of a database is skipped, the update fails and the database keeps its current data. // // This is the zero value, and what happens if Options.RetryPolicy is nil. RetryActionSkip RetryAction = iota // RetryActionRetry tries to download the source again after RetryDecision.Delay. RetryActionRetry // RetryActionFail fails the update of the whole database immediately, without trying its remaining sources. // The database keeps its current data, and the update is retried later as for any other failed update. RetryActionFail )
func (RetryAction) String ¶ added in v1.1.0
func (a RetryAction) String() string
type RetryDecision ¶ added in v1.1.0
type RetryDecision struct {
// Action is the action to take.
// Unknown actions are treated as RetryActionSkip.
Action RetryAction
// Delay is the time to wait before retrying when Action is RetryActionRetry.
// The wait is cut short if the Ipdb instance is closed.
// Ignored for other actions.
Delay time.Duration
}
RetryDecision is returned by a RetryPolicy to decide what happens after a source fails to download.
func SkipAllSources ¶ added in v1.1.0
func SkipAllSources(_ SourceFailure) RetryDecision
SkipAllSources is the default RetryPolicy. It skips any failed sources without retrying.
type RetryPolicy ¶ added in v1.1.0
type RetryPolicy func(failure SourceFailure) RetryDecision
RetryPolicy decides what happens when a source of a database fails to download. It is called once for each failed attempt, and may be called concurrently for different databases.
Retries made by the policy all happen within a single update. They are separate from the retries of failed updates, which happen with an increasing delay that never exceeds the database's DataSource.RefreshInterval.
Example policy that retries server errors twice, and skips anything else (such as a 404):
func(f ipdb.SourceFailure) ipdb.RetryDecision {
statusErr, is := errors.AsType[*ipdb.HttpStatusError](f.Err)
if is && statusErr.StatusCode >= 500 && f.Attempt <= 2 {
return ipdb.RetryDecision{
Action: ipdb.RetryActionRetry,
Delay: 10 * time.Second,
}
}
return ipdb.RetryDecision{
Action: ipdb.RetryActionSkip,
}
}
type SourceFailure ¶ added in v1.1.0
type SourceFailure struct {
// DbName is the name of the database being updated.
// This is either a range database name, DbNameGeoIpv4 or DbNameGeoIpv6.
DbName string
// Url is the URL that failed, or nil if the source is a DataSource.Get function.
// It may contain credentials or query parameters such as license keys, so take care when logging it.
Url *url.URL
// Attempt is the number of attempts made to download this source during the current update, starting at 1.
Attempt int
// Err is the error that caused the attempt to fail.
// A response with a non-200 status code produces an error that matches *HttpStatusError when checked with errors.As.
// A download that is not a valid database produces an error that matches ErrNoRanges, ErrDatabaseTooLarge or
// a parse error, depending on the problem.
Err error
}
SourceFailure describes a failed attempt to download one source of a database.
type StorageDriver ¶
type StorageDriver interface {
// WriteDatabase writes the contents of the reader to the database file with the specified name.
// The reader will be closed by the function regardless of whether an error occurs.
// If an error occurs, any previously written database with the same name must be left intact.
// May be called concurrently for different names.
WriteDatabase(name string, input io.ReadCloser) error
// ReadDatabase opens the database file with the specified name for reading.
// The caller is expected to close the reader.
// If there is no cached database with the specified name, the function must return an error that matches
// fs.ErrNotExist when checked with errors.Is (such as syscall.ENOENT or a wrapped error from the os package).
ReadDatabase(name string) (io.ReadCloser, error)
// WriteCheckpoints writes all checkpoints.
// Checkpoints must not be nil.
WriteCheckpoints(checkpoints *AllCheckpoints) error
// ReadCheckpoints reads and returns all checkpoints.
// The returned checkpoints will never be nil if there is no error.
// If checkpoints have not been saved yet, the function must return an error that matches
// fs.ErrNotExist when checked with errors.Is (such as syscall.ENOENT or a wrapped error from the os package).
ReadCheckpoints() (*AllCheckpoints, error)
}
StorageDriver is an interface that stores IP databases and checkpoint data.