Skip to content

Commit 77acebd

Browse files
committed
Handle error conditions better in NetworksWithin
Previously, NetworksWithin would allow you to look up an IPv6 network in an IPv4 database. In this case it would return invalid data. As the method doesn't have an error return value, it will now return a Networks with Err() set. When the Networks has an error, iteration will stop and the Network call will fail.
1 parent 2d469b6 commit 77acebd

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

traverse.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package maxminddb
22

33
import (
4+
"fmt"
45
"net"
56
)
67

@@ -51,6 +52,15 @@ func (r *Reader) Networks() *Networks {
5152
// If the provided network is contained within a network in the database, the
5253
// iterator will iterate over exactly one network, the containing network.
5354
func (r *Reader) NetworksWithin(network *net.IPNet) *Networks {
55+
if r.Metadata.IPVersion == 4 && network.IP.To4() == nil {
56+
return &Networks{
57+
err: fmt.Errorf(
58+
"error getting networks with '%s': you attempted to use an IPv6 network in an IPv4-only database",
59+
network.String(),
60+
),
61+
}
62+
}
63+
5464
ip := network.IP
5565
prefixLength, _ := network.Mask.Size()
5666

@@ -76,6 +86,9 @@ func (r *Reader) NetworksWithin(network *net.IPNet) *Networks {
7686
// returns true if there is another network to be processed and false if there
7787
// are no more networks or if there is an error.
7888
func (n *Networks) Next() bool {
89+
if n.err != nil {
90+
return false
91+
}
7992
for len(n.nodes) > 0 {
8093
node := n.nodes[len(n.nodes)-1]
8194
n.nodes = n.nodes[:len(n.nodes)-1]
@@ -115,6 +128,9 @@ func (n *Networks) Next() bool {
115128
// decoding the data for the network. It takes a pointer to a result value to
116129
// decode the network's data into.
117130
func (n *Networks) Network(result interface{}) (*net.IPNet, error) {
131+
if n.err != nil {
132+
return nil, n.err
133+
}
118134
if err := n.reader.retrieveData(n.lastNode.pointer, result); err != nil {
119135
return nil, err
120136
}

traverse_test.go

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -152,22 +152,17 @@ var tests = []networkTest{
152152
},
153153
},
154154
{
155-
Network: "::/0",
156-
Database: "ipv4",
155+
Network: "1.1.1.16/28",
156+
Database: "mixed",
157157
Expected: []string{
158-
"101:101::/32",
159-
"101:102::/31",
160-
"101:104::/30",
161-
"101:108::/29",
162-
"101:110::/28",
163-
"101:120::/32",
158+
"1.1.1.16/28",
164159
},
165160
},
166161
{
167-
Network: "101:104::/30",
162+
Network: "1.1.1.4/30",
168163
Database: "ipv4",
169164
Expected: []string{
170-
"101:104::/30",
165+
"1.1.1.4/30",
171166
},
172167
},
173168
}

0 commit comments

Comments
 (0)