Browse Source

Guess the geoip2 directory if it's not explicitly configured

Ask Bjørn Hansen 7 years ago
parent
commit
06a1091924
4 changed files with 30 additions and 3 deletions
  1. 6 1
      config.go
  2. 3 2
      dns/geodns.conf.sample
  3. 19 0
      targeting/geoip2/geoip2.go
  4. 2 0
      targeting/targeting.go

+ 6 - 1
config.go

@@ -7,6 +7,8 @@ import (
 	"sync"
 	"sync"
 	"time"
 	"time"
 
 
+	"github.com/abh/geodns/targeting/geoip2"
+
 	"gopkg.in/fsnotify.v1"
 	"gopkg.in/fsnotify.v1"
 	gcfg "gopkg.in/gcfg.v1"
 	gcfg "gopkg.in/gcfg.v1"
 )
 )
@@ -64,7 +66,10 @@ func (conf *AppConfig) StatHatApiKey() string {
 func (conf *AppConfig) GeoIPDirectory() string {
 func (conf *AppConfig) GeoIPDirectory() string {
 	cfgMutex.RLock()
 	cfgMutex.RLock()
 	defer cfgMutex.RUnlock()
 	defer cfgMutex.RUnlock()
-	return conf.GeoIP.Directory
+	if len(conf.GeoIP.Directory) > 0 {
+		return conf.GeoIP.Directory
+	}
+	return geoip2.FindDB()
 }
 }
 
 
 func configWatcher(fileName string) {
 func configWatcher(fileName string) {

+ 3 - 2
dns/geodns.conf.sample

@@ -4,9 +4,10 @@
 ; with your .json zone files.
 ; with your .json zone files.
 
 
 [geoip]
 [geoip]
-;; Directory containing the GeoIP .dat database files
+;; Directory containing the GeoIP .dat database files; defaults
+;; to looking through a list of directories looking for one that
+;; exists.
 ;directory=/usr/local/share/GeoIP/
 ;directory=/usr/local/share/GeoIP/
-directory=/usr/local/share/GeoIP/
 
 
 [querylog]
 [querylog]
 ;; directory to save query logs; disabled if not specified
 ;; directory to save query logs; disabled if not specified

+ 19 - 0
targeting/geoip2/geoip2.go

@@ -39,7 +39,26 @@ func init() {
 		asnDB:     []string{"GeoIP2-ISP.mmdb"},
 		asnDB:     []string{"GeoIP2-ISP.mmdb"},
 		cityDB:    []string{"GeoIP2-City.mmdb", "GeoLite2-City.mmdb"},
 		cityDB:    []string{"GeoIP2-City.mmdb", "GeoLite2-City.mmdb"},
 	}
 	}
+}
 
 
+func FindDB() string {
+	dirs := []string{
+		"/usr/share/GeoIP/",       // Linux default
+		"/usr/share/local/GeoIP/", // source install?
+		"/usr/local/share/GeoIP/", // FreeBSD
+		"/opt/local/share/GeoIP/", // MacPorts
+		"/usr/share/GeoIP/",       // ArchLinux
+	}
+	for _, dir := range dirs {
+		if _, err := os.Stat(dir); err != nil {
+			if os.IsExist(err) {
+				log.Println(err)
+			}
+			continue
+		}
+		return dir
+	}
+	return ""
 }
 }
 
 
 func (g *g2) open(t geoType, db string) (*geoip2.Reader, error) {
 func (g *g2) open(t geoType, db string) (*geoip2.Reader, error) {

+ 2 - 0
targeting/targeting.go

@@ -29,11 +29,13 @@ func init() {
 
 
 var g geo.Provider
 var g geo.Provider
 
 
+// Setup sets the global geo provider
 func Setup(gn geo.Provider) error {
 func Setup(gn geo.Provider) error {
 	g = gn
 	g = gn
 	return nil
 	return nil
 }
 }
 
 
+// Geo returns the global geo provider
 func Geo() geo.Provider {
 func Geo() geo.Provider {
 	return g
 	return g
 }
 }