package app import ( "net/netip" "strings" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ua" ) // enricher adapts the geo and ua packages to core.Enricher. geo may be nil // (databases missing): locations are then simply empty. type enricher struct{ g *geo.Resolver } func clip(s string, n int) string { s = strings.Map(func(r rune) rune { if r < 0x20 || r == 0x7f { return -1 } return r }, s) if len(s) > n { s = strings.ToValidUTF8(s[:n], "") } return s } func validCC(cc string) string { if len(cc) != 2 || cc[0] < 'A' || cc[0] > 'Z' || cc[1] < 'A' || cc[1] > 'Z' { return "" } return cc } func (e enricher) Geo(ip string) (out core.GeoInfo) { defer func() { if recover() != nil { // a corrupt database must never take the daemon down out = core.GeoInfo{} } }() if e.g == nil { return core.GeoInfo{} } a, err := netip.ParseAddr(ip) if err != nil { return core.GeoInfo{} } i := e.g.Lookup(a) return core.GeoInfo{CC: validCC(i.CountryCode), Country: clip(i.Country, 80), CountryPT: clip(i.CountryPT, 80), Continent: clip(i.Continent, 40), Region: clip(i.Region, 80), City: clip(i.City, 80), Lat: i.Lat, Lon: i.Lon, ASN: i.ASN, ASOrg: clip(i.ASOrg, 120)} } func (enricher) UA(raw string) (out core.UAInfo) { defer func() { if recover() != nil { out = core.UAInfo{} } }() i := ua.Parse(raw) return core.UAInfo{Browser: i.Browser, BrowserMajor: i.BrowserMajor, OS: i.OS, Device: i.Device, Bot: i.Bot, BotName: i.BotName, Tool: i.Tool} } // geoStatus reports the geo database like a log source in the Sources table. func geoStatus(g *geo.Resolver, dir string) store.SourceStatus { st := store.SourceStatus{Name: "geo", Path: dir, State: "following"} if g == nil { st.State = "waiting" return st } s := g.Status() if !s.City.Loaded || !s.ASN.Loaded { st.State = "waiting" } if s.LastError != "" { st.Error = s.LastError } if !s.LastUpdate.IsZero() { st.LastEvent = s.LastUpdate.Unix() } return st } // Attribution is the licence credit the geo data requires. const Attribution = geo.Attribution