package geo import ( "compress/gzip" "context" "errors" "fmt" "io" "net/http" "os" "path/filepath" "time" ) const ( maxAge = 35 * 24 * time.Hour maxUnpacked = 1 << 30 // teto de segurança para o arquivo descompactado ) // downloadBase é a URL base dos arquivos; variável para os testes. var downloadBase = "https://download.db-ip.com/free/" var errNotFound = errors.New("não encontrado") // StartUpdater baixa as bases na partida se faltarem ou tiverem mais de 35 // dias e depois confere a cada interval. Roda em goroutine própria até ctx // terminar. Falhas ficam em Status().LastError e nunca interrompem o uso. func (r *Resolver) StartUpdater(ctx context.Context, interval time.Duration, client *http.Client) { if client == nil { client = &http.Client{Timeout: 15 * time.Minute} } if interval <= 0 { interval = 24 * time.Hour } go func() { r.updateAll(ctx, client, false) t := time.NewTicker(interval) defer t.Stop() for { select { case <-ctx.Done(): return case <-t.C: r.updateAll(ctx, client, true) } } }() } // updateAll atualiza city e asn. Na partida (periodic=false) só baixa se // faltar ou estiver velha; nos ciclos, procura o arquivo do mês corrente. func (r *Resolver) updateAll(ctx context.Context, client *http.Client, periodic bool) { if !r.updating.CompareAndSwap(false, true) { return } defer r.updating.Store(false) var errs []string for _, k := range []kind{kindCity, kindASN} { if ctx.Err() != nil { return } if !periodic { if d := r.slot(k).Load(); d != nil && time.Since(time.Unix(int64(d.r.BuildEpoch), 0)) <= maxAge { continue } } if err := r.updateKind(ctx, client, k); err != nil { errs = append(errs, k.name+": "+err.Error()) } } r.mu.Lock() r.lastCheck = time.Now() if len(errs) > 0 { r.lastErr = errs[0] for _, e := range errs[1:] { r.lastErr += "; " + e } } else { r.lastErr = "" } r.mu.Unlock() } func (r *Resolver) updateKind(ctx context.Context, client *http.Client, k kind) error { now := time.Now().UTC() cur := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC) for _, m := range []time.Time{cur, cur.AddDate(0, -1, 0)} { name := fmt.Sprintf("%s%s.mmdb", k.prefix, m.Format("2006-01")) final := filepath.Join(r.dir, name) if d := r.slot(k).Load(); d != nil && filepath.Base(d.file) >= name { return nil // já temos este mês (ou mais novo) } if _, err := os.Stat(final); err == nil { if r.install(k, final) == nil { return nil } } err := r.download(ctx, client, k, name+".gz", final) if errors.Is(err, errNotFound) { continue } if err != nil { return err } return r.install(k, final) } return nil // nenhum arquivo publicado ainda; tenta no próximo ciclo } func (r *Resolver) download(ctx context.Context, client *http.Client, k kind, remote, final string) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadBase+remote, nil) if err != nil { return err } req.Header.Set("User-Agent", "urutau-geo") resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode == http.StatusNotFound { return errNotFound } if resp.StatusCode != http.StatusOK { return fmt.Errorf("download %s: HTTP %d", remote, resp.StatusCode) } gz, err := gzip.NewReader(resp.Body) if err != nil { return fmt.Errorf("download %s: %w", remote, err) } defer gz.Close() tmp, err := os.CreateTemp(r.dir, ".tmp-"+k.name+"-*") if err != nil { return err } tmpName := tmp.Name() defer os.Remove(tmpName) // no-op após rename n, err := io.Copy(tmp, io.LimitReader(gz, maxUnpacked+1)) if cerr := tmp.Close(); err == nil { err = cerr } if err != nil { return fmt.Errorf("download %s: %w", remote, err) } if n > maxUnpacked { return fmt.Errorf("download %s: arquivo grande demais", remote) } // valida abrindo o MMDB e fazendo uma consulta de sanidade probe, err := openReader(tmpName) if err != nil { return fmt.Errorf("download %s inválido: %w", remote, err) } serr := probe.sanity() probe.close() if serr != nil { return fmt.Errorf("download %s inválido: %w", remote, serr) } if err := os.Chmod(tmpName, 0o644); err != nil { return err } return os.Rename(tmpName, final) } // install abre path e troca a base em uso, fechando a antiga e removendo meses velhos. func (r *Resolver) install(k kind, path string) error { rd, err := openReader(path) if err != nil { return err } if err := rd.sanity(); err != nil { rd.close() return err } old := r.slot(k).Swap(&db{r: rd, file: path}) r.cache.clear() r.mu.Lock() r.lastUpdate = time.Now() r.mu.Unlock() if old != nil { old.r.close() // espera lookups em andamento terminarem } for _, f := range r.listFiles(k) { if f != path && filepath.Base(f) < filepath.Base(path) { os.Remove(f) } } return nil }