pingerplot 1.6.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.
pingerplot/launch.py ADDED
@@ -0,0 +1,37 @@
1
+ """Start the window, or say what's missing.
2
+
3
+ tkinter comes with Python on Windows and from python.org on macOS, but most
4
+ Linux distributions package it separately. Without it ``import tkinter``
5
+ fails inside gui.py's imports, before the app can say anything, and the
6
+ user gets a ModuleNotFoundError traceback. Every way of starting the window
7
+ (main.py, ``python -m pingerplot``, the ``pingerplot`` command) comes here
8
+ first.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import sys
13
+
14
+ TK_PACKAGES = (
15
+ ("Debian, Ubuntu, Mint", "sudo apt install python3-tk"),
16
+ ("Fedora, RHEL", "sudo dnf install python3-tkinter"),
17
+ ("Arch, Manjaro", "sudo pacman -S tk"),
18
+ ("openSUSE", "sudo zypper install python3-tk"),
19
+ )
20
+
21
+
22
+ def missing_tk_message() -> str:
23
+ width = max(len(d) for d, _c in TK_PACKAGES)
24
+ rows = "\n".join(f" {d + ':':<{width + 1}} {c}" for d, c in TK_PACKAGES)
25
+ return ("PingerPlot's window needs Tk (Python's tkinter), and this Python doesn't have it.\n"
26
+ f"Install it for your system, then start PingerPlot again:\n\n{rows}\n\n"
27
+ "The headless runner needs no Tk: python3 -m pingerplot.headless --help")
28
+
29
+
30
+ def main() -> None:
31
+ try:
32
+ import tkinter # noqa: F401
33
+ except ImportError:
34
+ print(missing_tk_message(), file=sys.stderr)
35
+ raise SystemExit(1)
36
+ from .gui import main as gui_main
37
+ gui_main()
pingerplot/locating.py ADDED
@@ -0,0 +1,248 @@
1
+ """Where a router is: its name first, then the IP database, unless the round
2
+ trips show that the database's answer can't be right.
3
+
4
+ The IP database is good for homes and offices and poor for the backbone
5
+ (places.py says why): it puts a carrier's routers at its registered address,
6
+ and an anycast address where its block was registered, so 1.1.1.1 answering
7
+ in 3 ms "is" in Brisbane. A reply can't come from farther away than light in
8
+ fiber travels in half its round trip, so two routers are within half the sum
9
+ of their round trips of each other: each is that close to this computer (the
10
+ triangle inequality), wherever this computer is. A database answer farther
11
+ than that from a router whose name places it is impossible, and is left out:
12
+ no point on the map, a blank cell, and Details says why. It is never replaced
13
+ by a guess.
14
+
15
+ Physics can't rule out much near this computer: from Maine, any reply slower
16
+ than about 2 ms could come from Washington. So one judgement is added: a
17
+ router that answers within NEAR_MS of the hop just before or after it on the
18
+ same path, placed by its name, is a link away from it, and a database answer
19
+ more than FAR_KM from there is almost certainly a registered address. Only
20
+ when both round trips mean what they seem: inside an MPLS tunnel every
21
+ router reports the round trip of the tunnel's far end (Atlanta and San
22
+ Antonio both at 54 ms), and a router can be slow to answer. So the hop is
23
+ skipped when a later hop answers faster, and the named hop is used only when
24
+ its round trip is about the quickest seen for its city. Even then it isn't
25
+ proof (a reply can come back a shorter way than it went), so it too only
26
+ leaves the answer out.
27
+
28
+ Every place that shows a router's location gets it from a Locator, so the
29
+ tables, the map, Details, the CSV export and "where the trouble is" agree.
30
+ The round trips must come from this computer, and from one place: a laptop
31
+ carried across the country while recording could see a correct answer left
32
+ out, never a wrong one drawn.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import math
37
+ from dataclasses import dataclass
38
+ from typing import Iterable, List, Optional, Sequence, Tuple
39
+
40
+ from . import places
41
+
42
+ # Light in fiber covers about 204 km per millisecond (c / 1.47). Rounded
43
+ # down, so a doubt only ever favors the database.
44
+ FIBER_KM_PER_MS = 200.0
45
+ SLACK_KM = 150.0 # city-center coordinates and metro sprawl
46
+ # Windows reports whole milliseconds (IcmpSendEcho's RoundTripTime), "<1" as
47
+ # 0: a reading can be up to this much under the real round trip.
48
+ CLOCK_MS = 1.0
49
+ # The neighbor judgement: a symmetric 2 ms covers about 200 km of fiber, so
50
+ # 500 km leaves room for a reply that came back another way.
51
+ NEAR_MS = 2.0
52
+ NEAR_HOPS = 2 # how many links away the named hop may be
53
+ FAR_KM = 500.0
54
+
55
+
56
+ def distance_km(a: Tuple[float, float], b: Tuple[float, float]) -> float:
57
+ """Great-circle distance between two (lat, lon) points."""
58
+ la1, lo1, la2, lo2 = map(math.radians, (a[0], a[1], b[0], b[1]))
59
+ h = math.sin((la2 - la1) / 2) ** 2 + math.cos(la1) * math.cos(la2) * math.sin((lo2 - lo1) / 2) ** 2
60
+ return 2 * 6371.0 * math.asin(min(1.0, math.sqrt(h)))
61
+
62
+
63
+ def reach_km(a_ms: float, b_ms: float) -> float:
64
+ """How far apart two routers can be, given each one's best round trip."""
65
+ return (a_ms + b_ms + 2 * CLOCK_MS) / 2 * FIBER_KM_PER_MS + SLACK_KM
66
+
67
+
68
+ def _usable(ms) -> bool:
69
+ return isinstance(ms, (int, float)) and math.isfinite(ms) and ms >= 0
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Anchor:
74
+ """A router placed by its name, with its best round trip from here."""
75
+ lat: float
76
+ lon: float
77
+ best: float
78
+ city: str
79
+ router: str # its name, for saying which router ruled an answer out
80
+
81
+ @property
82
+ def point(self) -> Tuple[float, float]:
83
+ return self.lat, self.lon
84
+
85
+
86
+ def anchors(routers: Iterable[Tuple[Optional[str], Optional[float]]]) -> List[Anchor]:
87
+ """The anchors among ``routers`` (``(hostname, best_ms)`` pairs): those
88
+ whose names place them, the quickest in each city (it gives the tightest
89
+ bound; the others add nothing), less any that contradict the rest."""
90
+ best: dict = {}
91
+ for host, ms in routers:
92
+ if not _usable(ms):
93
+ continue
94
+ place = places.from_name(host)
95
+ point = places.coords(place)
96
+ if point is None:
97
+ continue
98
+ if place.city not in best or ms < best[place.city].best:
99
+ best[place.city] = Anchor(point[0], point[1], float(ms), place.city, host or "")
100
+ return _consistent(list(best.values()))
101
+
102
+
103
+ def _conflict(a: Anchor, b: Anchor) -> bool:
104
+ return distance_km(a.point, b.point) > reach_km(a.best, b.best)
105
+
106
+
107
+ def _consistent(found: List[Anchor]) -> List[Anchor]:
108
+ """Drop anchors that contradict other anchors. A name is a hint: one
109
+ router named after the far end of a transatlantic link would otherwise
110
+ rule out every correct answer near this computer. The one contradicting
111
+ the most goes first, and when two contradict only each other there's no
112
+ telling which is wrong, so both go."""
113
+ keep = found
114
+ while True:
115
+ counts = [sum(_conflict(a, b) for b in keep if b is not a) for a in keep]
116
+ worst = max(counts, default=0)
117
+ if worst == 0:
118
+ return keep
119
+ keep = [a for a, n in zip(keep, counts) if n < worst]
120
+
121
+
122
+ def ruled_out(point: Tuple[float, float], best: Optional[float],
123
+ found: Sequence[Anchor]) -> Optional[Anchor]:
124
+ """The anchor that proves a router whose best round trip is ``best``
125
+ can't be at ``point`` (the one it misses by most), or None."""
126
+ if not _usable(best):
127
+ return None
128
+ worst, by = None, 0.0
129
+ for a in found:
130
+ over = distance_km(point, a.point) - reach_km(best, a.best)
131
+ if over > by:
132
+ worst, by = a, over
133
+ return worst
134
+
135
+
136
+ def _ms(ms: float) -> str:
137
+ return f"{ms:.0f}"
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class Where:
142
+ """One router's location, and how it was decided."""
143
+ place: Optional[places.Place] # from its name
144
+ info: object # the IP database's answer (GeoInfo), used or not
145
+ point: Optional[Tuple[float, float]] # where to draw it
146
+ source: str # where the point came from: "name", "ip" or ""
147
+ why: str = "" # why the database's answer was left out
148
+
149
+ @property
150
+ def text(self) -> str:
151
+ """For a table cell."""
152
+ if self.place is not None:
153
+ return str(self.place)
154
+ if self.source != "ip":
155
+ return ""
156
+ info = self.info
157
+ if info.city and info.country:
158
+ return f"{info.city}, {places.country_code(info.country)}"
159
+ return info.city or info.country
160
+
161
+ @property
162
+ def label(self) -> str:
163
+ """For the map: the city alone."""
164
+ if self.source == "name":
165
+ return self.place.city
166
+ if self.source == "ip":
167
+ return self.info.city or self.info.country
168
+ return ""
169
+
170
+
171
+ @dataclass(frozen=True)
172
+ class _Hop:
173
+ address: Optional[str]
174
+ hostname: Optional[str]
175
+ best: Optional[float]
176
+
177
+
178
+ def path_of(views) -> List[Tuple[int, Optional[str], Optional[str], Optional[float]]]:
179
+ """A path for a Locator from hop views: ``(ttl, address, hostname,
180
+ best)``, where best is the current router's own best round trip."""
181
+ return [(v.ttl, v.address, v.hostname, getattr(v, "best_here", None)) for v in views]
182
+
183
+
184
+ class Locator:
185
+ """Locations for the routers of one path, checked against ``anchors``
186
+ (from every path measured from here at about the same time). ``geo``
187
+ is the IP database (``.get(address)``)."""
188
+
189
+ def __init__(self, geo, found: Sequence[Anchor] = (), path=()) -> None:
190
+ self.geo = geo
191
+ self.anchors = list(found)
192
+ self._quickest = {a.city: a.best for a in self.anchors}
193
+ self._hops = {ttl: _Hop(addr, host, best) for ttl, addr, host, best in path}
194
+ self._named: List[Tuple[int, Anchor]] = [] # the path's routers placed by name
195
+ for ttl, _addr, host, best in sorted(path, key=lambda h: h[0]):
196
+ place = places.from_name(host)
197
+ point = places.coords(place)
198
+ if point is not None and _usable(best):
199
+ self._named.append((ttl, Anchor(point[0], point[1], float(best), place.city, host)))
200
+
201
+ def where(self, address: Optional[str], hostname: Optional[str],
202
+ best: Optional[float] = None, ttl: Optional[int] = None) -> Where:
203
+ """``best`` is this router's own best round trip; given only ``ttl``,
204
+ it's taken from the path when the path's router there is this one."""
205
+ if best is None and ttl in self._hops and self._hops[ttl].address == address:
206
+ best = self._hops[ttl].best
207
+ place = places.from_name(hostname)
208
+ info = self.geo.get(address) if address else None
209
+ point = places.coords(place)
210
+ if point is not None:
211
+ return Where(place, info, point, "name")
212
+ if info is None:
213
+ return Where(place, None, None, "")
214
+ why = self._doubt((info.lat, info.lon), info, best, ttl)
215
+ if why:
216
+ return Where(place, info, None, "", why)
217
+ return Where(place, info, (info.lat, info.lon), "ip")
218
+
219
+ def view(self, v) -> Where:
220
+ """A hop view's router."""
221
+ return self.where(v.address, v.hostname, getattr(v, "best_here", None), v.ttl)
222
+
223
+ def _doubt(self, point, info, best, ttl) -> str:
224
+ there = info.city or info.country or "that place"
225
+ a = ruled_out(point, best, self.anchors)
226
+ if a is not None:
227
+ return (f"Not possible: it answers in {_ms(best)} ms and {a.router} ({a.city}, from its "
228
+ f"name) in {_ms(a.best)} ms, so the two are within about "
229
+ f"{reach_km(best, a.best):,.0f} km of each other, and {there} is "
230
+ f"{distance_km(point, a.point):,.0f} km from {a.city}.")
231
+ if ttl is None or not _usable(best) or self._inflated(ttl, best):
232
+ return ""
233
+ for t, n in self._named:
234
+ if not 0 < abs(t - ttl) <= NEAR_HOPS or self._inflated(t, n.best):
235
+ continue
236
+ if n.best > self._quickest.get(n.city, -math.inf) + NEAR_MS:
237
+ continue # slower than its city's quickest router: a tunnel or a slow answer
238
+ far = distance_km(point, n.point)
239
+ if abs(best - n.best) <= NEAR_MS and far > FAR_KM:
240
+ return (f"Doubtful: it answers within {NEAR_MS:g} ms of hop {t}, {n.router} ({n.city}, "
241
+ f"from its name), so it's most likely a link away from it, and {there} is "
242
+ f"{far:,.0f} km from {n.city}.")
243
+ return ""
244
+
245
+ def _inflated(self, ttl: int, best: float) -> bool:
246
+ """Whether a later hop on the path answers faster than ``best``: the
247
+ router at ``ttl`` is inside an MPLS tunnel or slow to answer."""
248
+ return any(t > ttl and _usable(h.best) and h.best < best - NEAR_MS for t, h in self._hops.items())
pingerplot/model.py ADDED
@@ -0,0 +1,410 @@
1
+ """Data model and per-hop statistics.
2
+
3
+ Pure standard-library, no Tk or ctypes here so it stays unit-testable on any
4
+ platform. A :class:`Hop` owns a bounded ring buffer of :class:`Sample`s and
5
+ derives all statistics from it. :class:`HopView` is an immutable snapshot the
6
+ GUI renders without touching the live (monitor-owned, lock-protected) Hop.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ import time
12
+ from collections import deque
13
+ from itertools import islice
14
+ from dataclasses import dataclass
15
+ from typing import Deque, Dict, List, Optional
16
+
17
+ DEFAULT_HISTORY = 600 # samples kept per hop (~25 min at a 2.5 s interval)
18
+ MAX_ROUTERS_PER_HOP = 64 # routers whose best round trip a hop remembers (ECMP, reroutes)
19
+
20
+ # What a saved time or round trip can plausibly be. JSON as Python reads it
21
+ # allows NaN, Infinity and 1e300; a session file is someone else's, and a time
22
+ # like that made time.localtime() raise on every refresh of the tab showing it.
23
+ MAX_FILE_TIME = 4e9 # seconds since 1970: the year 2096
24
+ MAX_FILE_RTT_MS = 1e7
25
+
26
+
27
+ def plausible_time(t: float) -> bool:
28
+ return math.isfinite(t) and 0 <= t < MAX_FILE_TIME
29
+
30
+
31
+ def plausible_rtt(rtt: Optional[float]) -> bool:
32
+ return rtt is None or (math.isfinite(rtt) and 0 <= rtt < MAX_FILE_RTT_MS)
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Sample:
37
+ t: float # epoch seconds when recorded
38
+ rtt: Optional[float] # round-trip ms, or None for a lost probe
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Event:
43
+ """A timestamped notable occurrence: a route change or an alert."""
44
+
45
+ seq: int # monotonic id, for "show me what's new" in the UI
46
+ t: float # epoch seconds
47
+ kind: str # "route" | "alert" | "clear" | "info"
48
+ text: str
49
+
50
+
51
+ class Hop:
52
+ """One position along the path (a TTL). Mutable; lives inside the monitor."""
53
+
54
+ def __init__(self, ttl: int, history: int = DEFAULT_HISTORY) -> None:
55
+ self.ttl = ttl
56
+ self.address: Optional[str] = None
57
+ self.hostname: Optional[str] = None # None=unresolved, ""=no PTR record
58
+ self.last_status: Optional[int] = None
59
+ self.resolving = False
60
+ self.samples: Deque[Sample] = deque(maxlen=history)
61
+ # Samples recorded since the current responder took this TTL. The
62
+ # samples deque deliberately spans responders (the MTR per-TTL model),
63
+ # but an alert judging the destination must not count a router that
64
+ # held this TTL before a reroute -- its rate-limited TTL-exceeded
65
+ # replies read as the destination's packet loss.
66
+ self.since_change = 0
67
+ # Each router's own best round trip. The window's best spans every
68
+ # router that held this TTL; a location check needs the router's own
69
+ # (locating.py), or one quick router vouches for a slow one.
70
+ self.best_by_addr: Dict[str, float] = {}
71
+
72
+ def record(self, rtt: Optional[float], address: Optional[str], status: int) -> None:
73
+ self.last_status = status
74
+ if address and address != self.address:
75
+ # Path changed under this TTL (load balancing / reroute): adopt the
76
+ # new responder and re-resolve its name.
77
+ self.address = address
78
+ self.hostname = None
79
+ self.since_change = 0
80
+ if address and rtt is not None:
81
+ known = self.best_by_addr.get(address)
82
+ if known is None or rtt < known:
83
+ if known is None and len(self.best_by_addr) >= MAX_ROUTERS_PER_HOP:
84
+ del self.best_by_addr[next(iter(self.best_by_addr))]
85
+ self.best_by_addr[address] = rtt
86
+ self.samples.append(Sample(time.time(), rtt))
87
+ self.since_change += 1
88
+
89
+ # --- derived statistics, all computed over the current window ----------
90
+ def _rtts(self) -> List[float]:
91
+ return [s.rtt for s in self.samples if s.rtt is not None]
92
+
93
+ def _recent(self, k: int) -> List[Sample]:
94
+ """The last ``k`` samples (all of them when ``k`` is 0 or oversized)."""
95
+ if not k or k >= len(self.samples):
96
+ return list(self.samples)
97
+ return list(self.samples)[-k:]
98
+
99
+ def recent_loss_pct(self, k: int = 0) -> float:
100
+ """Packet loss over the last ``k`` probes — the 'sustained' signal."""
101
+ recent = self._recent(k)
102
+ if not recent:
103
+ return 0.0
104
+ lost = sum(1 for s in recent if s.rtt is None)
105
+ return 100.0 * lost / len(recent)
106
+
107
+ def recent_received(self, k: int = 0) -> int:
108
+ return sum(1 for s in self._recent(k) if s.rtt is not None)
109
+
110
+ def recent_avg(self, k: int = 0) -> Optional[float]:
111
+ rtts = [s.rtt for s in self._recent(k) if s.rtt is not None]
112
+ return sum(rtts) / len(rtts) if rtts else None
113
+
114
+ def recent_stats(self, k: int = 0) -> "tuple[float, Optional[float], Optional[float]]":
115
+ """``(loss_pct, avg, jitter)`` over the last ``k`` samples, one pass.
116
+
117
+ The window equivalent of :meth:`compute`. Alert evaluation needs all
118
+ three — jitter because MOS is a function of latency, jitter and loss
119
+ together — and scanning the deque three times for them would be silly
120
+ when they come from the same accumulation.
121
+
122
+ ``islice`` rather than ``list(...)[-k:]``: the deque holds 600 samples
123
+ and the window is usually 20, so the slice copied 30x more than it
124
+ needed. islice also avoids the trap of indexing a deque near its far
125
+ end, which is O(n) per access.
126
+ """
127
+ samples = self.samples
128
+ n = len(samples)
129
+ if n == 0:
130
+ return (0.0, None, None)
131
+ start = 0 if (not k or k >= n) else n - k
132
+ window = samples if start == 0 else islice(samples, start, None)
133
+ count = n - start
134
+ received = 0
135
+ total = 0.0
136
+ prev: Optional[float] = None
137
+ jump_total = 0.0
138
+ for s in window:
139
+ r = s.rtt
140
+ if r is None:
141
+ continue
142
+ received += 1
143
+ total += r
144
+ if prev is not None:
145
+ jump_total += abs(r - prev)
146
+ prev = r
147
+ loss_pct = 100.0 * (count - received) / count
148
+ if not received:
149
+ return (loss_pct, None, None)
150
+ avg = total / received
151
+ if received < 2:
152
+ return (loss_pct, avg, None)
153
+ return (loss_pct, avg, jump_total / (received - 1))
154
+
155
+ @property
156
+ def sent(self) -> int:
157
+ return len(self.samples)
158
+
159
+ @property
160
+ def received(self) -> int:
161
+ return sum(1 for s in self.samples if s.rtt is not None)
162
+
163
+ @property
164
+ def lost(self) -> int:
165
+ return self.sent - self.received
166
+
167
+ @property
168
+ def loss_pct(self) -> float:
169
+ return (100.0 * self.lost / self.sent) if self.sent else 0.0
170
+
171
+ @property
172
+ def current(self) -> Optional[float]:
173
+ """Most recent sample's RTT (None means the last probe was lost)."""
174
+ return self.samples[-1].rtt if self.samples else None
175
+
176
+ @property
177
+ def avg(self) -> Optional[float]:
178
+ r = self._rtts()
179
+ return sum(r) / len(r) if r else None
180
+
181
+ @property
182
+ def best(self) -> Optional[float]:
183
+ r = self._rtts()
184
+ return min(r) if r else None
185
+
186
+ @property
187
+ def worst(self) -> Optional[float]:
188
+ r = self._rtts()
189
+ return max(r) if r else None
190
+
191
+ @property
192
+ def jitter(self) -> Optional[float]:
193
+ """Mean absolute change in RTT between consecutive replies (lost probes
194
+ skipped) -- packet-to-packet variation, RFC 3550's notion averaged
195
+ rather than smoothed, and the quantity the MOS E-model's jitter term
196
+ expects. Not the standard deviation, which it was until 1.3.3: that
197
+ scores a clean latency step after a reroute as sustained jitter, and
198
+ alternating 10/30 ms as only 10 ms when every packet moved 20."""
199
+ r = self._rtts()
200
+ if len(r) < 2:
201
+ return None
202
+ return sum(abs(b - a) for a, b in zip(r, r[1:])) / (len(r) - 1)
203
+
204
+ def compute(self):
205
+ """All window stats in a *single* pass — much cheaper than the
206
+ individual properties above, each of which re-scans the deque. Returns
207
+ ``(sent, received, loss_pct, current, avg, best, worst, jitter)``. This
208
+ is the per-tick hot path (see :meth:`HopView.of`)."""
209
+ samples = self.samples
210
+ n = len(samples)
211
+ if n == 0:
212
+ return (0, 0, 0.0, None, None, None, None, None)
213
+ received = 0
214
+ total = 0.0
215
+ prev: Optional[float] = None
216
+ jump_total = 0.0 # sum of |rtt - previous rtt|; see jitter
217
+ best: Optional[float] = None
218
+ worst: Optional[float] = None
219
+ for s in samples:
220
+ r = s.rtt
221
+ if r is None:
222
+ continue
223
+ received += 1
224
+ total += r
225
+ if prev is not None:
226
+ jump_total += abs(r - prev)
227
+ prev = r
228
+ if best is None or r < best:
229
+ best = r
230
+ if worst is None or r > worst:
231
+ worst = r
232
+ current = samples[-1].rtt
233
+ loss_pct = 100.0 * (n - received) / n
234
+ if received:
235
+ avg = total / received
236
+ jitter = jump_total / (received - 1) if received >= 2 else None
237
+ else:
238
+ avg = jitter = None
239
+ return (n, received, loss_pct, current, avg, best, worst, jitter)
240
+
241
+
242
+ def opt_str(value) -> Optional[str]:
243
+ """``value`` if it is a string, else None -- for fields read from a file
244
+ that is not necessarily ours, where a list or object would otherwise reach
245
+ code that formats or hashes it."""
246
+ return value if isinstance(value, str) else None
247
+
248
+
249
+ MAX_NAME = 253 # the longest a DNS name can be
250
+
251
+
252
+ def host_name(value) -> Optional[str]:
253
+ """A router's name as it may be shown, printed and saved: text only,
254
+ without control or formatting characters, at most MAX_NAME long. A PTR
255
+ record says whatever its owner likes, escape sequences and line breaks
256
+ included, and the headless reports print names straight to a console
257
+ (2026-11 review); a session file's names are someone else's too."""
258
+ if not isinstance(value, str):
259
+ return None
260
+ return "".join(ch for ch in value if ch.isprintable())[:MAX_NAME]
261
+
262
+
263
+ def hop_from_session(hd, max_history: Optional[int] = None) -> Optional[Hop]:
264
+ """Rebuild a :class:`Hop` from one entry of a saved session's ``hops``
265
+ list, or None if the entry is unusable.
266
+
267
+ Shared by Load session and baseline comparison, so a malformed entry is
268
+ handled identically by both: skipped, never raised. ``max_history`` caps
269
+ the ring buffer (most recent samples kept) against a crafted file.
270
+ """
271
+ if not isinstance(hd, dict):
272
+ return None
273
+ try:
274
+ samples = hd.get("samples") or []
275
+ if not isinstance(samples, list):
276
+ return None
277
+ history = max(DEFAULT_HISTORY, len(samples))
278
+ if max_history:
279
+ history = min(history, max_history)
280
+ hop = Hop(int(hd["ttl"]), history=history)
281
+ hop.address = opt_str(hd.get("address"))
282
+ hop.hostname = host_name(hd.get("hostname"))
283
+ status = hd.get("last_status")
284
+ hop.last_status = status if isinstance(status, int) else None
285
+ for pair in samples[-history:]:
286
+ t, rtt = float(pair[0]), (None if pair[1] is None else float(pair[1]))
287
+ if plausible_time(t) and plausible_rtt(rtt):
288
+ hop.samples.append(Sample(t, rtt))
289
+ # A session records no per-sample responder, so all of it is
290
+ # attributed to the address the file names.
291
+ hop.since_change = len(hop.samples)
292
+ rtts = [s.rtt for s in hop.samples if s.rtt is not None]
293
+ if hop.address and rtts:
294
+ hop.best_by_addr[hop.address] = min(rtts)
295
+ return hop
296
+ except (KeyError, ValueError, TypeError, IndexError, OverflowError):
297
+ return None
298
+
299
+
300
+ @dataclass(frozen=True)
301
+ class HopView:
302
+ """Immutable snapshot of a :class:`Hop` for the UI thread."""
303
+
304
+ ttl: int
305
+ address: Optional[str]
306
+ hostname: Optional[str]
307
+ last_status: Optional[int]
308
+ sent: int
309
+ received: int
310
+ loss_pct: float
311
+ current: Optional[float]
312
+ avg: Optional[float]
313
+ best: Optional[float]
314
+ worst: Optional[float]
315
+ jitter: Optional[float]
316
+ best_here: Optional[float] = None # the current router's own best (best spans them all)
317
+
318
+ @classmethod
319
+ def of(cls, hop: Hop) -> "HopView":
320
+ sent, received, loss_pct, current, avg, best, worst, jitter = hop.compute()
321
+ return cls(
322
+ ttl=hop.ttl,
323
+ address=hop.address,
324
+ hostname=hop.hostname,
325
+ last_status=hop.last_status,
326
+ sent=sent,
327
+ received=received,
328
+ loss_pct=loss_pct,
329
+ current=current,
330
+ avg=avg,
331
+ best=best,
332
+ worst=worst,
333
+ jitter=jitter,
334
+ best_here=hop.best_by_addr.get(hop.address) if hop.address else None,
335
+ )
336
+
337
+
338
+ def mos(avg_ms: Optional[float], jitter_ms: Optional[float], loss_pct: float) -> Optional[float]:
339
+ """Estimated Mean Opinion Score (1.0–5.0) for a VoIP-style call over this
340
+ path, from the simplified ITU-T G.107 E-model used by most ping/traceroute
341
+ tools. Needs a latency measurement; returns None without one.
342
+
343
+ ~4.4 is a clean LAN/broadband path; <3.1 is poor. It is only meaningful for
344
+ the *end-to-end* path (the destination hop), not an intermediate router."""
345
+ if avg_ms is None:
346
+ return None
347
+ effective_latency = avg_ms + (jitter_ms or 0.0) * 2.0 + 10.0
348
+ if effective_latency < 160.0:
349
+ r = 93.2 - effective_latency / 40.0
350
+ else:
351
+ r = 93.2 - (effective_latency - 120.0) / 10.0
352
+ r -= loss_pct * 2.5 # each 1% loss costs ~2.5 R-factor points
353
+ if r < 0.0:
354
+ return 1.0
355
+ r = min(r, 100.0)
356
+ score = 1.0 + 0.035 * r + r * (r - 60.0) * (100.0 - r) * 7e-6
357
+ return max(1.0, min(5.0, score))
358
+
359
+
360
+ def mos_label(score: Optional[float]) -> str:
361
+ if score is None:
362
+ return "—"
363
+ if score >= 4.3:
364
+ return "Excellent"
365
+ if score >= 4.0:
366
+ return "Good"
367
+ if score >= 3.6:
368
+ return "Fair"
369
+ if score >= 3.1:
370
+ return "Poor"
371
+ return "Bad"
372
+
373
+
374
+ def draw_version(active_name, monitor, selected_ttl, theme, geo_count: int):
375
+ """Everything a canvas redraw depends on, as one comparable tuple.
376
+
377
+ The GUI's refresh timer ticks faster than probes arrive, so a canvas is
378
+ only redrawn when this changes. ``geo_count`` belongs in it because geo
379
+ lookups land asynchronously, roughly a second apart, and touch none of the
380
+ other four — so without it the Map tab drew its coastlines, fired off the
381
+ lookups and then never plotted the answers. A live monitor hid that behind
382
+ the next round's redraw; a *loaded session* has no next round, so its map
383
+ stayed empty until the window happened to be resized.
384
+
385
+ Here rather than in gui.py so it is testable on any platform, like the
386
+ other pure presentation helpers below.
387
+ """
388
+ return (active_name,
389
+ getattr(monitor, "_round", -1) if monitor is not None else -1,
390
+ selected_ttl, theme, geo_count)
391
+
392
+
393
+ # --- CSV hardening ---------------------------------------------------------
394
+ _CSV_TRIGGERS = ("=", "+", "-", "@")
395
+
396
+
397
+ def csv_safe(value: str) -> str:
398
+ """Neutralise spreadsheet formula injection (CWE-1236) in a CSV cell.
399
+
400
+ Reverse-DNS hostnames are attacker-influenced — a hop's PTR record can be
401
+ anything its operator chooses — and a saved session's address/hostname come
402
+ from a file that may not be ours. A value like ``=cmd|'/c calc'!A1`` (or one
403
+ starting ``+ - @``) is run as a formula when the export is opened in
404
+ Excel/Sheets. Prefix any such cell with a single quote, the conventional
405
+ defang; plain values (IPv4 addresses, normal hostnames) pass through
406
+ untouched. ``csv.writer`` quoting handles delimiters but not this. Leading
407
+ whitespace is defanged too (some importers strip it before evaluating)."""
408
+ if value and (value[0] in _CSV_TRIGGERS or value[0].isspace()):
409
+ return "'" + value
410
+ return value