mirror of
https://github.com/therootcompany/golib.git
synced 2026-04-24 20:58:00 +00:00
feat(check-ip): --format pretty|json, move rendering out of geoip
geoip.Databases now exposes a structured Lookup(ip) Info. Rendering moved up to the cmd — the library no longer writes to io.Writer. check-ip adds a Result struct and --format flag (pretty/json). Serve mode dispatches on ?format=json or Accept: application/json. Pretty is the default for both one-shot and HTTP.
This commit is contained in:
parent
a3d657ec61
commit
912e1179d4
@ -19,6 +19,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
@ -57,6 +58,26 @@ type Config struct {
|
|||||||
CityDB string
|
CityDB string
|
||||||
ASNDB string
|
ASNDB string
|
||||||
Serve string
|
Serve string
|
||||||
|
Format string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format selects the report rendering.
|
||||||
|
type Format string
|
||||||
|
|
||||||
|
const (
|
||||||
|
FormatPretty Format = "pretty"
|
||||||
|
FormatJSON Format = "json"
|
||||||
|
)
|
||||||
|
|
||||||
|
func parseFormat(s string) (Format, error) {
|
||||||
|
switch s {
|
||||||
|
case "", "pretty":
|
||||||
|
return FormatPretty, nil
|
||||||
|
case "json":
|
||||||
|
return FormatJSON, nil
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("invalid --format %q (want: pretty, json)", s)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@ -72,6 +93,7 @@ func main() {
|
|||||||
fs.StringVar(&cfg.CityDB, "city-db", "", "path to GeoLite2-City.mmdb (skips auto-download)")
|
fs.StringVar(&cfg.CityDB, "city-db", "", "path to GeoLite2-City.mmdb (skips auto-download)")
|
||||||
fs.StringVar(&cfg.ASNDB, "asn-db", "", "path to GeoLite2-ASN.mmdb (skips auto-download)")
|
fs.StringVar(&cfg.ASNDB, "asn-db", "", "path to GeoLite2-ASN.mmdb (skips auto-download)")
|
||||||
fs.StringVar(&cfg.Serve, "serve", "", "start HTTP server at addr:port (e.g. :8080) instead of one-shot check")
|
fs.StringVar(&cfg.Serve, "serve", "", "start HTTP server at addr:port (e.g. :8080) instead of one-shot check")
|
||||||
|
fs.StringVar(&cfg.Format, "format", "", "output format: pretty, json (default pretty)")
|
||||||
fs.Usage = func() {
|
fs.Usage = func() {
|
||||||
fmt.Fprintf(os.Stderr, "Usage: %s [flags] <ip-address>\n", os.Args[0])
|
fmt.Fprintf(os.Stderr, "Usage: %s [flags] <ip-address>\n", os.Args[0])
|
||||||
fmt.Fprintf(os.Stderr, " %s --serve :8080 [flags]\n", os.Args[0])
|
fmt.Fprintf(os.Stderr, " %s --serve :8080 [flags]\n", os.Args[0])
|
||||||
@ -137,23 +159,79 @@ type Checker struct {
|
|||||||
geo *geoip.Databases
|
geo *geoip.Databases
|
||||||
}
|
}
|
||||||
|
|
||||||
// Report writes a human-readable status line (plus geoip info) for ip and
|
// Result is the structured verdict for a single IP.
|
||||||
// reports whether ip was blocked.
|
type Result struct {
|
||||||
func (c *Checker) Report(w io.Writer, ip string) (blocked bool) {
|
IP string `json:"ip"`
|
||||||
blockedIn := isBlocked(ip, c.whitelist, c.inbound.Value())
|
Blocked bool `json:"blocked"`
|
||||||
blockedOut := isBlocked(ip, c.whitelist, c.outbound.Value())
|
BlockedInbound bool `json:"blocked_inbound"`
|
||||||
switch {
|
BlockedOutbound bool `json:"blocked_outbound"`
|
||||||
case blockedIn && blockedOut:
|
Whitelisted bool `json:"whitelisted,omitempty"`
|
||||||
fmt.Fprintf(w, "%s is BLOCKED (inbound + outbound)\n", ip)
|
Geo geoip.Info `json:"geo,omitzero"`
|
||||||
case blockedIn:
|
}
|
||||||
fmt.Fprintf(w, "%s is BLOCKED (inbound)\n", ip)
|
|
||||||
case blockedOut:
|
// Check returns the structured verdict for ip without rendering.
|
||||||
fmt.Fprintf(w, "%s is BLOCKED (outbound)\n", ip)
|
func (c *Checker) Check(ip string) Result {
|
||||||
default:
|
whitelisted := c.whitelist != nil && c.whitelist.Contains(ip)
|
||||||
fmt.Fprintf(w, "%s is allowed\n", ip)
|
in := !whitelisted && cohortContains(c.inbound.Value(), ip)
|
||||||
|
out := !whitelisted && cohortContains(c.outbound.Value(), ip)
|
||||||
|
return Result{
|
||||||
|
IP: ip,
|
||||||
|
Blocked: in || out,
|
||||||
|
BlockedInbound: in,
|
||||||
|
BlockedOutbound: out,
|
||||||
|
Whitelisted: whitelisted,
|
||||||
|
Geo: c.geo.Lookup(ip),
|
||||||
}
|
}
|
||||||
c.geo.PrintInfo(w, ip)
|
}
|
||||||
return blockedIn || blockedOut
|
|
||||||
|
// Report renders r to w in the given format. Returns r.Blocked for convenience.
|
||||||
|
func (r Result) Report(w io.Writer, format Format) bool {
|
||||||
|
switch format {
|
||||||
|
case FormatJSON:
|
||||||
|
enc := json.NewEncoder(w)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
_ = enc.Encode(r)
|
||||||
|
default:
|
||||||
|
r.writePretty(w)
|
||||||
|
}
|
||||||
|
return r.Blocked
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Result) writePretty(w io.Writer) {
|
||||||
|
switch {
|
||||||
|
case r.BlockedInbound && r.BlockedOutbound:
|
||||||
|
fmt.Fprintf(w, "%s is BLOCKED (inbound + outbound)\n", r.IP)
|
||||||
|
case r.BlockedInbound:
|
||||||
|
fmt.Fprintf(w, "%s is BLOCKED (inbound)\n", r.IP)
|
||||||
|
case r.BlockedOutbound:
|
||||||
|
fmt.Fprintf(w, "%s is BLOCKED (outbound)\n", r.IP)
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(w, "%s is allowed\n", r.IP)
|
||||||
|
}
|
||||||
|
geoPrint(w, r.Geo)
|
||||||
|
}
|
||||||
|
|
||||||
|
func geoPrint(w io.Writer, info geoip.Info) {
|
||||||
|
var parts []string
|
||||||
|
if info.City != "" {
|
||||||
|
parts = append(parts, info.City)
|
||||||
|
}
|
||||||
|
if info.Region != "" {
|
||||||
|
parts = append(parts, info.Region)
|
||||||
|
}
|
||||||
|
if info.Country != "" {
|
||||||
|
parts = append(parts, fmt.Sprintf("%s (%s)", info.Country, info.CountryISO))
|
||||||
|
}
|
||||||
|
if len(parts) > 0 {
|
||||||
|
fmt.Fprintf(w, " Location: %s\n", strings.Join(parts, ", "))
|
||||||
|
}
|
||||||
|
if info.ASN != 0 {
|
||||||
|
fmt.Fprintf(w, " ASN: AS%d %s\n", info.ASN, info.ASNOrg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func cohortContains(c *ipcohort.Cohort, ip string) bool {
|
||||||
|
return c != nil && c.Contains(ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
// newChecker builds a fully-populated Checker and starts background refresh.
|
// newChecker builds a fully-populated Checker and starts background refresh.
|
||||||
@ -185,12 +263,16 @@ func newChecker(ctx context.Context, cfg Config) (*Checker, func(), error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func oneshot(ctx context.Context, cfg Config, ip string) (blocked bool, err error) {
|
func oneshot(ctx context.Context, cfg Config, ip string) (blocked bool, err error) {
|
||||||
|
format, err := parseFormat(cfg.Format)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
checker, cleanup, err := newChecker(ctx, cfg)
|
checker, cleanup, err := newChecker(ctx, cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
return checker.Report(os.Stdout, ip), nil
|
return checker.Check(ip).Report(os.Stdout, format), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func serve(ctx context.Context, cfg Config) error {
|
func serve(ctx context.Context, cfg Config) error {
|
||||||
@ -200,18 +282,26 @@ func serve(ctx context.Context, cfg Config) error {
|
|||||||
}
|
}
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
|
||||||
|
handle := func(w http.ResponseWriter, r *http.Request, ip string) {
|
||||||
|
format := requestFormat(r)
|
||||||
|
if format == FormatJSON {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
} else {
|
||||||
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
|
}
|
||||||
|
checker.Check(ip).Report(w, format)
|
||||||
|
}
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("GET /check", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("GET /check", func(w http.ResponseWriter, r *http.Request) {
|
||||||
ip := strings.TrimSpace(r.URL.Query().Get("ip"))
|
ip := strings.TrimSpace(r.URL.Query().Get("ip"))
|
||||||
if ip == "" {
|
if ip == "" {
|
||||||
ip = clientIP(r)
|
ip = clientIP(r)
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
handle(w, r, ip)
|
||||||
checker.Report(w, ip)
|
|
||||||
})
|
})
|
||||||
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
handle(w, r, clientIP(r))
|
||||||
checker.Report(w, clientIP(r))
|
|
||||||
})
|
})
|
||||||
|
|
||||||
srv := &http.Server{
|
srv := &http.Server{
|
||||||
@ -236,6 +326,19 @@ func serve(ctx context.Context, cfg Config) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// requestFormat picks a response format from ?format=, then Accept header.
|
||||||
|
func requestFormat(r *http.Request) Format {
|
||||||
|
if q := r.URL.Query().Get("format"); q != "" {
|
||||||
|
if f, err := parseFormat(q); err == nil {
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||||||
|
return FormatJSON
|
||||||
|
}
|
||||||
|
return FormatPretty
|
||||||
|
}
|
||||||
|
|
||||||
// clientIP extracts the caller's IP, honoring X-Forwarded-For when present.
|
// clientIP extracts the caller's IP, honoring X-Forwarded-For when present.
|
||||||
// The leftmost entry in X-Forwarded-For is the originating client; intermediate
|
// The leftmost entry in X-Forwarded-For is the originating client; intermediate
|
||||||
// proxies append themselves rightward.
|
// proxies append themselves rightward.
|
||||||
@ -354,13 +457,3 @@ func splitCSV(s string) []string {
|
|||||||
}
|
}
|
||||||
return strings.Split(s, ",")
|
return strings.Split(s, ",")
|
||||||
}
|
}
|
||||||
|
|
||||||
func isBlocked(ip string, whitelist, cohort *ipcohort.Cohort) bool {
|
|
||||||
if cohort == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if whitelist != nil && whitelist.Contains(ip) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return cohort.Contains(ip)
|
|
||||||
}
|
|
||||||
|
|||||||
@ -3,11 +3,9 @@ package geoip
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/oschwald/geoip2-golang"
|
"github.com/oschwald/geoip2-golang"
|
||||||
)
|
)
|
||||||
@ -116,45 +114,48 @@ func (d *Databases) Close() error {
|
|||||||
return errors.Join(errs...)
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// PrintInfo writes city and ASN info for ip to w. No-op on nil receiver or
|
// Info is the structured result of a GeoIP lookup. Zero-valued fields mean
|
||||||
// unparseable IP; missing readers are skipped silently.
|
// the database didn't return a value (or wasn't configured).
|
||||||
func (d *Databases) PrintInfo(w io.Writer, ip string) {
|
type Info struct {
|
||||||
|
City string `json:"city,omitempty"`
|
||||||
|
Region string `json:"region,omitempty"`
|
||||||
|
Country string `json:"country,omitempty"`
|
||||||
|
CountryISO string `json:"country_iso,omitempty"`
|
||||||
|
ASN uint `json:"asn,omitzero"`
|
||||||
|
ASNOrg string `json:"asn_org,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup returns city + ASN info for ip. Returns a zero Info on nil receiver,
|
||||||
|
// unparseable IP, or database miss.
|
||||||
|
func (d *Databases) Lookup(ip string) Info {
|
||||||
|
var info Info
|
||||||
if d == nil {
|
if d == nil {
|
||||||
return
|
return info
|
||||||
}
|
}
|
||||||
addr, err := netip.ParseAddr(ip)
|
addr, err := netip.ParseAddr(ip)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return info
|
||||||
}
|
}
|
||||||
stdIP := addr.AsSlice()
|
stdIP := addr.AsSlice()
|
||||||
|
|
||||||
if d.City != nil {
|
if d.City != nil {
|
||||||
if rec, err := d.City.City(stdIP); err == nil {
|
if rec, err := d.City.City(stdIP); err == nil {
|
||||||
city := rec.City.Names["en"]
|
info.City = rec.City.Names["en"]
|
||||||
country := rec.Country.Names["en"]
|
info.Country = rec.Country.Names["en"]
|
||||||
iso := rec.Country.IsoCode
|
info.CountryISO = rec.Country.IsoCode
|
||||||
var parts []string
|
|
||||||
if city != "" {
|
|
||||||
parts = append(parts, city)
|
|
||||||
}
|
|
||||||
if len(rec.Subdivisions) > 0 {
|
if len(rec.Subdivisions) > 0 {
|
||||||
if sub := rec.Subdivisions[0].Names["en"]; sub != "" && sub != city {
|
if sub := rec.Subdivisions[0].Names["en"]; sub != "" && sub != info.City {
|
||||||
parts = append(parts, sub)
|
info.Region = sub
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if country != "" {
|
|
||||||
parts = append(parts, fmt.Sprintf("%s (%s)", country, iso))
|
|
||||||
}
|
|
||||||
if len(parts) > 0 {
|
|
||||||
fmt.Fprintf(w, " Location: %s\n", strings.Join(parts, ", "))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if d.ASN != nil {
|
if d.ASN != nil {
|
||||||
if rec, err := d.ASN.ASN(stdIP); err == nil && rec.AutonomousSystemNumber != 0 {
|
if rec, err := d.ASN.ASN(stdIP); err == nil {
|
||||||
fmt.Fprintf(w, " ASN: AS%d %s\n",
|
info.ASN = rec.AutonomousSystemNumber
|
||||||
rec.AutonomousSystemNumber, rec.AutonomousSystemOrganization)
|
info.ASNOrg = rec.AutonomousSystemOrganization
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return info
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user