Skip to content
Snippets Groups Projects
ip.go 935 B
Newer Older
  • Learn to ignore specific revisions
  • ale's avatar
    ale committed
    package reportscollector
    
    import (
    
    ale's avatar
    ale committed
    	"net"
    	"net/http"
    
    	"os"
    	"sync"
    
    	geoip2 "github.com/oschwald/geoip2-golang"
    )
    
    var (
    	geoipDbPath = "/var/lib/GeoIP/GeoLite2-ASN.mmdb"
    	geodb       *geoip2.Reader
    	geodbInit   sync.Once
    
    ale's avatar
    ale committed
    )
    
    
    func initGeoIP() {
    	if s := os.Getenv("GEOIP_DB_PATH"); s != "" {
    		geoipDbPath = s
    	}
    
    	var err error
    	geodb, err = geoip2.Open(geoipDbPath)
    	if err != nil {
    		log.Printf("warning: could not open GeoIP db: %v", err)
    		return
    	}
    }
    
    func lookupASN(addr string) (string, bool) {
    	geodbInit.Do(initGeoIP)
    
    	if geodb != nil {
    		asn, err := geodb.ASN(net.ParseIP(addr))
    		if err == nil {
    			return fmt.Sprintf("AS%d", asn.AutonomousSystemNumber), true
    		}
    	}
    	return "", false
    }
    
    
    ale's avatar
    ale committed
    func getRemoteIP(req *http.Request) string {
    	if addr := req.Header.Get("X-Forwarded-For"); addr != "" {
    		return addr
    	}
    	if addr, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
    		return addr
    	}
    	return ""
    }