-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathgeoip.go
218 lines (187 loc) · 7.08 KB
/
geoip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package caddywaf
import (
"fmt"
"net"
"strings"
"sync"
"time"
"github.com/oschwald/maxminddb-golang"
"go.uber.org/zap"
)
// GeoIPHandler struct
type GeoIPHandler struct {
logger *zap.Logger
geoIPCache map[string]GeoIPRecord
geoIPCacheMutex sync.RWMutex
geoIPCacheTTL time.Duration // Configurable TTL for cache
geoIPLookupFallbackBehavior string // "default", "none", or a specific country code
}
// NewGeoIPHandler creates a new GeoIPHandler with a given logger
func NewGeoIPHandler(logger *zap.Logger) *GeoIPHandler {
if logger == nil {
logger = zap.NewNop()
}
return &GeoIPHandler{logger: logger}
}
// WithGeoIPCache enables GeoIP lookup caching.
func (gh *GeoIPHandler) WithGeoIPCache(ttl time.Duration) {
gh.geoIPCache = make(map[string]GeoIPRecord)
gh.geoIPCacheTTL = ttl
}
// WithGeoIPLookupFallbackBehavior configures the fallback behavior for GeoIP lookups.
func (gh *GeoIPHandler) WithGeoIPLookupFallbackBehavior(behavior string) {
gh.geoIPLookupFallbackBehavior = behavior
}
// LoadGeoIPDatabase opens the geoip database
func (gh *GeoIPHandler) LoadGeoIPDatabase(path string) (*maxminddb.Reader, error) {
if path == "" {
gh.logger.Error("No GeoIP database path specified")
return nil, fmt.Errorf("no GeoIP database path specified")
}
gh.logger.Debug("Loading GeoIP database", zap.String("path", path))
reader, err := maxminddb.Open(path)
if err != nil {
gh.logger.Error("Failed to load GeoIP database", zap.String("path", path), zap.Error(err))
return nil, fmt.Errorf("failed to load GeoIP database: %w", err)
}
gh.logger.Info("GeoIP database loaded", zap.String("path", path))
return reader, nil
}
// IsCountryInList checks if an IP belongs to a list of countries
func (gh *GeoIPHandler) IsCountryInList(remoteAddr string, countryList []string, geoIP *maxminddb.Reader) (bool, error) {
if geoIP == nil {
return false, fmt.Errorf("geoip database not loaded")
}
ip, err := gh.extractIPFromRemoteAddr(remoteAddr)
if err != nil {
gh.logger.Debug("Failed to extract IP from remote address", zap.String("remote_addr", remoteAddr), zap.Error(err))
return false, err
}
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
gh.logger.Debug("Invalid IP address", zap.String("ip", ip))
return false, fmt.Errorf("invalid IP address: %s", ip)
}
return gh.isCountryInListWithCache(ip, parsedIP, countryList, geoIP)
}
// getCountryCode extracts the country code for logging purposes
func (gh *GeoIPHandler) GetCountryCode(remoteAddr string, geoIP *maxminddb.Reader) string {
if geoIP == nil {
gh.logger.Error("GeoIP database not loaded for GetCountryCode")
return "N/A"
}
ip, err := gh.extractIPFromRemoteAddr(remoteAddr)
if err != nil {
gh.logger.Debug("Failed to extract IP from remote address for GetCountryCode", zap.String("remote_addr", remoteAddr), zap.Error(err))
return "N/A"
}
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
gh.logger.Debug("Invalid IP address for GetCountryCode", zap.String("ip", ip))
return "N/A"
}
return gh.getCountryCodeWithCache(ip, parsedIP, geoIP)
}
func (gh *GeoIPHandler) isCountryInListWithCache(ip string, parsedIP net.IP, countryList []string, geoIP *maxminddb.Reader) (bool, error) {
// Check cache first
if gh.geoIPCache != nil {
gh.geoIPCacheMutex.RLock()
if record, ok := gh.geoIPCache[ip]; ok {
gh.geoIPCacheMutex.RUnlock()
return gh.isCountryInRecord(record, countryList), nil
}
gh.geoIPCacheMutex.RUnlock()
}
var record GeoIPRecord
err := geoIP.Lookup(parsedIP, &record)
if err != nil {
gh.logger.Error("GeoIP lookup failed", zap.String("ip", ip), zap.Error(err))
return gh.handleGeoIPLookupError(err, countryList) // Helper function for error handling
}
// Cache the record
if gh.geoIPCache != nil {
gh.cacheGeoIPRecord(ip, record) // Helper function for caching
}
return gh.isCountryInRecord(record, countryList), nil // Helper function for country check
}
func (gh *GeoIPHandler) getCountryCodeWithCache(ip string, parsedIP net.IP, geoIP *maxminddb.Reader) string {
// Check cache first for GetCountryCode as well for consistency and potential perf gain
if gh.geoIPCache != nil {
gh.geoIPCacheMutex.RLock()
if record, ok := gh.geoIPCache[ip]; ok {
gh.geoIPCacheMutex.RUnlock()
return record.Country.ISOCode
}
gh.geoIPCacheMutex.RUnlock()
}
var record GeoIPRecord
err := geoIP.Lookup(parsedIP, &record)
if err != nil {
gh.logger.Debug("GeoIP lookup failed for getCountryCode", zap.String("ip", ip), zap.Error(err))
return "N/A"
}
// Cache the record for GetCountryCode as well
if gh.geoIPCache != nil {
gh.cacheGeoIPRecord(ip, record)
}
return record.Country.ISOCode
}
// extractIPFromRemoteAddr extracts the ip from remote address
func (gh *GeoIPHandler) extractIPFromRemoteAddr(remoteAddr string) (string, error) {
host, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
// If it's not in host:port format, assume it's just the IP
ip := net.ParseIP(remoteAddr)
if ip == nil {
return "", fmt.Errorf("invalid IP format: %s", remoteAddr)
}
return remoteAddr, nil
}
return host, nil
}
// Helper function to check if the country in the record is in the country list
func (gh *GeoIPHandler) isCountryInRecord(record GeoIPRecord, countryList []string) bool {
for _, country := range countryList {
if strings.EqualFold(record.Country.ISOCode, country) {
return true
}
}
return false
}
// Helper function to handle GeoIP lookup errors based on fallback behavior
func (gh *GeoIPHandler) handleGeoIPLookupError(err error, countryList []string) (bool, error) {
switch gh.geoIPLookupFallbackBehavior {
case "default":
// Log at debug level as it's a fallback scenario, not necessarily an error for the overall operation
gh.logger.Debug("GeoIP lookup failed, using default fallback (not in list)", zap.Error(err))
return false, nil // Treat as not in the list
case "none":
gh.logger.Debug("GeoIP lookup failed, using none fallback", zap.Error(err))
return false, fmt.Errorf("geoip lookup failed: %w", err) // Propagate the error
case "": // No fallback configured, maintain existing behavior
gh.logger.Debug("GeoIP lookup failed, no fallback defined", zap.Error(err))
return false, fmt.Errorf("geoip lookup failed: %w", err) // Propagate the error
default: // Configurable fallback country code
gh.logger.Debug("GeoIP lookup failed, using configured fallback", zap.String("fallbackCountry", gh.geoIPLookupFallbackBehavior), zap.Error(err))
for _, country := range countryList {
if strings.EqualFold(gh.geoIPLookupFallbackBehavior, country) {
return true, nil // Treat as in the list for the fallback country
}
}
return false, nil // Treat as not in the list if fallback country is not in the list
}
}
// Helper function to cache GeoIP record
func (gh *GeoIPHandler) cacheGeoIPRecord(ip string, record GeoIPRecord) {
gh.geoIPCacheMutex.Lock()
gh.geoIPCache[ip] = record
gh.geoIPCacheMutex.Unlock()
// Invalidate cache entry after TTL
if gh.geoIPCacheTTL > 0 {
time.AfterFunc(gh.geoIPCacheTTL, func() {
gh.geoIPCacheMutex.Lock()
delete(gh.geoIPCache, ip)
gh.geoIPCacheMutex.Unlock()
})
}
}