Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ ENV CC=zigcc CGO_ENABLED=1
# Build server
WORKDIR /build/server
COPY cmd/server/go.mod cmd/server/go.sum ./
COPY internal/areamap/ ../../internal/areamap/
COPY internal/geofilter/ ../../internal/geofilter/
COPY internal/sigvalidate/ ../../internal/sigvalidate/
COPY internal/packetpath/ ../../internal/packetpath/
Expand Down
76 changes: 76 additions & 0 deletions cmd/server/areas.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package main

import (
"fmt"
"os"
"path/filepath"
"sort"

"github.com/meshcore-analyzer/areamap"
)

// LoadAreaMap builds the map of every area: config.json's areas (layer
// "region") and the features of AreasFile. It stores the map on cfg, where
// the store and the handlers find it. A code defined twice, a missing file
// or a file that is not GeoJSON is an error: the caller refuses to start
// rather than run with areas silently missing.
func LoadAreaMap(cfg *Config, configDir string) (*areamap.Map, error) {
var areas []areamap.Area
keys := make([]string, 0, len(cfg.Areas))
for k := range cfg.Areas {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
e := cfg.Areas[k]
if e.Label == "" {
continue // "_comment" and other non-areas
}
var ring [][2]float64
switch {
case len(e.Polygon) >= 3:
// config.json polygons are [lat, lon]; GeoJSON rings are [lon, lat].
for _, p := range e.Polygon {
ring = append(ring, [2]float64{p[1], p[0]})
}
case e.LatMin != nil && e.LatMax != nil && e.LonMin != nil && e.LonMax != nil:
ring = [][2]float64{{*e.LonMin, *e.LatMin}, {*e.LonMax, *e.LatMin}, {*e.LonMax, *e.LatMax}, {*e.LonMin, *e.LatMax}}
default:
continue // listed by name only, with nothing to locate against
}
areas = append(areas, areamap.Area{Code: k, Label: e.Label, Layer: areamap.DefaultLayer, Polygons: [][][][2]float64{{ring}}})
}
if cfg.AreasFile != "" {
path := cfg.AreasFile
if !filepath.IsAbs(path) {
path = filepath.Join(configDir, path)
}
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("areasFile: %w", err)
}
fromFile, err := areamap.ParseGeoJSON(data)
if err != nil {
return nil, fmt.Errorf("areasFile %s: %w", path, err)
}
areas = append(areas, fromFile...)
}
m, err := areamap.New(areas)
if err != nil {
return nil, err
}
cfg.areaMap = m
return m, nil
}

// fileArea reports whether code names an area that only the areas file
// defines, so area= resolves it by position instead of config.json's entry.
func (c *Config) fileArea(code string) bool {
if c == nil || c.areaMap == nil {
return false
}
if _, inConfig := c.Areas[code]; inConfig {
return false
}
return c.areaMap.Has(code)
}
137 changes: 137 additions & 0 deletions cmd/server/areas_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package main

import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"

"github.com/gorilla/mux"
"github.com/meshcore-analyzer/areamap"
)

// A rough Scotland on the "country" layer, in GeoJSON's [lon, lat] order.
const scotlandGeoJSON = `{"type":"FeatureCollection","features":[
{"type":"Feature","properties":{"code":"SCO","label":"Scotland","layer":"country","iata":["EDI"]},
"geometry":{"type":"Polygon","coordinates":[[[-7.5,55.0],[-1.5,55.0],[-1.5,60.9],[-7.5,60.9],[-7.5,55.0]]]}}]}`

func writeAreasFile(t *testing.T, body string) string {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "areas.geojson"), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
return dir
}

func belgium() map[string]AreaEntry {
return map[string]AreaEntry{
"BEL": {Label: "Belgium", Polygon: [][2]float64{{50.0, 2.5}, {51.5, 2.5}, {51.5, 6.4}, {50.0, 6.4}}},
"_comment": {},
}
}

