pewpath 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pewpath/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """pewpath: infer where a traceroute path goes, from router names, hints and exchange data (stdlib only, no I/O)."""
2
+ from .geohint import city_lookup, from_hostname
3
+ from .hints import Hints, load
4
+ from .hops import annotate_shared_ixs, placed_path, refine_hop_geo
5
+
6
+ __version__ = "0.1.0"
7
+ __all__ = ["Hints", "__version__", "annotate_shared_ixs", "city_lookup", "from_hostname", "load", "placed_path", "refine_hop_geo"]
pewpath/geohint.py ADDED
@@ -0,0 +1,223 @@
1
+ """Location hints for IPs that GeoIP can't place precisely (stdlib only).
2
+
3
+ Router and server hostnames usually carry a location: IATA airport codes (lax1, fra3,
4
+ ord-2), CLLI city codes used by North American carriers (sttlwa01, chcgil, nycmny), or
5
+ a plain city name (toronto, frankfurt). This module turns a reverse-DNS name into a
6
+ city with coordinates, and checks the guess against the country we already believe the
7
+ IP is in, so short codes inside ordinary words don't send packets to the wrong place.
8
+ """
9
+ import math
10
+ import re
11
+ from types import MappingProxyType
12
+
13
+ # name, country, lat, lon, IATA codes, CLLI-style prefixes, extra tokens
14
+ PLACES = (
15
+ ("Seattle", "US", 47.61, -122.33, ["sea"], ["sttlwa"], []),
16
+ ("Portland", "US", 45.52, -122.68, ["pdx"], ["ptldor"], []),
17
+ ("San Jose", "US", 37.34, -121.89, ["sjc"], ["snjsca"], ["sanjose"]),
18
+ ("Palo Alto", "US", 37.44, -122.14, ["pao"], ["plalca"], ["paloalto"]),
19
+ ("Fremont", "US", 37.55, -121.99, [], ["frmtca"], ["fremont"]),
20
+ ("San Francisco", "US", 37.77, -122.42, ["sfo"], ["snfcca"], ["sanfrancisco"]),
21
+ ("Los Angeles", "US", 34.05, -118.24, ["lax"], ["lsanca"], ["losangeles"]),
22
+ ("San Diego", "US", 32.72, -117.16, ["san"], ["sndgca"], ["sandiego"]),
23
+ ("Las Vegas", "US", 36.17, -115.14, ["las"], ["lsvgnv"], ["lasvegas"]),
24
+ ("Phoenix", "US", 33.45, -112.07, ["phx"], ["phnxaz"], ["phoenix"]),
25
+ ("Salt Lake City", "US", 40.76, -111.89, ["slc"], ["slkcut"], ["saltlake"]),
26
+ ("Denver", "US", 39.74, -104.99, ["den"], ["dnvrco"], ["denver"]),
27
+ ("Dallas", "US", 32.78, -96.80, ["dfw", "dal"], ["dllstx"], ["dallas"]),
28
+ ("Houston", "US", 29.76, -95.37, ["iah", "hou"], ["hstntx"], ["houston"]),
29
+ ("Austin", "US", 30.27, -97.74, ["aus"], ["austtx"], ["austin"]),
30
+ ("Kansas City", "US", 39.10, -94.58, ["mci"], ["kscymo"], ["kansascity"]),
31
+ ("Minneapolis", "US", 44.98, -93.27, ["msp"], ["mplsmn"], ["minneapolis"]),
32
+ ("Chicago", "US", 41.88, -87.63, ["ord", "chi", "mdw"], ["chcgil"], ["chicago"]),
33
+ ("St. Louis", "US", 38.63, -90.20, ["stl"], ["stlsmo"], ["stlouis"]),
34
+ ("Detroit", "US", 42.33, -83.05, ["dtw"], ["dtrtmi"], ["detroit"]),
35
+ ("Columbus", "US", 39.96, -83.00, ["cmh"], ["clmboh"], ["columbus"]),
36
+ ("Cleveland", "US", 41.50, -81.69, ["cle"], ["clevoh"], ["cleveland"]),
37
+ ("Atlanta", "US", 33.75, -84.39, ["atl"], ["atlnga"], ["atlanta"]),
38
+ ("Miami", "US", 25.76, -80.19, ["mia"], ["miamfl"], ["miami"]),
39
+ ("Tampa", "US", 27.95, -82.46, ["tpa"], ["tamqfl"], ["tampa"]),
40
+ ("Jacksonville", "US", 30.33, -81.66, ["jax"], ["jcvlfl"], ["jacksonville"]),
41
+ ("Charlotte", "US", 35.23, -80.84, ["clt"], ["chrlnc"], ["charlotte"]),
42
+ ("Raleigh", "US", 35.78, -78.64, ["rdu"], ["rlghnc"], ["raleigh"]),
43
+ ("Ashburn", "US", 39.04, -77.49, ["iad"], ["asbnva"], ["ashburn"]),
44
+ ("Washington", "US", 38.91, -77.04, ["dca", "was"], ["washdc"], ["washington"]),
45
+ ("Baltimore", "US", 39.29, -76.61, ["bwi"], ["bltmmd"], ["baltimore"]),
46
+ ("Philadelphia", "US", 39.95, -75.17, ["phl"], ["phlapa"], ["philadelphia"]),
47
+ ("Pittsburgh", "US", 40.44, -80.00, ["pit"], ["pitbpa"], ["pittsburgh"]),
48
+ ("New York", "US", 40.71, -74.01, ["jfk", "lga", "nyc"], ["nycmny", "nwyynyx"], ["newyork"]),
49
+ ("Newark", "US", 40.74, -74.17, ["ewr"], ["nwrknj"], ["newark"]),
50
+ ("Secaucus", "US", 40.79, -74.06, [], ["scaunj"], ["secaucus"]),
51
+ ("Boston", "US", 42.36, -71.06, ["bos"], ["bstnma"], ["boston"]),
52
+ ("Buffalo", "US", 42.89, -78.88, ["buf"], ["bffony"], ["buffalo"]),
53
+ ("Honolulu", "US", 21.31, -157.86, ["hnl"], ["hnllhi"], ["honolulu"]),
54
+ ("Anchorage", "US", 61.22, -149.90, ["anc"], ["anchak"], ["anchorage"]),
55
+ ("Toronto", "CA", 43.65, -79.38, ["yyz", "yto"], ["trnton", "toroon"], ["toronto", "tor"]),
56
+ ("Montreal", "CA", 45.50, -73.57, ["yul"], ["mtrlpq"], ["montreal", "mtl", "mtrl"]),
57
+ ("Ottawa", "CA", 45.42, -75.70, ["yow"], ["ottwon"], ["ottawa"]),
58
+ ("Quebec City", "CA", 46.81, -71.21, ["yqb"], ["qubcpq"], ["quebec"]),
59
+ ("Vancouver", "CA", 49.28, -123.12, ["yvr"], ["vncvbc"], ["vancouver", "van"]),
60
+ ("Calgary", "CA", 51.05, -114.07, ["yyc"], ["clgrab"], ["calgary"]),
61
+ ("Edmonton", "CA", 53.55, -113.49, ["yeg"], ["edtnab"], ["edmonton"]),
62
+ ("Winnipeg", "CA", 49.90, -97.14, ["ywg"], ["wnpgmb"], ["winnipeg"]),
63
+ ("Halifax", "CA", 44.65, -63.58, ["yhz"], ["hlfxns"], ["halifax"]),
64
+ ("Mexico City", "MX", 19.43, -99.13, ["mex"], [], ["mexico"]),
65
+ ("Queretaro", "MX", 20.59, -100.39, ["qro"], [], ["queretaro"]),
66
+ ("Sao Paulo", "BR", -23.55, -46.63, ["gru", "sao"], [], ["saopaulo"]),
67
+ ("Fortaleza", "BR", -3.73, -38.52, ["for"], [], ["fortaleza"]),
68
+ ("Rio de Janeiro", "BR", -22.91, -43.17, ["gig", "rio"], [], ["riodejaneiro"]),
69
+ ("Buenos Aires", "AR", -34.60, -58.38, ["eze", "bue"], [], ["buenosaires"]),
70
+ ("Santiago", "CL", -33.45, -70.67, ["scl"], [], ["santiago"]),
71
+ ("Bogota", "CO", 4.71, -74.07, ["bog"], [], ["bogota"]),
72
+ ("Lima", "PE", -12.05, -77.04, ["lim"], [], ["lima"]),
73
+ ("London", "GB", 51.51, -0.13, ["lhr", "lon", "lcy"], [], ["london", "ldn"]),
74
+ ("Manchester", "GB", 53.48, -2.24, ["man"], [], ["manchester"]),
75
+ ("Dublin", "IE", 53.35, -6.26, ["dub"], [], ["dublin"]),
76
+ ("Amsterdam", "NL", 52.37, 4.90, ["ams"], [], ["amsterdam"]),
77
+ ("Brussels", "BE", 50.85, 4.35, ["bru"], [], ["brussels"]),
78
+ ("Paris", "FR", 48.86, 2.35, ["cdg", "par", "ory"], [], ["paris"]),
79
+ ("Marseille", "FR", 43.30, 5.37, ["mrs"], [], ["marseille"]),
80
+ ("Frankfurt", "DE", 50.11, 8.68, ["fra"], [], ["frankfurt"]),
81
+ ("Berlin", "DE", 52.52, 13.40, ["ber", "txl"], [], ["berlin"]),
82
+ ("Munich", "DE", 48.14, 11.58, ["muc"], [], ["munich", "muenchen"]),
83
+ ("Hamburg", "DE", 53.55, 9.99, ["ham"], [], ["hamburg"]),
84
+ ("Nuremberg", "DE", 49.45, 11.08, ["nue"], [], ["nuremberg", "nuernberg"]),
85
+ ("Dusseldorf", "DE", 51.23, 6.77, ["dus"], [], ["dusseldorf", "duesseldorf"]),
86
+ ("Zurich", "CH", 47.37, 8.54, ["zrh"], [], ["zurich"]),
87
+ ("Geneva", "CH", 46.20, 6.14, ["gva"], [], ["geneva"]),
88
+ ("Vienna", "AT", 48.21, 16.37, ["vie"], [], ["vienna", "wien"]),
89
+ ("Milan", "IT", 45.46, 9.19, ["mxp", "mil", "lin"], [], ["milan", "milano"]),
90
+ ("Rome", "IT", 41.90, 12.50, ["fco", "rom"], [], ["rome", "roma"]),
91
+ ("Madrid", "ES", 40.42, -3.70, ["mad"], [], ["madrid"]),
92
+ ("Barcelona", "ES", 41.39, 2.17, ["bcn"], [], ["barcelona"]),
93
+ ("Lisbon", "PT", 38.72, -9.14, ["lis"], [], ["lisbon", "lisboa"]),
94
+ ("Copenhagen", "DK", 55.68, 12.57, ["cph"], [], ["copenhagen"]),
95
+ ("Stockholm", "SE", 59.33, 18.07, ["arn", "sto"], [], ["stockholm"]),
96
+ ("Oslo", "NO", 59.91, 10.75, ["osl"], [], ["oslo"]),
97
+ ("Helsinki", "FI", 60.17, 24.94, ["hel"], [], ["helsinki"]),
98
+ ("Warsaw", "PL", 52.23, 21.01, ["waw"], [], ["warsaw", "warszawa"]),
99
+ ("Prague", "CZ", 50.08, 14.44, ["prg"], [], ["prague", "praha"]),
100
+ ("Budapest", "HU", 47.50, 19.04, ["bud"], [], ["budapest"]),
101
+ ("Bucharest", "RO", 44.43, 26.10, ["otp", "buh"], [], ["bucharest"]),
102
+ ("Sofia", "BG", 42.70, 23.32, ["sof"], [], ["sofia"]),
103
+ ("Athens", "GR", 37.98, 23.73, ["ath"], [], ["athens"]),
104
+ ("Istanbul", "TR", 41.01, 28.98, ["ist"], [], ["istanbul"]),
105
+ ("Kyiv", "UA", 50.45, 30.52, ["kbp", "iev"], [], ["kyiv", "kiev"]),
106
+ ("Moscow", "RU", 55.76, 37.62, ["svo", "dme", "mow"], [], ["moscow"]),
107
+ ("Tel Aviv", "IL", 32.09, 34.78, ["tlv"], [], ["telaviv"]),
108
+ ("Dubai", "AE", 25.20, 55.27, ["dxb"], [], ["dubai"]),
109
+ ("Fujairah", "AE", 25.13, 56.33, ["fjr"], [], ["fujairah"]),
110
+ ("Mumbai", "IN", 19.08, 72.88, ["bom"], [], ["mumbai"]),
111
+ ("Chennai", "IN", 13.08, 80.27, ["maa"], [], ["chennai"]),
112
+ ("Delhi", "IN", 28.61, 77.21, ["del"], [], ["delhi"]),
113
+ ("Singapore", "SG", 1.35, 103.82, ["sin"], [], ["singapore"]),
114
+ ("Kuala Lumpur", "MY", 3.14, 101.69, ["kul"], [], ["kualalumpur"]),
115
+ ("Jakarta", "ID", -6.21, 106.85, ["cgk", "jkt"], [], ["jakarta"]),
116
+ ("Bangkok", "TH", 13.76, 100.50, ["bkk"], [], ["bangkok"]),
117
+ ("Hong Kong", "HK", 22.32, 114.17, ["hkg"], [], ["hongkong"]),
118
+ ("Taipei", "TW", 25.03, 121.57, ["tpe"], [], ["taipei"]),
119
+ ("Manila", "PH", 14.60, 120.98, ["mnl"], [], ["manila"]),
120
+ ("Tokyo", "JP", 35.68, 139.69, ["nrt", "hnd", "tyo"], [], ["tokyo"]),
121
+ ("Osaka", "JP", 34.69, 135.50, ["kix", "osa"], [], ["osaka"]),
122
+ ("Seoul", "KR", 37.57, 126.98, ["icn", "sel"], [], ["seoul"]),
123
+ ("Beijing", "CN", 39.90, 116.41, ["pek", "bjs"], [], ["beijing"]),
124
+ ("Shanghai", "CN", 31.23, 121.47, ["pvg", "sha"], [], ["shanghai"]),
125
+ ("Guangzhou", "CN", 23.13, 113.26, ["can"], [], ["guangzhou"]),
126
+ ("Sydney", "AU", -33.87, 151.21, ["syd"], [], ["sydney"]),
127
+ ("Melbourne", "AU", -37.81, 144.96, ["mel"], [], ["melbourne"]),
128
+ ("Brisbane", "AU", -27.47, 153.03, ["bne"], [], ["brisbane"]),
129
+ ("Perth", "AU", -31.95, 115.86, ["per"], [], ["perth"]),
130
+ ("Auckland", "NZ", -36.85, 174.76, ["akl"], [], ["auckland"]),
131
+ ("Johannesburg", "ZA", -26.20, 28.05, ["jnb"], [], ["johannesburg"]),
132
+ ("Cape Town", "ZA", -33.92, 18.42, ["cpt"], [], ["capetown"]),
133
+ ("Lagos", "NG", 6.52, 3.38, ["los"], [], ["lagos"]),
134
+ ("Nairobi", "KE", -1.29, 36.82, ["nbo"], [], ["nairobi"]),
135
+ ("Cairo", "EG", 30.04, 31.24, ["cai"], [], ["cairo"]),
136
+ )
137
+
138
+ _iata_d, _clli_d, _words_d, _city_d = {}, {}, {}, {}
139
+ for _name, _cc, _lat, _lon, _iata, _clli, _words in PLACES:
140
+ _p = {"city": _name, "cc": _cc, "lat": _lat, "lon": _lon}
141
+ _city_d[_name.lower().replace(" ", "").replace(".", "")] = _p
142
+ for _c in _iata:
143
+ _iata_d.setdefault(_c, _p)
144
+ for _c in _clli:
145
+ _clli_d[_c] = _p
146
+ for _w in _words:
147
+ _words_d[_w] = _p
148
+
149
+ # read-only views: the gazetteer is constant data, built once at import
150
+ IATA, CLLI, WORDS, BY_CITY = (MappingProxyType(d) for d in (_iata_d, _clli_d, _words_d, _city_d))
151
+
152
+ TOKEN = re.compile(r"[a-z]+")
153
+
154
+
155
+ def from_hostname(name, expect_cc=None, hints=None):
156
+ """Best (place, how) for a router/server hostname, or (None, None).
157
+
158
+ expect_cc: country we already believe the IP is in (GeoIP/ASN). Short codes are only
159
+ trusted when they agree with it; whole city names and CLLI codes are trusted unless
160
+ they contradict it.
161
+
162
+ hints: a hints.Hints whose hostname rules are tried first; default is the packaged hints.json.
163
+ Returns a fresh dict; nothing global is read or changed besides the constant gazetteer.
164
+ """
165
+ if not name:
166
+ return None, None
167
+ if hints is None:
168
+ from . import hints as _hints # late: hints imports this module
169
+ hints = _hints.default()
170
+ place, how = hints.place_for_name(name) # naming schemes from hints.json win
171
+ if place:
172
+ return place, how
173
+ labels = name.lower().rstrip(".").split(".")
174
+ if len(labels) > 2:
175
+ labels = labels[:-2] # drop the registrable domain: "ntt.net" says nothing about where
176
+ cands = []
177
+ for label in labels:
178
+ for raw in re.split(r"[-_]", label):
179
+ for tok in TOKEN.findall(raw):
180
+ if tok in WORDS and len(tok) >= 4:
181
+ cands.append((3, WORDS[tok], "hostname"))
182
+ if len(tok) >= 6 and tok[:6] in CLLI:
183
+ cands.append((3, CLLI[tok[:6]], "CLLI code"))
184
+ if tok in WORDS and len(tok) < 4:
185
+ # numbered ("tor1", Hurricane Electric's Toronto) is a site code; bare ("tor") is just a word
186
+ cands.append((2 if raw != tok else 1, WORDS[tok], "hostname"))
187
+ if len(tok) == 3 and tok in IATA:
188
+ # "lax1", "fra-3", "ord" as a whole token: airport-code convention
189
+ # numbered ("lax1", "yto20") is the airport-code convention; a bare 3-letter label
190
+ # ("icn", "chi") is often just a product/network name, so it needs the country to agree
191
+ cands.append((2 if raw != tok else 1, IATA[tok], "IATA code"))
192
+ best = None
193
+ for score, place, how in cands:
194
+ if expect_cc:
195
+ if place["cc"] != expect_cc:
196
+ continue
197
+ score += 1
198
+ elif score < 2:
199
+ continue # a bare short code with nothing to confirm it
200
+ if best is None or score > best[0]:
201
+ best = (score, place, how)
202
+ return (dict(best[1]), best[2]) if best else (None, None)
203
+
204
+
205
+ def city_lookup(city, cc=None):
206
+ p = BY_CITY.get((city or "").lower().replace(" ", "").replace(".", ""))
207
+ if p and (not cc or p["cc"] == cc):
208
+ return dict(p)
209
+ return None
210
+
211
+
212
+ def contradicts(geo, place, km=500):
213
+ """True when a GeoIP fix and a place from a name are further apart than `km`."""
214
+ if not geo or geo.get("lat") is None:
215
+ return False
216
+ p1, p2 = math.radians(geo["lat"]), math.radians(place["lat"])
217
+ a = math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(place["lon"] - geo["lon"]) / 2) ** 2
218
+ return 12742 * math.asin(math.sqrt(a)) > km
219
+
220
+
221
+ def is_coarse(geo):
222
+ """True when GeoIP only knows the country (or nothing)."""
223
+ return not geo or geo.get("lat") is None or (geo.get("radius") or 0) >= 500 or not geo.get("city")
pewpath/hints.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "_about": "Location hints shipped with pewpath: general, public facts about networks only. Callers can load extra files of the same schema. Schema: see hints.py.",
3
+ "asn": {
4
+ "20940": {"kind": "edge", "name": "Akamai International"},
5
+ "16625": {"kind": "edge", "name": "Akamai Technologies"},
6
+ "36183": {"kind": "edge", "name": "Akamai Technologies (Apple Private Relay egress, edge)"},
7
+ "19679": {"kind": "edge", "name": "Dropbox (edge PoPs)"},
8
+ "2906": {"kind": "edge", "name": "Netflix Open Connect"},
9
+ "15133": {"kind": "edge", "name": "Edgecast"},
10
+ "22822": {"kind": "edge", "name": "Limelight / Edgio"},
11
+ "13414": {"kind": "edge", "name": "Twitter / X"},
12
+ "393220": {"city": "San Jose", "cc": "US", "name": "ARIN (SJC site)"},
13
+ "393225": {"city": "Ashburn", "cc": "US", "name": "ARIN (IAD site)"},
14
+ "394018": {"city": "Seattle", "cc": "US", "name": "ARIN (SEA site)"}
15
+ },
16
+ "hostname": [
17
+ {
18
+ "note": "Tailscale DERP relays: derpN = region N (login.tailscale.com/derpmap/default)",
19
+ "pattern": "^derp(\\d+)[a-z]?\\.tailscale\\.com$",
20
+ "map": {"1": "New York", "2": "San Francisco", "3": "Singapore", "4": "Frankfurt", "5": "Sydney",
21
+ "6": "Mumbai", "7": "Tokyo", "8": "London", "9": "Dallas", "10": "Seattle", "11": "Sao Paulo",
22
+ "12": "Chicago", "13": "Denver", "14": "Amsterdam", "15": "Johannesburg", "16": "Miami",
23
+ "17": "Los Angeles", "18": "Paris", "19": "Madrid", "20": "Hong Kong", "21": "Toronto",
24
+ "22": "Warsaw", "23": "Dubai", "25": "Nairobi", "26": "Nuremberg", "27": "Ashburn", "28": "Helsinki"}
25
+ },
26
+ {
27
+ "note": "Apple edge: <country><airport><n>-vip-... (e.g. uschi6-vip-...)",
28
+ "pattern": "^[a-z]{2}([a-z]{3})\\d+-vip-",
29
+ "iata": 1
30
+ },
31
+ {
32
+ "note": "AWS EC2 public DNS names carry the region",
33
+ "pattern": "\\.(us-east-2|us-west-1|us-west-2|ca-central-1|eu-west-1|eu-west-2|eu-central-1|ap-northeast-1|ap-southeast-1|ap-southeast-2)\\.compute\\.amazonaws\\.com$",
34
+ "map": {"us-east-2": "Columbus", "us-west-1": "San Jose", "us-west-2": "Portland", "ca-central-1": "Montreal",
35
+ "eu-west-1": "Dublin", "eu-west-2": "London", "eu-central-1": "Frankfurt", "ap-northeast-1": "Tokyo",
36
+ "ap-southeast-1": "Singapore", "ap-southeast-2": "Sydney"}
37
+ },
38
+ {
39
+ "note": "AWS us-east-1 EC2 names: ec2-...compute-1.amazonaws.com",
40
+ "pattern": "\\.compute-1\\.amazonaws\\.com$",
41
+ "city": "Ashburn", "cc": "US"
42
+ },
43
+ {
44
+ "note": "Hurricane Electric router names use their own site codes: core1.ash1.he.net, core2.fmt2.he.net",
45
+ "pattern": "\\.(ash|fmt)\\d+\\.he\\.net$",
46
+ "map": {"ash": "Ashburn", "fmt": "Fremont"}
47
+ }
48
+ ],
49
+ "prefix": {}
50
+ }
pewpath/hints.py ADDED
@@ -0,0 +1,136 @@
1
+ """Location hints / corrections, loaded at startup from JSON (stdlib only).
2
+
3
+ Files, merged in order (later wins):
4
+ hints.json shipped with pewpath: general, public facts about networks (CDN/edge
5
+ ASNs, router/host naming schemes). Contributions welcome.
6
+ extra paths passed to load(): files of your own, same schema (e.g. where your VPS really is)
7
+
8
+ Schema (all sections optional):
9
+ {
10
+ "asn": {"36183": {"kind": "edge", "name": "Akamai"}, # served from a PoP near you
11
+ "393220": {"city": "San Jose", "cc": "US"}}, # this ASN lives in one place
12
+ "prefix": {"203.0.113.0/24": {"city": "Toronto", "cc": "CA"}, # or "lat"/"lon" instead of city
13
+ "198.51.100.7/32": {"lat": 43.7, "lon": -79.4, "label": "my VPS"}},
14
+ "hostname": [{"pattern": "^derp(\\\\d+)[a-z]?\\\\.tailscale\\\\.com$", "map": {"21": "Toronto"}},
15
+ {"pattern": "^[a-z]{2}([a-z]{3})\\\\d+-vip-", "iata": 1}] # capture group 1 is an airport code
16
+ }
17
+ """
18
+ import json
19
+ import os
20
+ import re
21
+ from functools import lru_cache
22
+ from types import MappingProxyType
23
+
24
+ from . import geohint
25
+
26
+ HERE = os.path.dirname(os.path.abspath(__file__))
27
+ DEFAULT_FILES = [os.path.join(HERE, "hints.json")]
28
+
29
+
30
+ def _place(spec):
31
+ """{"city": ..., "cc": ...} or {"lat": ..., "lon": ...} -> place dict, or None."""
32
+ if spec.get("lat") is not None and spec.get("lon") is not None:
33
+ return {"city": spec.get("city") or spec.get("label") or "", "cc": spec.get("cc", ""),
34
+ "lat": float(spec["lat"]), "lon": float(spec["lon"])}
35
+ p = geohint.city_lookup(spec.get("city", ""), spec.get("cc") or None)
36
+ return dict(p) if p else None
37
+
38
+
39
+ class Hints:
40
+ """Hostname rules, ASN facts and prefix hints. Build with load(), then use: after freeze() (which load() calls)
41
+ the object is read-only, so one instance can be shared freely and two never affect each other."""
42
+
43
+ _frozen = False
44
+
45
+ def __setattr__(self, name, value):
46
+ if self._frozen:
47
+ raise AttributeError("Hints is frozen")
48
+ object.__setattr__(self, name, value)
49
+
50
+ def freeze(self):
51
+ """Make the contents read-only (tuples, frozensets, read-only mappings). Returns self."""
52
+ if not self._frozen:
53
+ self.edge_asns, self.anycast_asns = frozenset(self.edge_asns), frozenset(self.anycast_asns)
54
+ self.asn_places = MappingProxyType(dict(self.asn_places))
55
+ self.prefixes, self.rules = tuple(self.prefixes), tuple(self.rules)
56
+ self.files, self.errors = tuple(self.files), tuple(self.errors)
57
+ object.__setattr__(self, "_frozen", True)
58
+ return self
59
+
60
+ def __init__(self):
61
+ self.edge_asns, self.anycast_asns, self.asn_places = set(), set(), {}
62
+ self.prefixes = [] # [(cidr, place, label)]: the caller builds its own lookup from these
63
+ self.rules = [] # [(compiled, spec)]
64
+ self.files, self.errors = [], []
65
+
66
+ def load(self, paths):
67
+ """Merge JSON files into this (not yet frozen) object, later files winning. Returns self."""
68
+ if self._frozen:
69
+ raise RuntimeError("Hints is frozen")
70
+ for path in paths:
71
+ if not path or not os.path.exists(path):
72
+ continue
73
+ try:
74
+ with open(path, encoding="utf-8") as fh:
75
+ self.merge(json.load(fh))
76
+ self.files.append(path)
77
+ except (OSError, ValueError) as e:
78
+ self.errors.append(f"{path}: {e}")
79
+ return self
80
+
81
+ def merge(self, d):
82
+ if self._frozen:
83
+ raise RuntimeError("Hints is frozen")
84
+ for asn, spec in (d.get("asn") or {}).items():
85
+ try:
86
+ n = int(str(asn).upper().removeprefix("AS"))
87
+ except ValueError:
88
+ self.errors.append(f"bad asn {asn!r}")
89
+ continue
90
+ kind = spec.get("kind")
91
+ if kind == "edge":
92
+ self.edge_asns.add(n)
93
+ elif kind == "anycast":
94
+ self.anycast_asns.add(n)
95
+ p = _place(spec)
96
+ if p:
97
+ self.asn_places[n] = p
98
+ for cidr, spec in (d.get("prefix") or {}).items():
99
+ p = _place(spec)
100
+ if p:
101
+ self.prefixes.append((cidr, p, spec.get("label", "")))
102
+ else:
103
+ self.errors.append(f"prefix {cidr}: unknown city {spec.get('city')!r} (give lat/lon)")
104
+ for spec in d.get("hostname") or []:
105
+ try:
106
+ self.rules.append((re.compile(spec["pattern"], re.I), spec))
107
+ except (KeyError, re.error) as e:
108
+ self.errors.append(f"hostname rule {spec!r}: {e}")
109
+
110
+ def place_for_name(self, name):
111
+ """(place, how) from the hostname rules, or (None, None)."""
112
+ for rx, spec in self.rules:
113
+ m = rx.search(name or "")
114
+ if not m:
115
+ continue
116
+ if "map" in spec:
117
+ city = spec["map"].get(m.group(1))
118
+ p = geohint.city_lookup(city) if city else None
119
+ elif "iata" in spec:
120
+ p = geohint.IATA.get(m.group(int(spec["iata"])).lower())
121
+ else:
122
+ p = _place(spec)
123
+ if p:
124
+ return dict(p), "hint: " + spec.get("note", spec["pattern"])[:60]
125
+ return None, None
126
+
127
+
128
+ def load(extra=()):
129
+ """A NEW read-only Hints: the packaged hints.json plus the extra files. Changes no global state."""
130
+ return Hints().load([*DEFAULT_FILES, *extra]).freeze()
131
+
132
+
133
+ @lru_cache(maxsize=1)
134
+ def default():
135
+ """The shared Hints built once from the packaged hints.json; used when a function gets no `hints`."""
136
+ return load()
pewpath/hops.py ADDED
@@ -0,0 +1,107 @@
1
+ """Hop rules: inferences about a traceroute path, as pure functions over its hop list (no network, no I/O).
2
+
3
+ A hop is a dict as a caller stores it with a trace: ttl, ip, name, rtt, asn, geo, and the annotations a caller adds
4
+ (`ix` when the address is on an IXP peering LAN). This module only reads and annotates those dicts.
5
+
6
+ refine_hop_geo place a hop from its router name or the exchange it sits on, when GeoIP is only coarse
7
+ annotate_shared_ixs at an AS boundary, name the exchanges both networks are members of (a hint, not proof)
8
+ placed_path the located hops of a trace as map points, and how many hops follow the last one
9
+ """
10
+ from . import geohint
11
+
12
+ # GeoIP fixes from these sources are authoritative: a router name does not override them
13
+ TRUSTED_SRC = ("hint", "cloud")
14
+
15
+
16
+ def refine_hop_geo(hop, hints=None):
17
+ """GeoIP often only knows a router's country (or its owner's HQ). Router names usually say
18
+ where they are (yto20, sttlwa01, frankfurt): use that when GeoIP has no city, or when a name that
19
+ stands on its own (numbered site code, CLLI, city word) puts the router somewhere GeoIP does not.
20
+
21
+ Updates and returns `hop`, and changes nothing else. hints: a hints.Hints; default is the packaged one."""
22
+ g = hop.get("geo") or {}
23
+ ix = hop.get("ix")
24
+ if ix and not hop.get("geo_src") and (geohint.is_coarse(g) or g.get("anycast")):
25
+ # an address on an exchange's peering LAN is a router port at the exchange, wherever its owner is registered
26
+ place = geohint.city_lookup(ix.get("city"), ix.get("country"))
27
+ if place:
28
+ hop["geo"] = dict(g, lat=place["lat"], lon=place["lon"], radius=50, city=place["city"], cc=place["cc"])
29
+ hop["geo"].pop("anycast", None)
30
+ hop["geo_src"] = "ix"
31
+ return hop
32
+ if hop.get("geo_src") or not hop.get("name"):
33
+ hop.setdefault("geo_src", "geoip")
34
+ return hop
35
+ if not (geohint.is_coarse(g) or g.get("anycast")):
36
+ # a precise-looking fix is often the owner's registered address (a backbone router "in Florida"
37
+ # named tor2): believe a strong name over it, unless the fix comes from a trusted source
38
+ place, how = geohint.from_hostname(hop["name"], hints=hints)
39
+ if place and g.get("loc_src") not in TRUSTED_SRC and geohint.contradicts(g, place):
40
+ hop["geo"] = dict(g, lat=place["lat"], lon=place["lon"], radius=50, city=place["city"], cc=place["cc"])
41
+ hop["geo_src"] = how
42
+ else:
43
+ hop["geo_src"] = "geoip"
44
+ return hop
45
+ # a coarse fix's country is often the registrant's, not the router's: only trust it to
46
+ # confirm weak (short-code) matches, strong ones (CLLI, numbered IATA, city names) stand alone
47
+ place, how = geohint.from_hostname(hop["name"], hints=hints)
48
+ if place is None and g.get("cc"):
49
+ place, how = geohint.from_hostname(hop["name"], g["cc"], hints)
50
+ if place:
51
+ hop["geo"] = dict(g, lat=place["lat"], lon=place["lon"], radius=50, city=place["city"], cc=place["cc"])
52
+ hop["geo"].pop("anycast", None)
53
+ hop["geo_src"] = how
54
+ else:
55
+ hop["geo_src"] = "geoip"
56
+ return hop
57
+
58
+
59
+ def annotate_shared_ixs(hops, ix_names):
60
+ """At each AS boundary with no hop on an IXP peering LAN between the two networks, set `ix_guess` to the
61
+ exchanges both are members of. It is only a hint: the two may peer privately or at another exchange.
62
+
63
+ ix_names(asn) -> set of exchange names that network is a member of.
64
+ """
65
+ prev, lan = None, False
66
+ for h in hops:
67
+ if h.get("ix"):
68
+ lan = True
69
+ asn = h.get("asn")
70
+ if not asn:
71
+ continue
72
+ if prev and asn != prev and not lan:
73
+ common = sorted(ix_names(prev) & ix_names(asn))
74
+ if common:
75
+ h["ix_guess"] = common[:40]
76
+ lan = False # only an exchange hop *between* two networks' hops counts
77
+ prev = asn
78
+ return hops
79
+
80
+
81
+ def placed_path(hops, hints=None):
82
+ """{path: [[lon, lat], ...], hops: [[hop, ...], ...], tail: n} for the hops we could place, or None.
83
+
84
+ Country-level fixes are centroids, not router locations, so they are skipped. Hops in one place share a
85
+ point. `tail` counts the hops after the last placed one: few means the target is close to that point.
86
+ Like refine_hop_geo it annotates the hop dicts it is given (geo, geo_src) and changes nothing else.
87
+ """
88
+ pts, info, last_placed = [], [], -1
89
+ for n, h in enumerate(hops):
90
+ refine_hop_geo(h, hints) # traces saved before hints existed get them too
91
+ g = h.get("geo") or {}
92
+ if g.get("lat") is None or (g.get("radius") or 0) >= 500 or g.get("anycast"):
93
+ continue
94
+ p = [round(g["lon"], 3), round(g["lat"], 3)]
95
+ hop = {"ttl": h.get("ttl"), "ip": h.get("ip"), "name": h.get("name", ""), "rtt": h.get("rtt"),
96
+ "asn": h.get("asn"), "as_name": h.get("as_name") or h.get("owner", ""),
97
+ "city": g.get("city", ""), "cc": g.get("cc", ""), "geo_src": h.get("geo_src", "geoip"),
98
+ "ix": (h.get("ix") or {}).get("name")}
99
+ last_placed = n
100
+ if pts and abs(pts[-1][0] - p[0]) < 0.3 and abs(pts[-1][1] - p[1]) < 0.3:
101
+ info[-1].append(hop) # same place as the previous hop: one dot, several routers
102
+ continue
103
+ pts.append(p)
104
+ info.append([hop])
105
+ if not pts:
106
+ return None
107
+ return {"path": pts, "hops": info, "tail": len(hops) - 1 - last_placed}
pewpath/py.typed ADDED
File without changes
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: pewpath
3
+ Version: 0.1.0
4
+ Summary: Infer where a traceroute path goes from its router hostnames. Pure Python, no dependencies, no network.
5
+ License-Expression: MIT
6
+ Project-URL: Documentation, https://github.com/worldwise001/pewpath/blob/main/docs/usage.md
7
+ Project-URL: Homepage, https://github.com/worldwise001/pewpath
8
+ Project-URL: Source, https://github.com/worldwise001/pewpath
9
+ Project-URL: Issues, https://github.com/worldwise001/pewpath/issues
10
+ Keywords: traceroute,geolocation,geoip,hostname,asn,bgp,peering,ixp,network
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Topic :: System :: Networking
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Dynamic: license-file
25
+
26
+ # pewpath
27
+
28
+ [![CI](https://github.com/worldwise001/pewpath/actions/workflows/ci.yml/badge.svg)](https://github.com/worldwise001/pewpath/actions/workflows/ci.yml)
29
+ [![PyPI](https://img.shields.io/pypi/v/pewpath)](https://pypi.org/project/pewpath/)
30
+ [![Python](https://img.shields.io/pypi/pyversions/pewpath)](https://pypi.org/project/pewpath/)
31
+ [![License: MIT](https://img.shields.io/github/license/worldwise001/pewpath)](LICENSE)
32
+
33
+ Infer where a traceroute path goes, from the router hostnames along it. Pure Python, standard library only, and it never touches the network.
34
+
35
+ Router names usually say where the router is (`ae1.fra1.example.net` is probably Frankfurt). pewpath reads those names, places hops that GeoIP only knows to the country, and turns the located hops into points you can draw on a map.
36
+
37
+ > [!WARNING]
38
+ > **Experimental, and written almost entirely by an AI (Claude) under human direction.** It has unit tests, but it hasn't had a careful human review. Its answers are inferences from hostnames and hints, not ground truth, so treat every placement as a guess. Read the code before relying on it for anything you care about.
39
+
40
+ ## Install
41
+
42
+ ```sh
43
+ pip install pewpath
44
+ ```
45
+
46
+ Requires Python 3.10 or later.
47
+
48
+ ## Use it
49
+
50
+ Place one hostname:
51
+
52
+ ```python
53
+ import pewpath
54
+
55
+ place, how = pewpath.from_hostname("core2.fmt2.he.net")
56
+ print(place) # {'city': 'Fremont', 'cc': 'US', 'lat': 37.55, 'lon': -121.99}
57
+ ```
58
+
59
+ Place a whole trace. You run the traceroute and the GeoIP lookup; pass the hops in as dicts:
60
+
61
+ ```python
62
+ hops = [
63
+ {"ttl": 1, "ip": "192.0.2.1", "name": "gw.example.net", "asn": 64500},
64
+ {"ttl": 2, "ip": "198.51.100.1", "name": "ae1.fra1.example.net", "asn": 64501},
65
+ ]
66
+
67
+ print(pewpath.placed_path(hops)["path"]) # [[8.68, 50.11]], one [lon, lat] per place
68
+ ```
69
+
70
+ Hops with nothing to go on are left out.
71
+
72
+ ## Docs
73
+
74
+ - [Usage guide](https://github.com/worldwise001/pewpath/blob/main/docs/usage.md): hop format, results, guessing the exchange between two networks.
75
+ - [Custom hints](https://github.com/worldwise001/pewpath/blob/main/docs/hints.md): add your own hostname rules and network facts.
76
+ - [API reference](https://github.com/worldwise001/pewpath/blob/main/docs/api.md): every function, state and side effects, versioning.
77
+
78
+ ## License
79
+
80
+ MIT.
@@ -0,0 +1,11 @@
1
+ pewpath/__init__.py,sha256=2zFM9sutt5vD6AgUzad9k5oajOVFXgIQ45LguwHBKNg,417
2
+ pewpath/geohint.py,sha256=FC0UhG1OE3sL2fJxVDbNKQXv9gCGPBqbG2bqM9kJGuU,13075
3
+ pewpath/hints.json,sha256=sA4RGS1Z5pLd8p6qvIjNntoFjeMRMqKKxx8wZdo_BvA,2764
4
+ pewpath/hints.py,sha256=vsRci0aBDkrNOyl5HErnG_sxrMtK01rEHPRd15p8axA,5745
5
+ pewpath/hops.py,sha256=j2lASxsOtgEK1ZuYzJPq6__eUzG3du09UnAaWsxSEis,5506
6
+ pewpath/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ pewpath-0.1.0.dist-info/licenses/LICENSE,sha256=mGWx27e4b1mani8EpM2dfyLbVdYmJS7y5LRrw_Wg6zs,1069
8
+ pewpath-0.1.0.dist-info/METADATA,sha256=3uprhUuHbVRHF2ioNA6xmTk0yvsGt7l8ZApiIiwiqgs,3374
9
+ pewpath-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ pewpath-0.1.0.dist-info/top_level.txt,sha256=EGzVe3ZGQSf1iKz8kpAveWGuHUws_A9hQC9npKrEK1s,8
11
+ pewpath-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 worldwise001
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pewpath