// RID headless adapter derived from Cyclenerd/offline-map-tile-downloader (MIT). // Upstream: 9b61800537b2c50a71345dfed3bbc0fcd8731711. See LICENSE-upstream.txt. // Retains its Web Mercator tile algorithm; replaces web UI with a bounded JSON job. package main import ( "bytes" "encoding/json" "fmt" "image" _ "image/jpeg" _ "image/png" "io" "math" "net/http" "net/url" "os" "path/filepath" "strings" "sync" "time" ) type bounds struct{ West, South, East, North float64 } type request struct { Bounds bounds MinZoom, MaxZoom int Layers []string Output, BaseURL string } type tile struct { layer string x, y, z uint32 } type progress struct { Done uint64 `json:"done"` Failed uint64 `json:"failed"` } // latLonToTile is from the pinned MIT upstream; clamp at Mercator world edges. func latLonToTile(lat, lon float64, zoom uint32) (x, y uint32) { latRad := lat * math.Pi / 180 n := math.Pow(2, float64(zoom)) x = uint32(n * ((lon + 180) / 360)) y = uint32(n * (1 - (math.Log(math.Tan(latRad)+1/math.Cos(latRad)) / math.Pi)) / 2) if x >= uint32(n) { x = uint32(n) - 1 } if y >= uint32(n) { y = uint32(n) - 1 } return } func coverage(r request) ([]tile, error) { b := r.Bounds for _, v := range []float64{b.West, b.East, b.South, b.North} { if math.IsNaN(v) || math.IsInf(v, 0) { return nil, fmt.Errorf("invalid bounds") } } if b.West < -180 || b.East > 180 || b.South < -85.051128 || b.North > 85.051128 || b.West >= b.East || b.South >= b.North || r.MinZoom < 0 || r.MaxZoom > 18 || r.MinZoom > r.MaxZoom || len(r.Layers) == 0 || len(r.Layers) > 4 { return nil, fmt.Errorf("invalid coverage") } seen := map[string]bool{} for _, l := range r.Layers { if seen[l] || !(l == "vec_w" || l == "cva_w" || l == "img_w" || l == "cia_w") { return nil, fmt.Errorf("invalid layer") } seen[l] = true } var tiles []tile for z := uint32(r.MinZoom); z <= uint32(r.MaxZoom); z++ { x0, y0 := latLonToTile(b.North, b.West, z) x1, y1 := latLonToTile(b.South, b.East, z) if uint64(x1-x0+1)*uint64(y1-y0+1)*uint64(len(r.Layers))+uint64(len(tiles)) > 20000 { return nil, fmt.Errorf("coverage exceeds limit") } for _, l := range r.Layers { for x := x0; x <= x1; x++ { for y := y0; y <= y1; y++ { tiles = append(tiles, tile{l, x, y, z}) } } } } return tiles, nil } func validImage(data []byte) bool { if len(data) == 0 || len(data) > 2*1024*1024 { return false } cfg, _, err := image.DecodeConfig(bytes.NewReader(data)) if err != nil || cfg.Width != 256 || cfg.Height != 256 { return false } _, _, err = image.Decode(bytes.NewReader(data)) return err == nil } func safePath(path string) bool { for p := filepath.Clean(path); ; p = filepath.Dir(p) { info, err := os.Lstat(p) if err == nil && info.Mode()&os.ModeSymlink != 0 { return false } if err != nil && !os.IsNotExist(err) { return false } if filepath.Dir(p) == p { return true } } } func store(path string, data []byte) error { if !safePath(path) { return fmt.Errorf("symlink output denied") } if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { return err } f, err := os.CreateTemp(filepath.Dir(path), ".rid-map-*.tmp") if err != nil { return err } name := f.Name() defer os.Remove(name) if _, err = f.Write(data); err != nil { f.Close() return err } if err = f.Sync(); err != nil { f.Close() return err } if err = f.Close(); err != nil { return err } return os.Rename(name, path) } func fetch(client *http.Client, r request, t tile, limiter <-chan time.Time) error { path := filepath.Join(r.Output, t.layer, fmt.Sprint(t.z), fmt.Sprint(t.x), fmt.Sprintf("%d.png", t.y)) if !safePath(path) { return fmt.Errorf("invalid output") } if info, err := os.Stat(path); err == nil && info.Size() <= 2*1024*1024 { if data, err := os.ReadFile(path); err == nil && validImage(data) { return nil } } // Valid local tiles do not consume network rate-limit slots. <-limiter resp, err := client.Get(fmt.Sprintf("%s/%s/%d/%d/%d", strings.TrimRight(r.BaseURL, "/"), t.layer, t.z, t.x, t.y)) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("tile unavailable") } data, err := io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024+1)) if err != nil { return err } if !validImage(data) { return fmt.Errorf("invalid image") } return store(path, data) } func run(input io.Reader, output io.Writer) error { var r request d := json.NewDecoder(io.LimitReader(input, 65537)) d.DisallowUnknownFields() if err := d.Decode(&r); err != nil { return err } u, err := url.Parse(r.BaseURL) if err != nil || u.Scheme != "http" || u.Hostname() != "127.0.0.1" || u.Port() == "" || u.Path != "/api/maps/tile" || u.RawQuery != "" || u.User != nil { return fmt.Errorf("only local tile proxy is allowed") } if !filepath.IsAbs(r.Output) || !safePath(r.Output) { return fmt.Errorf("invalid output") } tiles, err := coverage(r) if err != nil { return err } client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }} // A single ticker limits the whole pool, rather than each worker independently. ticker := time.NewTicker(250 * time.Millisecond) defer ticker.Stop() jobs := make(chan tile) var wg sync.WaitGroup var mu sync.Mutex p := progress{} encoder := json.NewEncoder(output) for i := 0; i < 4; i++ { wg.Add(1) go func() { defer wg.Done() for t := range jobs { err := fetch(client, r, t, ticker.C) mu.Lock() p.Done++ if err != nil { p.Failed++ } _ = encoder.Encode(p) mu.Unlock() } }() } for _, t := range tiles { jobs <- t } close(jobs) wg.Wait() if p.Failed > 0 { return fmt.Errorf("some tiles failed") } return nil } func main() { if err := run(os.Stdin, os.Stdout); err != nil { fmt.Fprintln(os.Stderr, "map download failed") os.Exit(1) } }