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/tcpudp.py ADDED
@@ -0,0 +1,479 @@
1
+ """TCP/UDP traceroute probes (tcptraceroute-style), for paths that block or
2
+ deprioritise ICMP, or to test reachability of a specific service port.
3
+
4
+ Technique
5
+ ---------
6
+ Send a normal TCP SYN (or UDP datagram) to the destination with a chosen IP TTL
7
+ through an ordinary socket — Windows lets us set ``IP_TTL`` on a normal socket
8
+ without elevation, sidestepping the rule that raw sockets may not *send* TCP.
9
+
10
+ To see the routers along the way we must capture the ICMP "TTL exceeded" errors
11
+ they send back. On Windows those errors are consumed by the network stack and
12
+ are *not* delivered to a plain raw ICMP socket, so we open a raw capture socket
13
+ with ``SIO_RCVALL`` (receive-all) and correlate each ICMP error to our probe by
14
+ the source/destination ports echoed inside it. ``SIO_RCVALL`` requires
15
+ Administrator rights.
16
+
17
+ Reaching the destination is detected:
18
+ * TCP -> at the TCP layer: connect completes (SYN-ACK, port open) or is
19
+ refused (RST, port closed). Either proves we reached the host — and
20
+ this needs no capture socket, so TCP "final hop only" works without
21
+ elevation.
22
+ * UDP -> via ICMP "port unreachable" from the destination (needs capture).
23
+ An *open* UDP port stays silent and reads as a timeout — a known
24
+ UDP-traceroute limitation; prefer TCP for a definitive "service up".
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import ctypes
29
+ import errno
30
+ import select
31
+ import socket
32
+ import sys
33
+ import time
34
+ from typing import Optional
35
+
36
+ from .icmp import (
37
+ ERROR_INVALID_NETNAME,
38
+ IP_REQ_TIMED_OUT,
39
+ IP_SUCCESS,
40
+ IP_TTL_EXPIRED_TRANSIT,
41
+ PingResult,
42
+ )
43
+
44
+ # What a probe reports when an explicitly chosen source address cannot be
45
+ # bound -- the same status the Windows ICMP backend returns for it.
46
+ _NO_SOURCE = PingResult(ERROR_INVALID_NETNAME, None, None, False)
47
+
48
+ ICMP_TYPE_DEST_UNREACH = 3
49
+ ICMP_TYPE_TTL_EXCEEDED = 11
50
+ IPPROTO_ICMP = 1
51
+ _PROTO = {"tcp": socket.IPPROTO_TCP, "udp": socket.IPPROTO_UDP}
52
+ # SO_ERROR values that still prove the destination host answered at the TCP layer
53
+ _CLEAN_REACH_ERRORS = {0, errno.ECONNREFUSED, 10061} # 10061 = WSAECONNREFUSED
54
+
55
+ DEFAULT_PORTS = {"tcp": 443, "udp": 33434}
56
+
57
+
58
+ def _set_tos(sock: socket.socket, tos: int) -> None:
59
+ """Mark the probe with an IP ToS byte, best effort.
60
+
61
+ Caveat worth knowing before trusting a TCP/UDP QoS test: Windows ignores
62
+ IP_TOS on an ordinary socket unless the DisableUserTOSSetting registry
63
+ value is cleared, and it does so *silently* -- setsockopt succeeds either
64
+ way. ICMP mode does not have this problem, because it marks through
65
+ IP_OPTION_INFORMATION.Tos in the IP Helper API rather than through a
66
+ socket. So: prefer ICMP mode for DSCP work on Windows, and confirm with a
67
+ capture before drawing conclusions from a TCP/UDP run.
68
+ """
69
+ if not tos:
70
+ return
71
+ try:
72
+ sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, int(tos) & 0xFF)
73
+ except OSError:
74
+ pass
75
+
76
+
77
+ def _tcp_reach(err: int, rtt: float, dest_ip: str) -> PingResult:
78
+ """Classify a TCP probe socket's SO_ERROR. A clean result (connected, or
79
+ refused = port closed) proves the destination answered; anything else is no
80
+ usable reply. Always returns a definite result, so a probed TTL is never
81
+ silently dropped from a round (the bug this replaces)."""
82
+ if err in _CLEAN_REACH_ERRORS:
83
+ return PingResult(IP_SUCCESS, rtt, dest_ip, True)
84
+ return PingResult(IP_REQ_TIMED_OUT, None, None, False)
85
+
86
+
87
+ def is_admin() -> bool:
88
+ """Best-effort check for the elevation raw capture needs on Windows."""
89
+ if sys.platform != "win32":
90
+ return True
91
+ try:
92
+ return bool(ctypes.windll.shell32.IsUserAnAdmin())
93
+ except Exception:
94
+ return False
95
+
96
+
97
+ def local_ip_for(dest_ip: str) -> str:
98
+ """The source IP the OS would use to reach ``dest_ip`` (for binding the
99
+ capture socket to the right interface)."""
100
+ try:
101
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
102
+ try:
103
+ s.connect((dest_ip, 9))
104
+ return s.getsockname()[0]
105
+ finally:
106
+ s.close()
107
+ except OSError:
108
+ return "0.0.0.0"
109
+
110
+
111
+ def source_problem(source_ip: str) -> Optional[str]:
112
+ """Why ``source_ip`` cannot be used as a probe source, or None if it can.
113
+
114
+ Binding a throwaway UDP socket asks the stack the real question -- "is
115
+ this an address I hold?" -- without sending anything, and fails the same
116
+ way for a malformed string.
117
+ """
118
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
119
+ try:
120
+ s.bind((source_ip, 0))
121
+ except (OSError, OverflowError, TypeError) as exc:
122
+ return str(exc)
123
+ finally:
124
+ s.close()
125
+ return None
126
+
127
+
128
+ def _bind_source(sock: socket.socket, local_ip: str, strict: bool) -> bool:
129
+ """Bind ``sock`` to ``local_ip``. False only when that fails for an address
130
+ the user chose (``strict``): falling back to the default route would then
131
+ measure a different path than the one asked about. An auto-detected
132
+ address that has gone away is allowed to fall back, as it always has."""
133
+ try:
134
+ sock.bind((local_ip, 0))
135
+ except OSError:
136
+ return not strict
137
+ return True
138
+
139
+
140
+ def _open_capture(local_ip: str) -> socket.socket:
141
+ """Raw socket in receive-all mode so we see ICMP errors the stack would
142
+ otherwise swallow. Raises OSError without Administrator rights, and
143
+ likewise on any platform that has no SIO_RCVALL."""
144
+ if not hasattr(socket, "SIO_RCVALL"):
145
+ # SIO_RCVALL is a Windows ioctl. Every caller guards this with
146
+ # `except OSError`, which does not catch the AttributeError that
147
+ # referencing it elsewhere raises -- so it would sail past
148
+ # capture_supported() and reach _run's broad handler as an obscure
149
+ # "Monitor error: AttributeError(...)" instead of the clear "needs
150
+ # Administrator" message. Unreachable on Linux, where the raw socket
151
+ # itself fails with EPROTONOSUPPORT first, but not verified on macOS,
152
+ # which has had an ICMP backend since 1.3.0.
153
+ raise OSError("raw ICMP capture (SIO_RCVALL) is available only on Windows")
154
+ s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
155
+ s.bind((local_ip, 0))
156
+ s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) # type: ignore[attr-defined]
157
+ s.setblocking(False)
158
+ return s
159
+
160
+
161
+ def _close_capture(s: socket.socket) -> None:
162
+ try:
163
+ s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) # type: ignore[attr-defined]
164
+ except (OSError, AttributeError): # AttributeError: not Windows
165
+ pass
166
+ try:
167
+ s.close()
168
+ except OSError:
169
+ pass
170
+
171
+
172
+ def capture_supported(local_ip: str) -> bool:
173
+ """Whether full TCP/UDP traceroute (raw ICMP capture) is available here."""
174
+ try:
175
+ s = _open_capture(local_ip)
176
+ except OSError:
177
+ return False
178
+ _close_capture(s)
179
+ return True
180
+
181
+
182
+ def probe(
183
+ dest_ip: str,
184
+ ip_ttl: int,
185
+ timeout_ms: int,
186
+ mode: str,
187
+ port: int,
188
+ local_ip: str,
189
+ payload: bytes = b"",
190
+ tos: int = 0,
191
+ strict_source: bool = False,
192
+ ) -> PingResult:
193
+ """One TCP or UDP probe at the given IP TTL. ``mode`` is "tcp" or "udp".
194
+
195
+ Without a capture socket (not elevated) TCP still detects reaching the
196
+ destination, so TCP final-hop-only works; intermediate hops and UDP need it.
197
+
198
+ ``strict_source`` means ``local_ip`` was chosen by the user: if it cannot
199
+ be bound the probe reports ERROR_INVALID_NETNAME instead of quietly going
200
+ out of whichever interface the route table picks.
201
+ """
202
+ timeout = max(0.05, timeout_ms / 1000.0)
203
+ try:
204
+ cap: Optional[socket.socket] = _open_capture(local_ip)
205
+ except OSError:
206
+ cap = None
207
+
208
+ probe_sock = None
209
+ try:
210
+ fam = socket.SOCK_STREAM if mode == "tcp" else socket.SOCK_DGRAM
211
+ probe_sock = socket.socket(socket.AF_INET, fam)
212
+ probe_sock.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, int(ip_ttl))
213
+ _set_tos(probe_sock, tos)
214
+ probe_sock.setblocking(False)
215
+ if not _bind_source(probe_sock, local_ip, strict_source):
216
+ return _NO_SOURCE
217
+
218
+ start = time.perf_counter()
219
+ if mode == "tcp":
220
+ try:
221
+ probe_sock.connect_ex((dest_ip, port))
222
+ except OSError:
223
+ pass
224
+ else:
225
+ try:
226
+ probe_sock.sendto(payload or b"\x00", (dest_ip, port))
227
+ except OSError:
228
+ pass
229
+ src_port = probe_sock.getsockname()[1]
230
+
231
+ deadline = start + timeout
232
+ result = PingResult(IP_REQ_TIMED_OUT, None, None, False)
233
+ while True:
234
+ remaining = deadline - time.perf_counter()
235
+ if remaining <= 0:
236
+ break
237
+ rlist = [cap] if cap is not None else []
238
+ wlist = [probe_sock] if mode == "tcp" else []
239
+ if not rlist and not wlist:
240
+ time.sleep(min(0.05, remaining))
241
+ continue
242
+ try:
243
+ r, w, x = select.select(rlist, wlist, wlist, min(0.2, remaining))
244
+ except OSError:
245
+ break
246
+ # Drain the capture socket BEFORE consulting the probe socket's
247
+ # error. When an ICMP error aborts the connect, both become ready
248
+ # in the same wakeup — and only the captured packet carries the
249
+ # responder's address. Taking the socket error first threw that
250
+ # away and recorded a bare timeout, losing exactly the answer the
251
+ # probe exists to get: *which* box is refusing to forward.
252
+ if r:
253
+ try:
254
+ data, _addr = cap.recvfrom(2048) # type: ignore[union-attr]
255
+ except OSError:
256
+ data = None
257
+ kind = _match(data, src_port, port, dest_ip, mode) if data else None
258
+ if kind is not None:
259
+ responder = socket.inet_ntoa(data[12:16]) # source of the ICMP error
260
+ rtt = (time.perf_counter() - start) * 1000.0
261
+ if kind == "dest" and responder == dest_ip:
262
+ result = PingResult(IP_SUCCESS, rtt, responder, True) # reached the target
263
+ else:
264
+ # TTL-exceeded router, or an unreachable from a mid-path
265
+ # firewall (not the target) — a responding hop, not the end.
266
+ result = PingResult(IP_TTL_EXPIRED_TRANSIT, rtt, responder, False)
267
+ break
268
+ if mode == "tcp" and (w or x):
269
+ err = probe_sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
270
+ result = _tcp_reach(err, (time.perf_counter() - start) * 1000.0, dest_ip)
271
+ break
272
+ return result
273
+ finally:
274
+ if probe_sock is not None:
275
+ probe_sock.close()
276
+ if cap is not None:
277
+ _close_capture(cap)
278
+
279
+
280
+ def probe_path(
281
+ dest_ip: str,
282
+ ttls,
283
+ timeout_ms: int,
284
+ mode: str,
285
+ port: int,
286
+ local_ip: str,
287
+ payload: bytes = b"",
288
+ tos: int = 0,
289
+ strict_source: bool = False,
290
+ ) -> dict:
291
+ """Probe all ``ttls`` in one round in parallel, sharing a single capture
292
+ socket — so a round costs ~one timeout instead of the sum (much faster on
293
+ paths with silent hops). Returns ``{ttl: PingResult}``. Falls back to serial
294
+ single probes if the capture socket can't be opened (e.g. not elevated).
295
+ ``strict_source`` as for :func:`probe`."""
296
+ ttls = list(ttls)
297
+ try:
298
+ cap = _open_capture(local_ip)
299
+ except OSError:
300
+ return {ttl: probe(dest_ip, ttl, timeout_ms, mode, port, local_ip, payload, tos,
301
+ strict_source)
302
+ for ttl in ttls}
303
+
304
+ timeout = max(0.05, timeout_ms / 1000.0)
305
+ senders: dict = {} # ttl -> [sock_or_None, start_time]
306
+ key_ttl: dict = {} # each hop's own socket's source port -> ttl
307
+ results: dict = {}
308
+
309
+ def settle(ttl: int, result: PingResult) -> None:
310
+ # Close the hop's socket the moment its answer is in. Windows keeps
311
+ # resending the SYN of a connecting socket (+1 s, +3 s) whatever the
312
+ # router said, and one silent hop holds the round open to the TCP
313
+ # timeout floor: with every socket left to the end, most hops went
314
+ # out two or three times and the routers answered each copy.
315
+ results[ttl] = result
316
+ pending.discard(ttl)
317
+ sock = senders[ttl][0]
318
+ if sock is not None:
319
+ senders[ttl][0] = None
320
+ try:
321
+ sock.close()
322
+ except OSError:
323
+ pass
324
+
325
+ try:
326
+ for ttl in ttls:
327
+ if mode == "tcp":
328
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
329
+ s.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, int(ttl))
330
+ _set_tos(s, tos)
331
+ s.setblocking(False)
332
+ if not _bind_source(s, local_ip, strict_source):
333
+ s.close()
334
+ results[ttl] = _NO_SOURCE
335
+ continue
336
+ key = s.getsockname()[1]
337
+ start = time.perf_counter()
338
+ try:
339
+ s.connect_ex((dest_ip, port))
340
+ except OSError:
341
+ pass
342
+ senders[ttl] = [s, start]
343
+ else:
344
+ # udp: like TCP, every hop goes to the port that was set, from
345
+ # its own socket, and the reply is matched on that socket's
346
+ # source port. Hop N used to go to port+N-1 (classic
347
+ # traceroute's walk): the first trace (probe()) used the port
348
+ # set and every round after it a different one, so a firewall
349
+ # passing only that port let the trace through and dropped the
350
+ # rounds, and a forged reply needed only a predictable
351
+ # destination port (2026-11 review).
352
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
353
+ s.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, int(ttl))
354
+ _set_tos(s, tos)
355
+ # Bound like the TCP sockets: an unbound datagram leaves from
356
+ # whatever interface the route table picks, which is not the
357
+ # path a pinned source asked about.
358
+ if not _bind_source(s, local_ip, strict_source):
359
+ s.close()
360
+ results[ttl] = _NO_SOURCE
361
+ continue
362
+ start = time.perf_counter()
363
+ try:
364
+ s.sendto(payload or b"\x00", (dest_ip, port))
365
+ key = s.getsockname()[1]
366
+ except OSError:
367
+ key = 0 # it never left: the hop times out
368
+ # Kept open until its answer is in (settle) or the round ends:
369
+ # closed, its source port could be handed to the next hop's
370
+ # socket, and two hops would share a key.
371
+ senders[ttl] = [s, start]
372
+ if not key:
373
+ continue
374
+ key_ttl[key] = ttl
375
+
376
+ pending = set(ttls) - set(results) # minus any refused at bind
377
+ deadline = time.perf_counter() + timeout
378
+ while pending and time.perf_counter() < deadline:
379
+ # A UDP socket is always writable: in the list it would wake
380
+ # select() at once, every time, for the whole round.
381
+ wlist = [senders[t][0] for t in pending
382
+ if senders[t][0] is not None] if mode == "tcp" else []
383
+ remaining = min(0.2, max(0.0, deadline - time.perf_counter()))
384
+ try:
385
+ r, w, x = select.select([cap], wlist, wlist, remaining)
386
+ except OSError:
387
+ break
388
+ now = time.perf_counter()
389
+ # Drain the capture socket first. An ICMP error that aborts a
390
+ # connect makes both ready in the same wakeup, and only the
391
+ # captured packet names the responder — reading the socket error
392
+ # first would resolve that TTL as a bare timeout and the `not in
393
+ # pending` guard below would then discard the router's identity.
394
+ if cap in r:
395
+ # Bounded by the round's deadline too: the capture socket sees
396
+ # every IP packet on the interface, and on a busy one it may
397
+ # never run dry (2026-11 review).
398
+ while time.perf_counter() < deadline:
399
+ try:
400
+ data, _ = cap.recvfrom(2048)
401
+ except (BlockingIOError, OSError):
402
+ break
403
+ parsed = _parse(data)
404
+ if parsed is None:
405
+ continue
406
+ kind, proto, sp, dp, odst = parsed
407
+ # Require the error to echo OUR target — a receive-all socket
408
+ # sees every host's ICMP, and other monitors may share a port.
409
+ if proto != _PROTO[mode] or odst != dest_ip:
410
+ continue
411
+ ttl = key_ttl.get(sp) if dp == port else None
412
+ if ttl is None or ttl not in pending:
413
+ continue
414
+ responder = socket.inet_ntoa(data[12:16])
415
+ rtt = (now - senders[ttl][1]) * 1000.0
416
+ if kind == "dest" and responder == dest_ip:
417
+ settle(ttl, PingResult(IP_SUCCESS, rtt, responder, True))
418
+ else:
419
+ settle(ttl, PingResult(IP_TTL_EXPIRED_TRANSIT, rtt, responder, False))
420
+ if mode == "tcp" and (w or x):
421
+ for ttl in list(pending):
422
+ s = senders[ttl][0]
423
+ if s in w or s in x:
424
+ err = s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
425
+ settle(ttl, _tcp_reach(err, (now - senders[ttl][1]) * 1000.0, dest_ip))
426
+ for ttl in pending:
427
+ results[ttl] = PingResult(IP_REQ_TIMED_OUT, None, None, False)
428
+ return results
429
+ finally:
430
+ for ttl in ttls:
431
+ sock = senders.get(ttl, [None])[0]
432
+ if sock is not None:
433
+ try:
434
+ sock.close()
435
+ except OSError:
436
+ pass
437
+ _close_capture(cap)
438
+
439
+
440
+ def _parse(packet: bytes):
441
+ """Parse an ICMP error datagram from the capture socket. Returns
442
+ ``(kind, orig_proto, orig_src_port, orig_dst_port, orig_dst_ip)`` or None,
443
+ where kind is "ttl" (TTL exceeded) or "dest" (destination unreachable). The
444
+ echoed original *destination IP* lets a caller confirm the error pertains to
445
+ its own probe — essential when a receive-all socket sees every host's ICMP
446
+ (and several monitors run at once)."""
447
+ if len(packet) < 28:
448
+ return None
449
+ if packet[9] != IPPROTO_ICMP: # outer IP protocol must be ICMP
450
+ return None
451
+ ihl = (packet[0] & 0x0F) * 4
452
+ icmp = packet[ihl:]
453
+ if len(icmp) < 8:
454
+ return None
455
+ itype = icmp[0]
456
+ if itype not in (ICMP_TYPE_TTL_EXCEEDED, ICMP_TYPE_DEST_UNREACH):
457
+ return None
458
+ orig = icmp[8:] # the original IP packet that triggered the error
459
+ if len(orig) < 20:
460
+ return None
461
+ orig_ihl = (orig[0] & 0x0F) * 4
462
+ trans = orig[orig_ihl:]
463
+ if len(trans) < 4:
464
+ return None
465
+ kind = "ttl" if itype == ICMP_TYPE_TTL_EXCEEDED else "dest"
466
+ return (kind, orig[9], int.from_bytes(trans[0:2], "big"),
467
+ int.from_bytes(trans[2:4], "big"), socket.inet_ntoa(orig[16:20]))
468
+
469
+
470
+ def _match(packet: bytes, src_port: int, dst_port: int, dest_ip: str, mode: str) -> Optional[str]:
471
+ """If ``packet`` is the ICMP error for *our* single probe (matching ports,
472
+ protocol, and the original destination IP), return "ttl"/"dest"; else None."""
473
+ parsed = _parse(packet)
474
+ if parsed is None:
475
+ return None
476
+ kind, proto, sp, dp, odst = parsed
477
+ if proto != _PROTO[mode] or sp != src_port or dp != dst_port or odst != dest_ip:
478
+ return None
479
+ return kind