// Copyright (c) 2018 LEAP Encryption Access Project
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"github.com/StefanSchroeder/Golang-Ellipsoid/ellipsoid"
"github.com/hongshibao/go-kdtree"
"github.com/oschwald/geoip2-golang"
"github.com/tidwall/cities"
)
func floatToString(num float64) string {
return strconv.FormatFloat(num, 'f', 6, 64)
}
func getRemoteIP(req *http.Request) string {
forward := req.Header.Get("X-Forwarded-For")
ipstr := ""
if forward != "" {
ipstr = forward
} else {
ip, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
log.Fatal(err)
}
netIP := net.ParseIP(ip)
ipstr = netIP.String()
}
return ipstr
}
type geodb struct {
db *geoip2.Reader
Gateways []gateway
GatewayTree *kdtree.KDTree
GatewayMap map[[3]float64][]gateway
earth *ellipsoid.Ellipsoid
}
func (g *geodb) getPointForLocation(lat float64, lon float64) *EuclideanPoint {
x, y, z := g.earth.ToECEF(lat, lon, 0)
p := NewEuclideanPoint(x, y, z)
return p
}
func (g *geodb) sortGateways(lat float64, lon float64) []string {
ret := make([]string, 0)
t := g.getPointForLocation(lat, lon)
nn := g.GatewayTree.KNN(t, len(g.Gateways))
for i:= 0; i