func TestLoadAreaMapReadsConfigAreasAndTheFile(t *testing.T) {
dir := writeAreasFile(t, scotlandGeoJSON)
cfg := &Config{Areas: belgium(), AreasFile: "areas.geojson"}
m, err := LoadAreaMap(cfg, dir)
if err != nil {
t.Fatal(err)
}
if cfg.areaMap != m {
t.Error("the map must be kept on the config for the store and handlers")
}
// config.json polygons are [lat, lon]; they must land the right way round.
if got, _ := m.Locate(areamap.DefaultLayer, 50.85, 4.35); got != "BEL" {
t.Errorf("Brussels = %q, want BEL from config.json", got)
}
if got, _ := m.Locate("country", 55.95, -3.19); got != "SCO" {
t.Errorf("Edinburgh = %q, want SCO from the file", got)
}
if got, _ := m.LocateIATA("country", "edi"); got != "SCO" {
t.Errorf("EDI = %q, want SCO", got)
}
}

func TestLoadAreaMapRefusesBadFiles(t *testing.T) {
dup := `{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"code":"BEL","label":"Again"},"geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,0]]]}}]}`
cases := map[string]struct {
body, file string
}{
"a code also in config.json": {dup, "areas.geojson"},
"a missing file": {scotlandGeoJSON, "nope.geojson"},
"not GeoJSON": {`{`, "areas.geojson"},
}
for name, c := range cases {
dir := writeAreasFile(t, c.body)
if _, err := LoadAreaMap(&Config{Areas: belgium(), AreasFile: c.file}, dir); err == nil {
t.Errorf("%s: accepted, want an error", name)
}
}
if m, err := LoadAreaMap(&Config{}, t.TempDir()); err != nil || len(m.Areas("")) != 0 {
t.Errorf("no areas at all = %v, %v; want an empty map and no error", m, err)
}
}

func TestHandleConfigAreasListsFileAreasWithTheirLayer(t *testing.T) {
dir := writeAreasFile(t, scotlandGeoJSON)
cfg := &Config{Areas: belgium(), AreasFile: "areas.geojson"}
if _, err := LoadAreaMap(cfg, dir); err != nil {
t.Fatal(err)
}
r := mux.NewRouter()
srv := &Server{db: setupTestDBv2(t), cfg: cfg}
r.HandleFunc("/api/config/areas", srv.handleConfigAreas).Methods("GET")
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/config/areas", nil))
var got []map[string]string
if err := json.NewDecoder(w.Body).Decode(&got); err != nil {
t.Fatal(err)
}
layers := map[string]string{}
for _, a := range got {
layers[a["key"]] = a["layer"]
}
if len(got) != 2 || layers["BEL"] != areamap.DefaultLayer || layers["SCO"] != "country" {
t.Errorf("areas = %v, want BEL (region) and SCO (country)", got)
}
}

