Skip to content
Snippets Groups Projects
Commit 3f7867d8 authored by renovate's avatar renovate
Browse files

Update module oschwald/maxminddb-golang to v0.2.0

parent 782d5400
No related branches found
No related tags found
1 merge request!14Update module oschwald/maxminddb-golang to v0.2.0
Pipeline #10690 passed
Showing
with 487 additions and 943 deletions
...@@ -14,7 +14,7 @@ require ( ...@@ -14,7 +14,7 @@ require (
github.com/jonboulle/clockwork v0.2.2 // indirect github.com/jonboulle/clockwork v0.2.2 // indirect
github.com/mattermost/xml-roundtrip-validator v0.0.0-20201219040909-8fd2afad43d1 // indirect github.com/mattermost/xml-roundtrip-validator v0.0.0-20201219040909-8fd2afad43d1 // indirect
github.com/mssola/user_agent v0.0.0-20170906152553-a2f39d5a9b15 github.com/mssola/user_agent v0.0.0-20170906152553-a2f39d5a9b15
github.com/oschwald/maxminddb-golang v0.0.0-20170901134056-26fe5ace1c70 github.com/oschwald/maxminddb-golang v0.2.0
github.com/prometheus/client_golang v1.9.0 github.com/prometheus/client_golang v1.9.0
github.com/rs/cors v0.0.0-20190613161432-33ffc0734c60 github.com/rs/cors v0.0.0-20190613161432-33ffc0734c60
github.com/tstranex/u2f v1.0.0 github.com/tstranex/u2f v1.0.0
......
...@@ -272,6 +272,8 @@ github.com/openzipkin/zipkin-go v0.2.5 h1:UwtQQx2pyPIgWYHRg+epgdx1/HnBQTgN3/oIYE ...@@ -272,6 +272,8 @@ github.com/openzipkin/zipkin-go v0.2.5 h1:UwtQQx2pyPIgWYHRg+epgdx1/HnBQTgN3/oIYE
github.com/openzipkin/zipkin-go v0.2.5/go.mod h1:KpXfKdgRDnnhsxw4pNIH9Md5lyFqKUa4YDFlwRYAMyE= github.com/openzipkin/zipkin-go v0.2.5/go.mod h1:KpXfKdgRDnnhsxw4pNIH9Md5lyFqKUa4YDFlwRYAMyE=
github.com/oschwald/maxminddb-golang v0.0.0-20170901134056-26fe5ace1c70 h1:XGLYUmodtNzThosQ8GkMvj9TiIB/uWsP8NfxKSa3aDc= github.com/oschwald/maxminddb-golang v0.0.0-20170901134056-26fe5ace1c70 h1:XGLYUmodtNzThosQ8GkMvj9TiIB/uWsP8NfxKSa3aDc=
github.com/oschwald/maxminddb-golang v0.0.0-20170901134056-26fe5ace1c70/go.mod h1:3jhIUymTJ5VREKyIhWm66LJiQt04F0UCDdodShpjWsY= github.com/oschwald/maxminddb-golang v0.0.0-20170901134056-26fe5ace1c70/go.mod h1:3jhIUymTJ5VREKyIhWm66LJiQt04F0UCDdodShpjWsY=
github.com/oschwald/maxminddb-golang v0.2.0 h1:cdvE3VUWCRdu+tYIBtwbcPWj1A83jZc5CSdGSuhnqO8=
github.com/oschwald/maxminddb-golang v0.2.0/go.mod h1:3jhIUymTJ5VREKyIhWm66LJiQt04F0UCDdodShpjWsY=
github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM= github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v0.0.0-20180815053127-5633e0862627/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/patrickmn/go-cache v0.0.0-20180815053127-5633e0862627/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
......
.vscode
*.out
*.sw?
*.test
[submodule "test-data"] [submodule "test-data"]
path = test-data path = test-data
url = https://github.com/maxmind/MaxMind-DB.git url = git://github.com/maxmind/MaxMind-DB.git
language: go language: go
go: go:
- 1.4 - 1.1
- 1.5 - 1.2
- 1.6 - 1.3
- 1.7 - release
- 1.8
- tip - tip
before_install:
- "if [[ $TRAVIS_GO_VERSION == 1.7 ]]; then go get -v github.com/golang/lint/golint; fi"
install: install:
- go get -v -t ./... - go get launchpad.net/gocheck
script:
- go test -race -cpu 1,4 -v
- go test -race -v -tags appengine
- "if [[ $TRAVIS_GO_VERSION == 1.7 ]]; then go vet ./...; fi"
- "if [[ $TRAVIS_GO_VERSION == 1.7 ]]; then golint .; fi"
sudo: false
ISC License
Copyright (c) 2015, Gregory J. Oschwald <oschwald@gmail.com> Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Permission to use, copy, modify, and/or distribute this software for any TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH 1. Definitions.
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, "License" shall mean the terms and conditions for use, reproduction,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM and distribution as defined by Sections 1 through 9 of this document.
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR "Licensor" shall mean the copyright owner or entity authorized by
PERFORMANCE OF THIS SOFTWARE. the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# MaxMind DB Reader for Go # # MaxMind DB Reader for Go #
[![Build Status](https://travis-ci.org/oschwald/maxminddb-golang.png?branch=master)](https://travis-ci.org/oschwald/maxminddb-golang) [![Build Status](https://travis-ci.org/oschwald/maxminddb-golang.png?branch=master)](https://travis-ci.org/oschwald/maxminddb-golang)
[![Windows Build Status](https://ci.appveyor.com/api/projects/status/4j2f9oep8nnfrmov/branch/master?svg=true)](https://ci.appveyor.com/project/oschwald/maxminddb-golang/branch/master)
[![GoDoc](https://godoc.org/github.com/oschwald/maxminddb-golang?status.png)](https://godoc.org/github.com/oschwald/maxminddb-golang) [![GoDoc](https://godoc.org/github.com/oschwald/maxminddb-golang?status.png)](https://godoc.org/github.com/oschwald/maxminddb-golang)
This is a Go reader for the MaxMind DB format. Although this can be used to
read [GeoLite2](http://dev.maxmind.com/geoip/geoip2/geolite2/) and This is a Go reader for the MaxMind DB format. This can be used to read
[GeoIP2](https://www.maxmind.com/en/geoip2-databases) databases, [GeoLite2](http://dev.maxmind.com/geoip/geoip2/geolite2/) and
[geoip2](https://github.com/oschwald/geoip2-golang) provides a higher-level [GeoIP2](http://www.maxmind.com/en/geolocation_landing) databases.
API for doing so.
This is not an official MaxMind API. This is not an official MaxMind API.
...@@ -35,4 +33,4 @@ with your changes. ...@@ -35,4 +33,4 @@ with your changes.
## License ## ## License ##
This is free software, licensed under the ISC License. This is free software, licensed under the Apache License, Version 2.0.
version: "{build}"
os: Windows Server 2012 R2
clone_folder: c:\gopath\src\github.com\oschwald\maxminddb-golang
environment:
GOPATH: c:\gopath
install:
- echo %PATH%
- echo %GOPATH%
- git submodule update --init --recursive
- go version
- go env
- go get -v -t ./...
build_script:
- go test -v ./...
set GOPATH=%BuildFolder%
go get -v ./...
go test -v ./...
This diff is collapsed.
package maxminddb
import (
"fmt"
"reflect"
)
// InvalidDatabaseError is returned when the database contains invalid data
// and cannot be parsed.
type InvalidDatabaseError struct {
message string
}
func newOffsetError() InvalidDatabaseError {
return InvalidDatabaseError{"unexpected end of database"}
}
func newInvalidDatabaseError(format string, args ...interface{}) InvalidDatabaseError {
return InvalidDatabaseError{fmt.Sprintf(format, args...)}
}
func (e InvalidDatabaseError) Error() string {
return e.message
}
// UnmarshalTypeError is returned when the value in the database cannot be
// assigned to the specified data type.
type UnmarshalTypeError struct {
Value string // stringified copy of the database value that caused the error
Type reflect.Type // type of the value that could not be assign to
}
func newUnmarshalTypeError(value interface{}, rType reflect.Type) UnmarshalTypeError {
return UnmarshalTypeError{
Value: fmt.Sprintf("%v", value),
Type: rType,
}
}
func (e UnmarshalTypeError) Error() string {
return fmt.Sprintf("maxminddb: cannot unmarshal %s into type %s", e.Value, e.Type.String())
}
...@@ -5,16 +5,11 @@ import ( ...@@ -5,16 +5,11 @@ import (
"errors" "errors"
"fmt" "fmt"
"net" "net"
"os"
"reflect" "reflect"
) )
const ( const dataSectionSeparatorSize = 16
// NotFound is returned by LookupOffset when a matched root record offset
// cannot be found.
NotFound = ^uintptr(0)
dataSectionSeparatorSize = 16
)
var metadataStartMarker = []byte("\xAB\xCD\xEFMaxMind.com") var metadataStartMarker = []byte("\xAB\xCD\xEFMaxMind.com")
...@@ -44,42 +39,62 @@ type Metadata struct { ...@@ -44,42 +39,62 @@ type Metadata struct {
RecordSize uint `maxminddb:"record_size"` RecordSize uint `maxminddb:"record_size"`
} }
// Open takes a string path to a MaxMind DB file and returns a Reader
// structure or an error. The database file is opened using a memory map. Use
// the Close method on the Reader object to return the resources to the
// system.
func Open(file string) (*Reader, error) {
mapFile, err := os.Open(file)
if err != nil {
return nil, err
}
defer mapFile.Close()
stats, err := mapFile.Stat()
if err != nil {
return nil, err
}
fileSize := int(stats.Size())
mmap, err := mmap(int(mapFile.Fd()), fileSize)
if err != nil {
return nil, err
}
reader, err := FromBytes(mmap)
if err != nil {
munmap(mmap)
return nil, err
}
reader.hasMappedFile = true
return reader, nil
}
// FromBytes takes a byte slice corresponding to a MaxMind DB file and returns // FromBytes takes a byte slice corresponding to a MaxMind DB file and returns
// a Reader structure or an error. // a Reader structure or an error.
func FromBytes(buffer []byte) (*Reader, error) { func FromBytes(buffer []byte) (*Reader, error) {
metadataStart := bytes.LastIndex(buffer, metadataStartMarker) metadataStart := bytes.LastIndex(buffer, metadataStartMarker)
if metadataStart == -1 { if metadataStart == -1 {
return nil, newInvalidDatabaseError("error opening database: invalid MaxMind DB file") return nil, fmt.Errorf("error opening database file: invalid MaxMind DB file")
} }
metadataStart += len(metadataStartMarker) metadataStart += len(metadataStartMarker)
metadataDecoder := decoder{buffer[metadataStart:]} metadataDecoder := decoder{buffer, uint(metadataStart)}
var metadata Metadata var metadata Metadata
rvMetdata := reflect.ValueOf(&metadata) rvMetdata := reflect.ValueOf(&metadata)
_, err := metadataDecoder.decode(0, rvMetdata, 0) _, err := metadataDecoder.decode(uint(metadataStart), rvMetdata)
if err != nil { if err != nil {
return nil, err return nil, err
} }
searchTreeSize := metadata.NodeCount * metadata.RecordSize / 4 searchTreeSize := metadata.NodeCount * metadata.RecordSize / 4
dataSectionStart := searchTreeSize + dataSectionSeparatorSize decoder := decoder{buffer, searchTreeSize + dataSectionSeparatorSize}
dataSectionEnd := uint(metadataStart - len(metadataStartMarker))
if dataSectionStart > dataSectionEnd {
return nil, newInvalidDatabaseError("the MaxMind DB contains invalid metadata")
}
d := decoder{
buffer[searchTreeSize+dataSectionSeparatorSize : metadataStart-len(metadataStartMarker)],
}
reader := &Reader{ reader := &Reader{buffer: buffer, decoder: decoder, Metadata: metadata, ipv4Start: 0}
buffer: buffer,
decoder: d,
Metadata: metadata,
ipv4Start: 0,
}
reader.ipv4Start, err = reader.startNode() reader.ipv4Start, err = reader.startNode()
...@@ -105,57 +120,22 @@ func (r *Reader) startNode() (uint, error) { ...@@ -105,57 +120,22 @@ func (r *Reader) startNode() (uint, error) {
} }
// Lookup takes an IP address as a net.IP structure and a pointer to the // Lookup takes an IP address as a net.IP structure and a pointer to the
// result value to Decode into. // result value to decode into. The result value pointed to must be a data
func (r *Reader) Lookup(ipAddress net.IP, result interface{}) error { // value that corresponds to a record in the database. This may include a
pointer, err := r.lookupPointer(ipAddress) // struct representation of the data, a map capable of holding the data or an
if pointer == 0 || err != nil { // empty interface{} value.
return err
}
return r.retrieveData(pointer, result)
}
// LookupOffset maps an argument net.IP to a corresponding record offset in the
// database. NotFound is returned if no such record is found, and a record may
// otherwise be extracted by passing the returned offset to Decode. LookupOffset
// is an advanced API, which exists to provide clients with a means to cache
// previously-decoded records.
func (r *Reader) LookupOffset(ipAddress net.IP) (uintptr, error) {
pointer, err := r.lookupPointer(ipAddress)
if pointer == 0 || err != nil {
return NotFound, err
}
return r.resolveDataPointer(pointer)
}
// Decode the record at |offset| into |result|. The result value pointed to
// must be a data value that corresponds to a record in the database. This may
// include a struct representation of the data, a map capable of holding the
// data or an empty interface{} value.
// //
// If result is a pointer to a struct, the struct need not include a field // If result is a pointer to a struct, the struct need not include a field
// for every value that may be in the database. If a field is not present in // for every value that may be in the database. If a field is not present in
// the structure, the decoder will not decode that field, reducing the time // the structure, the decoder will not decode that field, reducing the time
// required to decode the record. // required to decode the record.
// //
// As a special case, a struct field of type uintptr will be used to capture // Currently the decoder expect most data types to correspond exactly (e.g.,
// the offset of the value. Decode may later be used to extract the stored // a uint64 database type must be decoded into a uint64 Go type). In the
// value from the offset. MaxMind DBs are highly normalized: for example in // future, this may be made more flexible.
// the City database, all records of the same country will reference a func (r *Reader) Lookup(ipAddress net.IP, result interface{}) error {
// single representative record for that country. This uintptr behavior allows
// clients to leverage this normalization in their own sub-record caching.
func (r *Reader) Decode(offset uintptr, result interface{}) error {
rv := reflect.ValueOf(result)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return errors.New("result param must be a pointer")
}
_, err := r.decoder.decode(uint(offset), reflect.ValueOf(result), 0)
return err
}
func (r *Reader) lookupPointer(ipAddress net.IP) (uint, error) {
if ipAddress == nil { if ipAddress == nil {
return 0, errors.New("ipAddress passed to Lookup cannot be nil") return errors.New("ipAddress passed to Lookup cannot be nil")
} }
ipV4Address := ipAddress.To4() ipV4Address := ipAddress.To4()
...@@ -163,10 +143,20 @@ func (r *Reader) lookupPointer(ipAddress net.IP) (uint, error) { ...@@ -163,10 +143,20 @@ func (r *Reader) lookupPointer(ipAddress net.IP) (uint, error) {
ipAddress = ipV4Address ipAddress = ipV4Address
} }
if len(ipAddress) == 16 && r.Metadata.IPVersion == 4 { if len(ipAddress) == 16 && r.Metadata.IPVersion == 4 {
return 0, fmt.Errorf("error looking up '%s': you attempted to look up an IPv6 address in an IPv4-only database", ipAddress.String()) return fmt.Errorf("error looking up '%s': you attempted to look up an IPv6 address in an IPv4-only database", ipAddress.String())
} }
return r.findAddressInTree(ipAddress) pointer, err := r.findAddressInTree(ipAddress)
if pointer == 0 {
return err
}
rv := reflect.ValueOf(result)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return errors.New("result param for Lookup must be a pointer")
}
return r.resolveDataPointer(pointer, rv)
} }
func (r *Reader) findAddressInTree(ipAddress net.IP) (uint, error) { func (r *Reader) findAddressInTree(ipAddress net.IP) (uint, error) {
...@@ -196,7 +186,7 @@ func (r *Reader) findAddressInTree(ipAddress net.IP) (uint, error) { ...@@ -196,7 +186,7 @@ func (r *Reader) findAddressInTree(ipAddress net.IP) (uint, error) {
return node, nil return node, nil
} }
return 0, newInvalidDatabaseError("invalid node in search tree") return 0, errors.New("invalid node in search tree")
} }
func (r *Reader) readNode(nodeNumber uint, index uint) (uint, error) { func (r *Reader) readNode(nodeNumber uint, index uint) (uint, error) {
...@@ -205,13 +195,13 @@ func (r *Reader) readNode(nodeNumber uint, index uint) (uint, error) { ...@@ -205,13 +195,13 @@ func (r *Reader) readNode(nodeNumber uint, index uint) (uint, error) {
baseOffset := nodeNumber * RecordSize / 4 baseOffset := nodeNumber * RecordSize / 4
var nodeBytes []byte var nodeBytes []byte
var prefix uint var prefix uint64
switch RecordSize { switch RecordSize {
case 24: case 24:
offset := baseOffset + index*3 offset := baseOffset + index*3
nodeBytes = r.buffer[offset : offset+3] nodeBytes = r.buffer[offset : offset+3]
case 28: case 28:
prefix = uint(r.buffer[baseOffset+3]) prefix = uint64(r.buffer[baseOffset+3])
if index != 0 { if index != 0 {
prefix &= 0x0F prefix &= 0x0F
} else { } else {
...@@ -223,24 +213,31 @@ func (r *Reader) readNode(nodeNumber uint, index uint) (uint, error) { ...@@ -223,24 +213,31 @@ func (r *Reader) readNode(nodeNumber uint, index uint) (uint, error) {
offset := baseOffset + index*4 offset := baseOffset + index*4
nodeBytes = r.buffer[offset : offset+4] nodeBytes = r.buffer[offset : offset+4]
default: default:
return 0, newInvalidDatabaseError("unknown record size: %d", RecordSize) return 0, fmt.Errorf("unknown record size: %d", RecordSize)
} }
return uintFromBytes(prefix, nodeBytes), nil return uint(uintFromBytes(prefix, nodeBytes)), nil
} }
func (r *Reader) retrieveData(pointer uint, result interface{}) error { func (r *Reader) resolveDataPointer(pointer uint, result reflect.Value) error {
offset, err := r.resolveDataPointer(pointer) nodeCount := r.Metadata.NodeCount
if err != nil { searchTreeSize := r.Metadata.RecordSize * nodeCount / 4
return err
} resolved := pointer - nodeCount + searchTreeSize
return r.Decode(offset, result)
if resolved > uint(len(r.buffer)) {
return errors.New("the MaxMind DB file's search tree is corrupt")
} }
func (r *Reader) resolveDataPointer(pointer uint) (uintptr, error) { _, err := r.decoder.decode(resolved, result)
var resolved = uintptr(pointer - r.Metadata.NodeCount - dataSectionSeparatorSize) return err
}
if resolved > uintptr(len(r.buffer)) { // Close unmaps the database file from virtual memory and returns the
return 0, newInvalidDatabaseError("the MaxMind DB file's search tree is corrupt") // resources to the system. If called on a Reader opened using FromBytes,
// this method does nothing.
func (r *Reader) Close() {
if r.hasMappedFile {
munmap(r.buffer)
r.hasMappedFile = false
} }
return resolved, nil
} }
// +build appengine
package maxminddb
import "io/ioutil"
// Open takes a string path to a MaxMind DB file and returns a Reader
// structure or an error. The database file is opened using a memory map,
// except on Google App Engine where mmap is not supported; there the database
// is loaded into memory. Use the Close method on the Reader object to return
// the resources to the system.
func Open(file string) (*Reader, error) {
bytes, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
return FromBytes(bytes)
}
// Close unmaps the database file from virtual memory and returns the
// resources to the system. If called on a Reader opened using FromBytes
// or Open on Google App Engine, this method does nothing.
func (r *Reader) Close() error {
return nil
}
// +build !appengine
package maxminddb
import (
"os"
"runtime"
)
// Open takes a string path to a MaxMind DB file and returns a Reader
// structure or an error. The database file is opened using a memory map,
// except on Google App Engine where mmap is not supported; there the database
// is loaded into memory. Use the Close method on the Reader object to return
// the resources to the system.
func Open(file string) (*Reader, error) {
mapFile, err := os.Open(file)
if err != nil {
return nil, err
}
defer func() {
if rerr := mapFile.Close(); rerr != nil {
err = rerr
}
}()
stats, err := mapFile.Stat()
if err != nil {
return nil, err
}
fileSize := int(stats.Size())
mmap, err := mmap(int(mapFile.Fd()), fileSize)
if err != nil {
return nil, err
}
reader, err := FromBytes(mmap)
if err != nil {
if err2 := munmap(mmap); err2 != nil {
// failing to unmap the file is probably the more severe error
return nil, err2
}
return nil, err
}
reader.hasMappedFile = true
runtime.SetFinalizer(reader, (*Reader).Close)
return reader, err
}
// Close unmaps the database file from virtual memory and returns the
// resources to the system. If called on a Reader opened using FromBytes
// or Open on Google App Engine, this method does nothing.
func (r *Reader) Close() error {
if !r.hasMappedFile {
return nil
}
runtime.SetFinalizer(r, nil)
r.hasMappedFile = false
return munmap(r.buffer)
}
// +build !windows,!appengine // +build !windows
package maxminddb package maxminddb
import ( import (
"syscall" "syscall"
"golang.org/x/sys/unix"
) )
func mmap(fd int, length int) (data []byte, err error) { func mmap(fd int, length int) (data []byte, err error) {
return unix.Mmap(fd, 0, length, syscall.PROT_READ, syscall.MAP_SHARED) return syscall.Mmap(fd, 0, length, syscall.PROT_READ, syscall.MAP_SHARED)
} }
func munmap(b []byte) (err error) { func munmap(b []byte) (err error) {
return unix.Munmap(b) return syscall.Munmap(b)
} }
// +build windows,!appengine
package maxminddb
// Windows support largely borrowed from mmap-go. // Windows support largely borrowed from mmap-go.
// //
// Copyright 2011 Evan Shaw. All rights reserved. // Copyright 2011 Evan Shaw. All rights reserved.
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package maxminddb
import ( import (
"errors" "errors"
"os" "os"
"reflect" "reflect"
"sync" "sync"
"syscall"
"unsafe" "unsafe"
"golang.org/x/sys/windows"
) )
type memoryMap []byte type MMap []byte
// Windows // Windows
var handleLock sync.Mutex var handleLock sync.Mutex
var handleMap = map[uintptr]windows.Handle{} var handleMap = map[uintptr]syscall.Handle{}
func mmap(fd int, length int) (data []byte, err error) { func mmap(fd int, length int) (data []byte, err error) {
h, errno := windows.CreateFileMapping(windows.Handle(fd), nil, h, errno := syscall.CreateFileMapping(syscall.Handle(fd), nil,
uint32(windows.PAGE_READONLY), 0, uint32(length), nil) uint32(syscall.PAGE_READONLY), 0, uint32(length), nil)
if h == 0 { if h == 0 {
return nil, os.NewSyscallError("CreateFileMapping", errno) return nil, os.NewSyscallError("CreateFileMapping", errno)
} }
addr, errno := windows.MapViewOfFile(h, uint32(windows.FILE_MAP_READ), 0, addr, errno := syscall.MapViewOfFile(h, uint32(syscall.FILE_MAP_READ), 0,
0, uintptr(length)) 0, uintptr(length))
if addr == 0 { if addr == 0 {
return nil, os.NewSyscallError("MapViewOfFile", errno) return nil, os.NewSyscallError("MapViewOfFile", errno)
...@@ -40,7 +36,7 @@ func mmap(fd int, length int) (data []byte, err error) { ...@@ -40,7 +36,7 @@ func mmap(fd int, length int) (data []byte, err error) {
handleMap[addr] = h handleMap[addr] = h
handleLock.Unlock() handleLock.Unlock()
m := memoryMap{} m := MMap{}
dh := m.header() dh := m.header()
dh.Data = addr dh.Data = addr
dh.Len = length dh.Len = length
...@@ -49,24 +45,24 @@ func mmap(fd int, length int) (data []byte, err error) { ...@@ -49,24 +45,24 @@ func mmap(fd int, length int) (data []byte, err error) {
return m, nil return m, nil
} }
func (m *memoryMap) header() *reflect.SliceHeader { func (m *MMap) header() *reflect.SliceHeader {
return (*reflect.SliceHeader)(unsafe.Pointer(m)) return (*reflect.SliceHeader)(unsafe.Pointer(m))
} }
func flush(addr, len uintptr) error { func flush(addr, len uintptr) error {
errno := windows.FlushViewOfFile(addr, len) errno := syscall.FlushViewOfFile(addr, len)
return os.NewSyscallError("FlushViewOfFile", errno) return os.NewSyscallError("FlushViewOfFile", errno)
} }
func munmap(b []byte) (err error) { func munmap(b []byte) (err error) {
m := memoryMap(b) m := MMap(b)
dh := m.header() dh := m.header()
addr := dh.Data addr := dh.Data
length := uintptr(dh.Len) length := uintptr(dh.Len)
flush(addr, length) flush(addr, length)
err = windows.UnmapViewOfFile(addr) err = syscall.UnmapViewOfFile(addr)
if err != nil { if err != nil {
return err return err
} }
...@@ -80,6 +76,6 @@ func munmap(b []byte) (err error) { ...@@ -80,6 +76,6 @@ func munmap(b []byte) (err error) {
} }
delete(handleMap, addr) delete(handleMap, addr)
e := windows.CloseHandle(windows.Handle(handle)) e := syscall.CloseHandle(syscall.Handle(handle))
return os.NewSyscallError("CloseHandle", e) return os.NewSyscallError("CloseHandle", e)
} }
package maxminddb
import "net"
// Internal structure used to keep track of nodes we still need to visit.
type netNode struct {
ip net.IP
bit uint
pointer uint
}
// Networks represents a set of subnets that we are iterating over.
type Networks struct {
reader *Reader
nodes []netNode // Nodes we still have to visit.
lastNode netNode
err error
}
// Networks returns an iterator that can be used to traverse all networks in
// the database.
//
// Please note that a MaxMind DB may map IPv4 networks into several locations
// in in an IPv6 database. This iterator will iterate over all of these
// locations separately.
func (r *Reader) Networks() *Networks {
s := 4
if r.Metadata.IPVersion == 6 {
s = 16
}
return &Networks{
reader: r,
nodes: []netNode{
{
ip: make(net.IP, s),
},
},
}
}
// Next prepares the next network for reading with the Network method. It
// returns true if there is another network to be processed and false if there
// are no more networks or if there is an error.
func (n *Networks) Next() bool {
for len(n.nodes) > 0 {
node := n.nodes[len(n.nodes)-1]
n.nodes = n.nodes[:len(n.nodes)-1]
for {
if node.pointer < n.reader.Metadata.NodeCount {
ipRight := make(net.IP, len(node.ip))
copy(ipRight, node.ip)
if len(ipRight) <= int(node.bit>>3) {
n.err = newInvalidDatabaseError(
"invalid search tree at %v/%v", ipRight, node.bit)
return false
}
ipRight[node.bit>>3] |= 1 << (7 - (node.bit % 8))
rightPointer, err := n.reader.readNode(node.pointer, 1)
if err != nil {
n.err = err
return false
}
node.bit++
n.nodes = append(n.nodes, netNode{
pointer: rightPointer,
ip: ipRight,
bit: node.bit,
})
node.pointer, err = n.reader.readNode(node.pointer, 0)
if err != nil {
n.err = err
return false
}
} else if node.pointer > n.reader.Metadata.NodeCount {
n.lastNode = node
return true
} else {
break
}
}
}
return false
}
// Network returns the current network or an error if there is a problem
// decoding the data for the network. It takes a pointer to a result value to
// decode the network's data into.
func (n *Networks) Network(result interface{}) (*net.IPNet, error) {
if err := n.reader.retrieveData(n.lastNode.pointer, result); err != nil {
return nil, err
}
return &net.IPNet{
IP: n.lastNode.ip,
Mask: net.CIDRMask(int(n.lastNode.bit), len(n.lastNode.ip)*8),
}, nil
}
// Err returns an error, if any, that was encountered during iteration.
func (n *Networks) Err() error {
return n.err
}
package maxminddb
import "reflect"
type verifier struct {
reader *Reader
}
// Verify checks that the database is valid. It validates the search tree,
// the data section, and the metadata section. This verifier is stricter than
// the specification and may return errors on databases that are readable.
func (r *Reader) Verify() error {
v := verifier{r}
if err := v.verifyMetadata(); err != nil {
return err
}
return v.verifyDatabase()
}
func (v *verifier) verifyMetadata() error {
metadata := v.reader.Metadata
if metadata.BinaryFormatMajorVersion != 2 {
return testError(
"binary_format_major_version",
2,
metadata.BinaryFormatMajorVersion,
)
}
if metadata.BinaryFormatMinorVersion != 0 {
return testError(
"binary_format_minor_version",
0,
metadata.BinaryFormatMinorVersion,
)
}
if metadata.DatabaseType == "" {
return testError(
"database_type",
"non-empty string",
metadata.DatabaseType,
)
}
if len(metadata.Description) == 0 {
return testError(
"description",
"non-empty slice",
metadata.Description,
)
}
if metadata.IPVersion != 4 && metadata.IPVersion != 6 {
return testError(
"ip_version",
"4 or 6",
metadata.IPVersion,
)
}
if metadata.RecordSize != 24 &&
metadata.RecordSize != 28 &&
metadata.RecordSize != 32 {
return testError(
"record_size",
"24, 28, or 32",
metadata.RecordSize,
)
}
if metadata.NodeCount == 0 {
return testError(
"node_count",
"positive integer",
metadata.NodeCount,
)
}
return nil
}
func (v *verifier) verifyDatabase() error {
offsets, err := v.verifySearchTree()
if err != nil {
return err
}
if err := v.verifyDataSectionSeparator(); err != nil {
return err
}
return v.verifyDataSection(offsets)
}
func (v *verifier) verifySearchTree() (map[uint]bool, error) {
offsets := make(map[uint]bool)
it := v.reader.Networks()
for it.Next() {
offset, err := v.reader.resolveDataPointer(it.lastNode.pointer)
if err != nil {
return nil, err
}
offsets[uint(offset)] = true
}
if err := it.Err(); err != nil {
return nil, err
}
return offsets, nil
}
func (v *verifier) verifyDataSectionSeparator() error {
separatorStart := v.reader.Metadata.NodeCount * v.reader.Metadata.RecordSize / 4
separator := v.reader.buffer[separatorStart : separatorStart+dataSectionSeparatorSize]
for _, b := range separator {
if b != 0 {
return newInvalidDatabaseError("unexpected byte in data separator: %v", separator)
}
}
return nil
}
func (v *verifier) verifyDataSection(offsets map[uint]bool) error {
pointerCount := len(offsets)
decoder := v.reader.decoder
var offset uint
bufferLen := uint(len(decoder.buffer))
for offset < bufferLen {
var data interface{}
rv := reflect.ValueOf(&data)
newOffset, err := decoder.decode(offset, rv, 0)
if err != nil {
return newInvalidDatabaseError("received decoding error (%v) at offset of %v", err, offset)
}
if newOffset <= offset {
return newInvalidDatabaseError("data section offset unexpectedly went from %v to %v", offset, newOffset)
}
pointer := offset
if _, ok := offsets[pointer]; ok {
delete(offsets, pointer)
} else {
return newInvalidDatabaseError("found data (%v) at %v that the search tree does not point to", data, pointer)
}
offset = newOffset
}
if offset != bufferLen {
return newInvalidDatabaseError(
"unexpected data at the end of the data section (last offset: %v, end: %v)",
offset,
bufferLen,
)
}
if len(offsets) != 0 {
return newInvalidDatabaseError(
"found %v pointers (of %v) in the search tree that we did not see in the data section",
len(offsets),
pointerCount,
)
}
return nil
}
func testError(
field string,
expected interface{},
actual interface{},
) error {
return newInvalidDatabaseError(
"%v - Expected: %v Actual: %v",
field,
expected,
actual,
)
}
...@@ -72,7 +72,7 @@ github.com/openzipkin/zipkin-go/model ...@@ -72,7 +72,7 @@ github.com/openzipkin/zipkin-go/model
github.com/openzipkin/zipkin-go/propagation github.com/openzipkin/zipkin-go/propagation
github.com/openzipkin/zipkin-go/reporter github.com/openzipkin/zipkin-go/reporter
github.com/openzipkin/zipkin-go/reporter/http github.com/openzipkin/zipkin-go/reporter/http
# github.com/oschwald/maxminddb-golang v0.0.0-20170901134056-26fe5ace1c70 # github.com/oschwald/maxminddb-golang v0.2.0
## explicit ## explicit
github.com/oschwald/maxminddb-golang github.com/oschwald/maxminddb-golang
# github.com/pkg/errors v0.9.1 # github.com/pkg/errors v0.9.1
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment