echoip/api/api.go

297 lines
7.2 KiB
Go
Raw Normal View History

2015-09-17 20:57:27 +02:00
package api
import (
"encoding/json"
"fmt"
2016-04-15 20:14:16 +02:00
"html/template"
2015-09-17 20:57:27 +02:00
"io"
"log"
"net"
"net/http"
"path/filepath"
"regexp"
2016-04-15 20:52:15 +02:00
"strconv"
2015-09-17 20:57:27 +02:00
"strings"
2016-04-15 20:52:15 +02:00
"time"
2015-09-17 20:57:27 +02:00
"github.com/gorilla/mux"
geoip2 "github.com/oschwald/geoip2-golang"
)
2016-04-15 20:14:16 +02:00
const APPLICATION_JSON = "application/json"
2015-09-17 20:57:27 +02:00
2016-04-15 20:19:14 +02:00
var cliUserAgentExp = regexp.MustCompile(`^((curl|Wget|fetch\slibfetch|Go-http-client|HTTPie)\/.*|Go\s1\.1\spackage\shttp)$`)
2015-09-17 20:57:27 +02:00
type API struct {
2015-09-21 18:03:52 +02:00
CORS bool
Template string
2015-09-29 20:39:21 +02:00
lookupAddr func(string) ([]string, error)
lookupCountry func(net.IP) (string, error)
2016-04-15 20:52:15 +02:00
testPort func(net.IP, uint64) error
2015-09-29 20:39:21 +02:00
ipFromRequest func(*http.Request) (net.IP, error)
reverseLookup bool
countryLookup bool
portTesting bool
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:14:16 +02:00
type Response struct {
IP net.IP `json:"ip"`
Country string `json:"country,omitempty"`
Hostname string `json:"hostname,omitempty"`
}
2016-04-15 20:52:15 +02:00
type TestPortResponse struct {
IP net.IP `json:"ip"`
Port uint64 `json:"port"`
Reachable bool `json:"reachable"`
}
2015-09-29 20:39:21 +02:00
func New() *API {
return &API{
2016-04-15 20:14:16 +02:00
lookupAddr: func(addr string) (names []string, err error) { return nil, nil },
2015-09-29 20:39:21 +02:00
lookupCountry: func(ip net.IP) (string, error) { return "", nil },
2016-04-15 20:52:15 +02:00
testPort: func(ip net.IP, port uint64) error { return nil },
2015-09-29 20:39:21 +02:00
ipFromRequest: ipFromRequest,
}
}
2015-09-17 20:57:27 +02:00
2016-04-15 20:14:16 +02:00
func (a *API) EnableCountryLookup(filepath string) error {
2015-09-17 20:57:27 +02:00
db, err := geoip2.Open(filepath)
if err != nil {
2016-04-15 20:14:16 +02:00
return err
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:14:16 +02:00
a.lookupCountry = func(ip net.IP) (string, error) {
2015-09-29 20:39:21 +02:00
return lookupCountry(db, ip)
}
a.countryLookup = true
2016-04-15 20:14:16 +02:00
return nil
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:14:16 +02:00
func (a *API) EnableReverseLookup() {
a.lookupAddr = net.LookupAddr
a.reverseLookup = true
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:52:15 +02:00
func (a *API) EnablePortTesting() {
a.testPort = testPort
a.portTesting = true
2016-04-15 20:52:15 +02:00
}
2015-09-17 20:57:27 +02:00
func ipFromRequest(r *http.Request) (net.IP, error) {
var host string
realIP := r.Header.Get("X-Real-IP")
var err error
if realIP != "" {
host = realIP
} else {
host, _, err = net.SplitHostPort(r.RemoteAddr)
if err != nil {
return nil, err
}
}
ip := net.ParseIP(host)
if ip == nil {
return nil, fmt.Errorf("could not parse IP: %s", host)
}
return ip, nil
}
2016-04-15 20:52:15 +02:00
func testPort(ip net.IP, port uint64) error {
address := fmt.Sprintf("%s:%d", ip, port)
if _, err := net.DialTimeout("tcp", address, 2*time.Second); err != nil {
return err
}
return nil
}
2015-09-29 20:39:21 +02:00
func lookupCountry(db *geoip2.Reader, ip net.IP) (string, error) {
if db == nil {
2015-09-17 20:57:27 +02:00
return "", nil
}
2015-09-29 20:39:21 +02:00
record, err := db.Country(ip)
2015-09-17 20:57:27 +02:00
if err != nil {
return "", err
}
if country, exists := record.Country.Names["en"]; exists {
return country, nil
}
if country, exists := record.RegisteredCountry.Names["en"]; exists {
return country, nil
}
2016-04-15 20:14:16 +02:00
return "Unknown", fmt.Errorf("could not determine country for IP: %s", ip)
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:14:16 +02:00
func (a *API) newResponse(r *http.Request) (Response, error) {
ip, err := a.ipFromRequest(r)
2015-09-17 20:57:27 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
return Response{}, err
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:14:16 +02:00
country, err := a.lookupCountry(ip)
2015-09-17 20:57:27 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
log.Print(err)
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:14:16 +02:00
hostnames, err := a.lookupAddr(ip.String())
if err != nil {
log.Print(err)
}
return Response{
IP: ip,
Country: country,
Hostname: strings.Join(hostnames, " "),
}, nil
}
2015-09-17 20:57:27 +02:00
2016-04-15 20:14:16 +02:00
func (a *API) CLIHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := a.newResponse(r)
if err != nil {
2015-09-18 17:13:14 +02:00
return internalServerError(err)
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:14:16 +02:00
if r.URL.Path == "/country" {
io.WriteString(w, response.Country+"\n")
} else {
io.WriteString(w, response.IP.String()+"\n")
}
2015-09-18 17:13:14 +02:00
return nil
2015-09-17 20:57:27 +02:00
}
2015-09-18 17:13:14 +02:00
func (a *API) JSONHandler(w http.ResponseWriter, r *http.Request) *appError {
2016-04-15 20:14:16 +02:00
response, err := a.newResponse(r)
2015-09-18 17:13:14 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
return internalServerError(err).AsJSON()
2015-09-17 22:39:12 +02:00
}
2016-04-15 20:14:16 +02:00
b, err := json.Marshal(response)
2015-09-17 20:57:27 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
return internalServerError(err).AsJSON()
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:14:16 +02:00
w.Header().Set("Content-Type", APPLICATION_JSON)
2015-09-17 20:57:27 +02:00
w.Write(b)
2015-09-18 17:13:14 +02:00
return nil
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:52:15 +02:00
func (a *API) TestPortHandler(w http.ResponseWriter, r *http.Request) *appError {
vars := mux.Vars(r)
port, err := strconv.ParseUint(vars["port"], 10, 16)
if err != nil {
return badRequest(err).WithMessage("Invalid port: " + vars["port"]).AsJSON()
}
if port < 1 || port > 65355 {
return badRequest(nil).WithMessage("Invalid port: " + vars["port"]).AsJSON()
}
ip, err := a.ipFromRequest(r)
if err != nil {
return internalServerError(err).AsJSON()
}
err = testPort(ip, port)
response := TestPortResponse{
IP: ip,
Port: port,
Reachable: err == nil,
}
b, err := json.Marshal(response)
if err != nil {
return internalServerError(err).AsJSON()
}
w.Header().Set("Content-Type", APPLICATION_JSON)
w.Write(b)
return nil
}
2016-04-15 20:14:16 +02:00
func (a *API) DefaultHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := a.newResponse(r)
2015-09-18 17:42:43 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
return internalServerError(err)
2015-09-18 17:42:43 +02:00
}
2016-04-15 20:14:16 +02:00
t, err := template.New(filepath.Base(a.Template)).ParseFiles(a.Template)
2015-09-18 17:13:14 +02:00
if err != nil {
2016-04-15 20:14:16 +02:00
return internalServerError(err)
2015-09-17 22:39:12 +02:00
}
var data = struct {
Response
ReverseLookup bool
CountryLookup bool
PortTesting bool
}{response, a.reverseLookup, a.countryLookup, a.portTesting}
if err := t.Execute(w, &data); err != nil {
2016-04-15 20:14:16 +02:00
return internalServerError(err)
2015-09-17 20:57:27 +02:00
}
2015-09-18 17:13:14 +02:00
return nil
2015-09-17 20:57:27 +02:00
}
2016-04-15 20:14:16 +02:00
func (a *API) NotFoundHandler(w http.ResponseWriter, r *http.Request) *appError {
err := notFound(nil).WithMessage("404 page not found")
if r.Header.Get("accept") == APPLICATION_JSON {
err = err.AsJSON()
}
return err
}
2015-09-17 20:57:27 +02:00
func cliMatcher(r *http.Request, rm *mux.RouteMatch) bool {
return cliUserAgentExp.MatchString(r.UserAgent())
}
func (a *API) requestFilter(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if a.CORS {
w.Header().Set("Access-Control-Allow-Methods", "GET")
w.Header().Set("Access-Control-Allow-Origin", "*")
}
next.ServeHTTP(w, r)
})
}
2015-09-18 17:13:14 +02:00
type appHandler func(http.ResponseWriter, *http.Request) *appError
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if e := fn(w, r); e != nil { // e is *appError
if e.Error != nil {
log.Print(e.Error)
}
2016-04-15 20:14:16 +02:00
// When Content-Type for error is JSON, we need to marshal the response into JSON
2015-09-18 17:13:14 +02:00
if e.IsJSON() {
var data = struct {
Error string `json:"error"`
2016-04-15 20:14:16 +02:00
}{e.Message}
b, err := json.Marshal(data)
2015-09-18 17:13:14 +02:00
if err != nil {
panic(err)
}
2016-04-15 20:14:16 +02:00
e.Message = string(b)
}
// Set Content-Type of response if set in error
if e.ContentType != "" {
w.Header().Set("Content-Type", e.ContentType)
2015-09-18 17:13:14 +02:00
}
w.WriteHeader(e.Code)
2016-04-15 20:14:16 +02:00
io.WriteString(w, e.Message)
2015-09-18 17:13:14 +02:00
}
}
2015-09-17 20:57:27 +02:00
func (a *API) Handlers() http.Handler {
r := mux.NewRouter()
// JSON
2015-09-18 17:13:14 +02:00
r.Handle("/", appHandler(a.JSONHandler)).Methods("GET").Headers("Accept", APPLICATION_JSON)
2015-09-17 20:57:27 +02:00
// CLI
2015-09-18 17:13:14 +02:00
r.Handle("/", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher)
2016-04-15 20:14:16 +02:00
r.Handle("/ip", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher)
r.Handle("/country", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher)
2015-09-17 20:57:27 +02:00
2016-04-15 20:14:16 +02:00
// Browser
2015-09-18 17:13:14 +02:00
r.Handle("/", appHandler(a.DefaultHandler)).Methods("GET")
2015-09-17 20:57:27 +02:00
2016-04-15 20:52:15 +02:00
// Port testing
r.Handle("/port/{port:[0-9]+}", appHandler(a.TestPortHandler)).Methods("GET")
2016-04-15 20:14:16 +02:00
// Not found handler which returns JSON when appropriate
r.NotFoundHandler = appHandler(a.NotFoundHandler)
2015-09-17 20:57:27 +02:00
// Pass all requests through the request filter
return a.requestFilter(r)
}
func (a *API) ListenAndServe(addr string) error {
http.Handle("/", a.Handlers())
return http.ListenAndServe(addr, nil)
}