func TestAreaFilterWorksForFileAreas(t *testing.T) {
db := setupTestDBv2(t)
mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('edinburgh', 55.95, -3.19)`)
mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('newcastle', 54.97, -1.61)`)
mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('dublin', 53.35, -6.26)`)
dir := writeAreasFile(t, scotlandGeoJSON)
cfg := &Config{AreasFile: "areas.geojson"}
if _, err := LoadAreaMap(cfg, dir); err != nil {
t.Fatal(err)
}
s := newTestStoreWithDB(t, db, cfg)
got := s.resolveAreaNodes("SCO")
if len(got) != 1 || !got["edinburgh"] {
t.Errorf("nodes in SCO = %v, want only edinburgh", got)
}
// config.json areas keep their own path, unchanged.
cfg.Areas = belgium()
if got := s.resolveAreaNodes("BEL"); got != nil {
t.Errorf("no Belgian nodes, got %v", got)
}
}

// The example in docs/ must load as documented.
func TestTheDocumentedExampleAreasFileLoads(t *testing.T) {
cfg := &Config{AreasFile: "../../docs/examples/areas.example.geojson"}
m, err := LoadAreaMap(cfg, ".")
if err != nil {
t.Fatal(err)
}
if got, _ := m.Locate(areamap.DefaultLayer, 37.34, -121.89); got != "BAY" {
t.Errorf("San Jose = %q, want BAY", got)
}
if got, _ := m.LocateIATA(areamap.DefaultLayer, "MRY"); got != "MRY" {
t.Errorf("observer MRY = %q, want MRY", got)
}
}
12 changes: 12 additions & 0 deletions cmd/server/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"sync/atomic"
"time"

"github.com/meshcore-analyzer/areamap"
"github.com/meshcore-analyzer/dbconfig"
"github.com/meshcore-analyzer/geofilter"
"github.com/meshcore-analyzer/packetpath"
Expand All @@ -24,6 +25,9 @@ type AreaEntry struct {
LatMax *float64 `json:"latMax,omitempty"`
LonMin *float64 `json:"lonMin,omitempty"`
LonMax *float64 `json:"lonMax,omitempty"`
// match, when set, decides membership instead of the polygon or box: an
// area from areasFile, tested against its GeoJSON geometry.
match func(lat, lon float64) bool
}

// ListLimitsConfig defines maximum row limits for list endpoints to prevent DoS.
Expand Down Expand Up @@ -139,6 +143,14 @@ type Config struct {
GeoFilter *GeoFilterConfig `json:"geo_filter,omitempty"`

Areas map[string]AreaEntry `json:"areas,omitempty"`
// AreasFile names a GeoJSON FeatureCollection of further areas, relative
// to the config directory: real boundaries (coastlines, islands, holes)
// in layers, which config.json's polygons cannot hold. See
// internal/areamap for the feature properties it reads.
AreasFile string `json:"areasFile,omitempty"`
// areaMap holds every area, from Areas and AreasFile, once LoadAreaMap
// has run. Nil until then.
areaMap *areamap.Map

Timestamps *TimestampConfig `json:"timestamps,omitempty"`

Expand Down
6 changes: 5 additions & 1 deletion cmd/server/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -3190,6 +3190,10 @@ func (db *DB) GetNodePubkeysInArea(entry AreaEntry) ([]string, error) {
LonMin: entry.LonMin,
LonMax: entry.LonMax,
}
inside := func(lat, lon float64) bool { return geofilter.PassesFilter(lat, lon, gf) }
if entry.match != nil {
inside = entry.match
}

var result []string
for rows.Next() {
Expand All @@ -3205,7 +3209,7 @@ func (db *DB) GetNodePubkeysInArea(entry AreaEntry) ([]string, error) {
if lat.Float64 == 0 && lon.Float64 == 0 {
continue
}
if geofilter.PassesFilter(lat.Float64, lon.Float64, gf) {
if inside(lat.Float64, lon.Float64) {
result = append(result, pk)
}
}
Expand Down
3 changes: 3 additions & 0 deletions cmd/server/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ go 1.22
require (
github.com/gorilla/mux v1.8.1
github.com/gorilla/websocket v1.5.3
github.com/meshcore-analyzer/areamap v0.0.0
github.com/meshcore-analyzer/geofilter v0.0.0
github.com/meshcore-analyzer/sigvalidate v0.0.0
)

replace github.com/meshcore-analyzer/areamap => ../../internal/areamap

replace github.com/meshcore-analyzer/geofilter => ../../internal/geofilter

replace github.com/meshcore-analyzer/sigvalidate => ../../internal/sigvalidate
Expand Down
8 changes: 8 additions & 0 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,14 @@ func main() {
if err != nil {
log.Printf("[config] warning: %v (using defaults)", err)
}
// Areas from config.json and areasFile. A bad areas file stops startup:
// running with areas silently missing would put packets in the wrong
// place without anyone noticing.
if am, err := LoadAreaMap(cfg, configDir); err != nil {
log.Fatalf("[areas] %v", err)
} else if n := len(am.Areas("")); n > 0 {
log.Printf("[areas] %d areas in layers %v", n, am.Layers())
}

// CLI flags override config
if port > 0 {
Expand Down
21 changes: 18 additions & 3 deletions cmd/server/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/meshcore-analyzer/areamap"
"log"
"math"
"net/http"
Expand Down Expand Up @@ -541,13 +542,22 @@ func (s *Server) handleConfigAreas(w http.ResponseWriter, r *http.Request) {
type areaListEntry struct {
Key string `json:"key"`
Label string `json:"label"`
Layer string `json:"layer"`
}
result := make([]areaListEntry, 0, len(s.cfg.Areas))
for k, v := range s.cfg.Areas {
if v.Label == "" {
continue // skip comment/invalid entries (e.g. "_comment" keys in config)
}
result = append(result, areaListEntry{Key: k, Label: v.Label})
result = append(result, areaListEntry{Key: k, Label: v.Label, Layer: areamap.DefaultLayer})
}
// Areas from areasFile, in the file's order, with their layer.
if s.cfg.areaMap != nil {
for _, a := range s.cfg.areaMap.Areas("") {
if s.cfg.fileArea(a.Code) {
result = append(result, areaListEntry{Key: a.Code, Label: a.Label, Layer: a.Layer})
}
}
}
writeJSON(w, result)
}
Expand Down Expand Up @@ -1594,8 +1604,13 @@ func (s *Server) handleNodes(w http.ResponseWriter, r *http.Request) {
var areaNodes map[string]bool
if s.store != nil {
areaNodes = s.store.resolveAreaNodes(area)
} else if s.cfg != nil && s.cfg.Areas != nil {
if entry, ok := s.cfg.Areas[area]; ok {
} else if s.cfg != nil {
entry, ok := s.cfg.Areas[area]
if !ok && s.cfg.fileArea(area) {
m := s.cfg.areaMap
entry, ok = AreaEntry{match: func(lat, lon float64) bool { return m.Contains(area, lat, lon) }}, true
}
if ok {
pks, err := s.db.GetNodePubkeysInArea(entry)
if err == nil {
areaNodes = make(map[string]bool, len(pks))
Expand Down
10 changes: 8 additions & 2 deletions cmd/server/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -3860,12 +3860,18 @@ const areaNodeTTL = 30 * time.Second
// TTL is served as-is while one background refresh re-queries it (#2146).
// Uses its own RWMutex so callers holding s.mu won't deadlock.
func (s *PacketStore) resolveAreaNodes(areaKey string) map[string]bool {
if s.config == nil || s.config.Areas == nil {
if s.config == nil {
return nil
}
entry, ok := s.config.Areas[areaKey]
if !ok {
return nil
if !s.config.fileArea(areaKey) {
return nil
}
// An area from areasFile: matched by position against its GeoJSON
// geometry, through the same cache as config.json's areas.
m := s.config.areaMap
entry = AreaEntry{match: func(lat, lon float64) bool { return m.Contains(areaKey, lat, lon) }}
}

s.areaNodeMu.RLock()
Expand Down
2 changes: 2 additions & 0 deletions config.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,8 @@
"mode": "flag",
"_comment": "Controls how the ingestor handles ADVERTs whose GPS is OUTSIDE the geo_filter polygon (#730). 'flag' (default): store the advert/node and tag it foreign_advert=1 so operators can see bridged/leaked nodes via the API ('foreign': true on /api/nodes). 'drop': legacy behavior — silently discard the advert (no log, no node row). Only applies when geo_filter is configured; otherwise has no effect."
},
"_comment_areasFile": "Optional. A GeoJSON FeatureCollection of further areas, path relative to this file (or absolute). Use it for real boundaries that the polygons below cannot hold: coastlines, islands (MultiPolygon) and holes. Each feature is one area; its properties are code (required, unique across every area including those below), label, layer (default \"region\"; one file can hold several sets, such as countries and counties) and iata (airport codes of observers that report no position, so they still belong to an area). Coordinates are GeoJSON's [lon, lat]. Its areas join the area filter beside the ones below. A missing or invalid file stops the server at startup. Example: docs/examples/areas.example.geojson.",
"areasFile": "",
"areas": {
"_comment": "Optional. GPS-based display filter. Each entry defines a geographic area by polygon ([lat, lon] pairs) or bounding box (latMin/latMax/lonMin/lonMax). Packets and nodes are attributed to an area based on the transmitting node's own GPS coordinates — not the observer's location. Areas appear as a filter pill bar in the dashboard. Remove this section to disable the area filter UI.",
"BAY": {
Expand Down
Loading