echoip/http/http.go

448 lines
11 KiB
Go
Raw Normal View History

2018-02-10 13:24:32 +01:00
package http
2015-09-17 20:57:27 +02:00
import (
"context"
2015-09-17 20:57:27 +02:00
"encoding/json"
"fmt"
2016-04-15 20:14:16 +02:00
"html/template"
2020-12-09 21:08:06 +01:00
"log"
2018-03-18 22:15:51 +01:00
"path/filepath"
"reflect"
2018-08-14 21:04:58 +02:00
"strings"
2016-08-13 20:32:19 +02:00
2020-09-05 22:07:35 +02:00
"net/http/pprof"
rcache "github.com/go-redis/cache/v9"
2023-10-10 21:52:05 +02:00
"github.com/golang-jwt/jwt"
"github.com/levelsoftware/echoip/cache"
2023-10-10 21:52:05 +02:00
"github.com/levelsoftware/echoip/config"
2023-10-05 17:43:02 +02:00
parser "github.com/levelsoftware/echoip/iputil/paser"
"github.com/levelsoftware/echoip/useragent"
2016-08-13 20:32:19 +02:00
2015-09-17 20:57:27 +02:00
"net"
"net/http"
2016-04-15 20:52:15 +02:00
"strconv"
2015-09-17 20:57:27 +02:00
)
const (
jsonMediaType = "application/json"
textMediaType = "text/plain"
)
2015-09-17 20:57:27 +02:00
2018-02-10 13:24:32 +01:00
type Server struct {
IPHeaders []string
2018-03-19 19:54:24 +01:00
LookupAddr func(net.IP) (string, error)
2018-02-11 11:19:50 +01:00
LookupPort func(net.IP, uint64) error
cache cache.Cache
2023-10-10 21:52:05 +02:00
runConfig *config.Config
parser parser.Parser
2015-09-17 20:57:27 +02:00
}
2016-04-27 17:07:53 +02:00
type PortResponse struct {
2016-04-15 20:52:15 +02:00
IP net.IP `json:"ip"`
Port uint64 `json:"port"`
Reachable bool `json:"reachable"`
}
2023-10-10 21:52:05 +02:00
func New(parser parser.Parser, cache cache.Cache, runConfig *config.Config) *Server {
return &Server{cache: cache, parser: parser, runConfig: runConfig}
2016-07-06 23:44:33 +02:00
}
2018-08-14 21:04:58 +02:00
func ipFromForwardedForHeader(v string) string {
2018-08-14 21:32:29 +02:00
sep := strings.Index(v, ",")
if sep == -1 {
return v
2018-08-14 21:04:58 +02:00
}
2018-08-14 21:32:29 +02:00
return v[:sep]
2018-08-14 21:04:58 +02:00
}
// ipFromRequest detects the IP address for this transaction.
//
// * `headers` - the specific HTTP headers to trust
// * `r` - the incoming HTTP request
// * `customIP` - whether to allow the IP to be pulled from query parameters
func ipFromRequest(headers []string, r *http.Request, customIP bool) (net.IP, error) {
remoteIP := ""
if customIP && r.URL != nil {
if v, ok := r.URL.Query()["ip"]; ok {
remoteIP = v[0]
2018-08-14 21:04:58 +02:00
}
}
if remoteIP == "" {
for _, header := range headers {
remoteIP = r.Header.Get(header)
if http.CanonicalHeaderKey(header) == "X-Forwarded-For" {
remoteIP = ipFromForwardedForHeader(remoteIP)
}
if remoteIP != "" {
break
}
}
}
2016-04-16 10:45:43 +02:00
if remoteIP == "" {
host, _, err := net.SplitHostPort(r.RemoteAddr)
2015-09-17 20:57:27 +02:00
if err != nil {
return nil, err
}
2016-04-16 10:45:43 +02:00
remoteIP = host
2015-09-17 20:57:27 +02:00
}
2016-04-16 10:45:43 +02:00
ip := net.ParseIP(remoteIP)
2015-09-17 20:57:27 +02:00
if ip == nil {
2016-04-16 10:45:43 +02:00
return nil, fmt.Errorf("could not parse IP: %s", remoteIP)
2015-09-17 20:57:27 +02:00
}
return ip, nil
}
2020-06-07 23:16:35 +02:00
func userAgentFromRequest(r *http.Request) *useragent.UserAgent {
var userAgent *useragent.UserAgent
userAgentRaw := r.UserAgent()
if userAgentRaw != "" {
parsed := useragent.Parse(userAgentRaw)
userAgent = &parsed
}
return userAgent
}
func (s *Server) newResponse(r *http.Request) (parser.Response, error) {
2023-10-10 21:52:05 +02:00
if err := handleAuth(r, s.runConfig); err != nil {
return parser.Response{}, err
}
ctx := context.Background()
ip, err := ipFromRequest(s.IPHeaders, r, true)
2015-09-17 20:57:27 +02:00
if err != nil {
return parser.Response{}, err
2015-09-17 20:57:27 +02:00
}
var cachedResponse cache.CachedResponse
if err := s.cache.Get(ctx, ip.String(), &cachedResponse); err != nil && err != rcache.ErrCacheMiss {
return parser.Response{}, err
}
if cachedResponse.IsSet() {
log.Printf("Return cached response for %s", ip.String())
return cachedResponse.Get(), nil
2019-12-25 21:04:26 +01:00
}
2018-03-19 19:54:24 +01:00
var hostname string
2018-02-11 11:19:50 +01:00
if s.LookupAddr != nil {
2018-03-19 19:54:24 +01:00
hostname, _ = s.LookupAddr(ip)
2016-04-15 20:14:16 +02:00
}
var response parser.Response
response, err = s.parser.Parse(ip, hostname)
log.Printf("Caching response for %s", ip.String())
2023-10-10 21:52:05 +02:00
if err := s.cache.Set(ctx, ip.String(), cachedResponse.Build(response), s.runConfig.CacheTtl); err != nil {
return parser.Response{}, err
}
response.UserAgent = userAgentFromRequest(r)
2020-09-05 22:07:35 +02:00
return response, nil
2016-04-15 20:14:16 +02:00
}
2015-09-17 20:57:27 +02:00
2018-02-10 13:24:32 +01:00
func (s *Server) newPortResponse(r *http.Request) (PortResponse, error) {
2018-03-18 22:15:51 +01:00
lastElement := filepath.Base(r.URL.Path)
port, err := strconv.ParseUint(lastElement, 10, 16)
if err != nil || port < 1 || port > 65535 {
return PortResponse{Port: port}, fmt.Errorf("invalid port: %s", lastElement)
2016-04-27 17:07:53 +02:00
}
ip, err := ipFromRequest(s.IPHeaders, r, false)
2016-04-27 17:07:53 +02:00
if err != nil {
return PortResponse{Port: port}, err
}
2018-02-11 11:19:50 +01:00
err = s.LookupPort(ip, port)
2016-04-27 17:07:53 +02:00
return PortResponse{
IP: ip,
Port: port,
Reachable: err == nil,
}, nil
}
2018-02-10 13:24:32 +01:00
func (s *Server) CLIHandler(w http.ResponseWriter, r *http.Request) *appError {
2023-10-10 21:52:05 +02:00
if err := handleAuth(r, s.runConfig); err != nil {
return badRequest(err).WithMessage(err.Error()).AsJSON()
}
ip, err := ipFromRequest(s.IPHeaders, r, true)
2016-04-15 20:14:16 +02:00
if err != nil {
return badRequest(err).WithMessage(err.Error()).AsJSON()
2015-09-17 20:57:27 +02:00
}
2017-05-28 19:20:02 +02:00
fmt.Fprintln(w, ip.String())
2016-04-16 09:18:21 +02:00
return nil
}
2018-02-10 13:24:32 +01:00
func (s *Server) CLICountryHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := s.newResponse(r)
2016-04-16 09:18:21 +02:00
if err != nil {
return badRequest(err).WithMessage(err.Error()).AsJSON()
2016-04-15 20:14:16 +02:00
}
2017-05-28 19:20:02 +02:00
fmt.Fprintln(w, response.Country)
2015-09-18 17:13:14 +02:00
return nil
2015-09-17 20:57:27 +02:00
}
2018-02-10 13:24:32 +01:00
func (s *Server) CLICountryISOHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := s.newResponse(r)
2018-02-09 20:41:30 +01:00
if err != nil {
return badRequest(err).WithMessage(err.Error()).AsJSON()
2018-02-09 20:41:30 +01:00
}
fmt.Fprintln(w, response.CountryISO)
return nil
}
2018-02-10 13:24:32 +01:00
func (s *Server) CLICityHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := s.newResponse(r)
2016-04-17 11:28:47 +02:00
if err != nil {
return badRequest(err).WithMessage(err.Error()).AsJSON()
2016-04-17 11:28:47 +02:00
}
2017-05-28 19:20:02 +02:00
fmt.Fprintln(w, response.City)
2016-04-17 11:28:47 +02:00
return nil
}
2018-06-15 09:29:13 +02:00
func (s *Server) CLICoordinatesHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := s.newResponse(r)
if err != nil {
return badRequest(err).WithMessage(err.Error()).AsJSON()
2018-06-15 09:29:13 +02:00
}
2018-08-27 21:48:08 +02:00
fmt.Fprintf(w, "%s,%s\n", formatCoordinate(response.Latitude), formatCoordinate(response.Longitude))
2018-06-15 09:29:13 +02:00
return nil
}
2019-07-05 15:01:45 +02:00
func (s *Server) CLIASNHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := s.newResponse(r)
if err != nil {
return badRequest(err).WithMessage(err.Error()).AsJSON()
2019-07-05 15:01:45 +02:00
}
fmt.Fprintf(w, "%s\n", response.ASN)
return nil
}
2022-09-04 00:06:01 +02:00
func (s *Server) CLIASNOrgHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := s.newResponse(r)
if err != nil {
return badRequest(err).WithMessage(err.Error()).AsJSON()
}
fmt.Fprintf(w, "%s\n", response.ASNOrg)
return nil
}
2018-02-10 13:24:32 +01:00
func (s *Server) JSONHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := s.newResponse(r)
2015-09-18 17:13:14 +02:00
if err != nil {
return badRequest(err).WithMessage(err.Error()).AsJSON()
2015-09-17 22:39:12 +02:00
}
b, err := json.MarshalIndent(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-05-26 21:38:10 +02:00
w.Header().Set("Content-Type", jsonMediaType)
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
}
2018-07-30 22:32:42 +02:00
func (s *Server) HealthHandler(w http.ResponseWriter, r *http.Request) *appError {
w.Header().Set("Content-Type", jsonMediaType)
w.Write([]byte(`{"status":"OK"}`))
return nil
}
2018-02-10 13:24:32 +01:00
func (s *Server) PortHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := s.newPortResponse(r)
2016-04-15 20:52:15 +02:00
if err != nil {
2019-01-16 22:16:05 +01:00
return badRequest(err).WithMessage(err.Error()).AsJSON()
2016-04-15 20:52:15 +02:00
}
b, err := json.MarshalIndent(response, "", " ")
2016-04-15 20:52:15 +02:00
if err != nil {
return internalServerError(err).AsJSON()
}
2016-05-26 21:38:10 +02:00
w.Header().Set("Content-Type", jsonMediaType)
2016-04-15 20:52:15 +02:00
w.Write(b)
return nil
}
2018-02-10 13:24:32 +01:00
func (s *Server) DefaultHandler(w http.ResponseWriter, r *http.Request) *appError {
response, err := s.newResponse(r)
2015-09-18 17:42:43 +02:00
if err != nil {
return badRequest(err).WithMessage(err.Error())
2015-09-18 17:42:43 +02:00
}
2023-10-10 21:52:05 +02:00
t, err := template.ParseGlob(s.runConfig.TemplateDir + "/*")
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
}
2023-10-10 21:52:05 +02:00
2018-02-10 14:35:12 +01:00
json, err := json.MarshalIndent(response, "", " ")
if err != nil {
return internalServerError(err)
}
2020-12-14 19:02:35 +01:00
var data = struct {
2023-09-23 03:28:49 +02:00
parser.Response
2018-10-28 16:42:17 +01:00
Host string
BoxLatTop float64
BoxLatBottom float64
BoxLonLeft float64
BoxLonRight float64
JSON string
Port bool
2020-12-14 19:02:35 +01:00
Sponsor bool
2018-02-10 14:35:12 +01:00
}{
response,
r.Host,
2018-10-28 16:42:17 +01:00
response.Latitude + 0.05,
response.Latitude - 0.05,
response.Longitude - 0.05,
response.Longitude + 0.05,
2018-02-10 14:35:12 +01:00
string(json),
2018-02-11 11:19:50 +01:00
s.LookupPort != nil,
2023-10-10 21:52:05 +02:00
s.runConfig.ShowSponsor,
2018-02-10 14:35:12 +01:00
}
2023-09-23 03:28:49 +02:00
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
}
2018-03-18 22:15:51 +01:00
func NotFoundHandler(w http.ResponseWriter, r *http.Request) *appError {
2016-04-15 20:14:16 +02:00
err := notFound(nil).WithMessage("404 page not found")
2016-05-26 21:38:10 +02:00
if r.Header.Get("accept") == jsonMediaType {
2016-04-15 20:14:16 +02:00
err = err.AsJSON()
}
return err
}
2018-03-18 22:15:51 +01:00
func cliMatcher(r *http.Request) bool {
2017-05-27 15:31:50 +02:00
ua := useragent.Parse(r.UserAgent())
switch ua.Product {
case "curl", "HTTPie", "httpie-go", "Wget", "fetch libfetch", "Go", "Go-http-client", "ddclient", "Mikrotik", "xh":
2017-05-27 15:31:50 +02:00
return true
}
return false
2015-09-17 20:57:27 +02:00
}
2015-09-18 17:13:14 +02:00
type appHandler func(http.ResponseWriter, *http.Request) *appError
2020-09-05 12:21:02 +02:00
func wrapHandlerFunc(f http.HandlerFunc) appHandler {
return func(w http.ResponseWriter, r *http.Request) *appError {
f.ServeHTTP(w, r)
return nil
}
}
2015-09-18 17:13:14 +02:00
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if e := fn(w, r); e != nil { // e is *appError
2020-12-09 21:08:06 +01:00
if e.Code/100 == 5 {
log.Println(e.Error)
}
2020-12-09 21:16:11 +01: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 {
2020-12-09 21:16:11 +01:00
Code int `json:"status"`
2015-09-18 17:13:14 +02:00
Error string `json:"error"`
2020-12-09 21:16:11 +01:00
}{e.Code, e.Message}
b, err := json.MarshalIndent(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)
2017-05-28 19:20:02 +02:00
fmt.Fprint(w, e.Message)
2015-09-18 17:13:14 +02:00
}
}
2018-02-10 13:24:32 +01:00
func (s *Server) Handler() http.Handler {
2018-03-18 22:15:51 +01:00
r := NewRouter()
2015-09-17 20:57:27 +02:00
2018-07-30 22:32:42 +02:00
// Health
r.Route("GET", "/health", s.HealthHandler)
2015-09-17 20:57:27 +02:00
// JSON
2018-03-18 22:15:51 +01:00
r.Route("GET", "/", s.JSONHandler).Header("Accept", jsonMediaType)
r.Route("GET", "/json", s.JSONHandler)
2015-09-17 20:57:27 +02:00
// CLI
2018-03-18 22:15:51 +01:00
r.Route("GET", "/", s.CLIHandler).MatcherFunc(cliMatcher)
r.Route("GET", "/", s.CLIHandler).Header("Accept", textMediaType)
r.Route("GET", "/ip", s.CLIHandler)
if !s.parser.IsEmpty() {
2018-03-18 22:15:51 +01:00
r.Route("GET", "/country", s.CLICountryHandler)
r.Route("GET", "/country-iso", s.CLICountryISOHandler)
r.Route("GET", "/city", s.CLICityHandler)
2018-06-15 09:29:13 +02:00
r.Route("GET", "/coordinates", s.CLICoordinatesHandler)
2019-07-05 15:01:45 +02:00
r.Route("GET", "/asn", s.CLIASNHandler)
2022-09-04 00:06:01 +02:00
r.Route("GET", "/asn-org", s.CLIASNOrgHandler)
2018-02-10 17:52:55 +01:00
}
2015-09-17 20:57:27 +02:00
2016-04-15 20:14:16 +02:00
// Browser
2023-10-10 21:52:05 +02:00
if s.runConfig.TemplateDir != "" {
2018-12-28 15:05:31 +01:00
r.Route("GET", "/", s.DefaultHandler)
}
2015-09-17 20:57:27 +02:00
2016-04-15 20:52:15 +02:00
// Port testing
2018-02-11 11:19:50 +01:00
if s.LookupPort != nil {
2018-03-18 22:15:51 +01:00
r.RoutePrefix("GET", "/port/", s.PortHandler)
2018-02-10 17:52:55 +01:00
}
2016-04-15 20:52:15 +02:00
2020-09-05 12:21:02 +02:00
// Profiling
2023-10-10 21:52:05 +02:00
if s.runConfig.Profile {
2020-09-05 12:21:02 +02:00
r.Route("GET", "/debug/pprof/cmdline", wrapHandlerFunc(pprof.Cmdline))
r.Route("GET", "/debug/pprof/profile", wrapHandlerFunc(pprof.Profile))
r.Route("GET", "/debug/pprof/symbol", wrapHandlerFunc(pprof.Symbol))
r.Route("GET", "/debug/pprof/trace", wrapHandlerFunc(pprof.Trace))
r.RoutePrefix("GET", "/debug/pprof/", wrapHandlerFunc(pprof.Index))
}
2018-03-18 22:15:51 +01:00
return r.Handler()
2015-09-17 20:57:27 +02:00
}
2018-02-10 13:24:32 +01:00
func (s *Server) ListenAndServe(addr string) error {
return http.ListenAndServe(addr, s.Handler())
}
2018-06-15 09:29:13 +02:00
func formatCoordinate(c float64) string {
return strconv.FormatFloat(c, 'f', 6, 64)
}
2023-10-10 21:52:05 +02:00
type InvalidTokenError struct{}
func (m *InvalidTokenError) Error() string {
return "invalid_token"
}
func handleAuth(r *http.Request, runConfig *config.Config) error {
if !runConfig.Jwt.Enabled {
return nil
}
authorization := r.Header.Get("Authorization")
tokenString := strings.ReplaceAll(authorization, "Bearer ", "")
if _, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
expected := reflect.TypeOf(jwt.GetSigningMethod(runConfig.Jwt.SigningMethod))
got := reflect.TypeOf(token.Method)
if expected != got {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// Only support SigningMethodHMAC ( Others will be quite a bit more complicated )
2023-10-10 21:52:05 +02:00
return []byte(runConfig.Jwt.Secret), nil
}); err != nil {
if runConfig.Debug {
log.Printf("Error validating token ( %s ): %s \n", tokenString, err)
}
return new(InvalidTokenError)
}
return nil
}