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/icmp.py ADDED
@@ -0,0 +1,305 @@
1
+ """ICMP echo via the Windows IP Helper API (iphlpapi.dll).
2
+
3
+ Uses ``IcmpCreateFile`` / ``IcmpSendEcho`` so no administrator privileges,
4
+ raw sockets, or Npcap are needed. The TTL field of ``IP_OPTION_INFORMATION``
5
+ lets us probe individual hops: a router that drops the packet for TTL expiry
6
+ answers with an ICMP "TTL exceeded in transit" message, and IcmpSendEcho
7
+ surfaces that as status ``IP_TTL_EXPIRED_TRANSIT`` with the router's address.
8
+ That is exactly the primitive a traceroute needs.
9
+
10
+ IPv4 only. The address round-trips below assume a little-endian host (x86/x64),
11
+ which is every Windows machine this targets.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import ctypes
16
+ import socket
17
+ import struct
18
+ import sys
19
+ from ctypes import wintypes
20
+ from dataclasses import dataclass
21
+ from typing import Optional
22
+
23
+ # --- ICMP status codes (subset of the IP_STATUS_BASE range) ----------------
24
+ IP_SUCCESS = 0
25
+ IP_BUF_TOO_SMALL = 11001
26
+ IP_DEST_NET_UNREACHABLE = 11002
27
+ IP_DEST_HOST_UNREACHABLE = 11003
28
+ IP_DEST_PROT_UNREACHABLE = 11004
29
+ IP_DEST_PORT_UNREACHABLE = 11005
30
+ IP_NO_RESOURCES = 11006
31
+ IP_BAD_OPTION = 11007
32
+ IP_HW_ERROR = 11008
33
+ IP_PACKET_TOO_BIG = 11009
34
+ IP_REQ_TIMED_OUT = 11010
35
+ IP_BAD_ROUTE = 11012
36
+ IP_TTL_EXPIRED_TRANSIT = 11013
37
+ IP_TTL_EXPIRED_REASSEM = 11014
38
+ # Not an IP_STATUS: a Win32 error IcmpSendEcho2Ex returns when SourceAddress is
39
+ # not an address this machine holds. Worth naming, because "status 1214" tells
40
+ # an operator nothing and the cause is a one-line fix.
41
+ ERROR_INVALID_NETNAME = 1214
42
+
43
+ _STATUS_TEXT = {
44
+ IP_SUCCESS: "ok",
45
+ IP_DEST_NET_UNREACHABLE: "net unreachable",
46
+ IP_DEST_HOST_UNREACHABLE: "host unreachable",
47
+ IP_DEST_PROT_UNREACHABLE: "protocol unreachable",
48
+ IP_DEST_PORT_UNREACHABLE: "port unreachable",
49
+ IP_NO_RESOURCES: "no resources",
50
+ IP_BAD_OPTION: "bad option",
51
+ IP_HW_ERROR: "hardware error",
52
+ IP_PACKET_TOO_BIG: "packet too big",
53
+ IP_REQ_TIMED_OUT: "timed out",
54
+ IP_BAD_ROUTE: "bad route",
55
+ IP_TTL_EXPIRED_TRANSIT: "ttl expired (hop)",
56
+ IP_TTL_EXPIRED_REASSEM: "ttl expired (reassembly)",
57
+ ERROR_INVALID_NETNAME: "source address is not on this machine",
58
+ }
59
+
60
+
61
+ def status_text(status: int) -> str:
62
+ return _STATUS_TEXT.get(status, f"status {status}")
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class PingResult:
67
+ """Outcome of a single ICMP echo probe."""
68
+
69
+ status: int
70
+ rtt_ms: Optional[float] # round-trip time; None on timeout / error
71
+ address: Optional[str] # IPv4 of whoever answered (router or destination)
72
+ reached: bool # True only when the final destination replied
73
+
74
+ @property
75
+ def responded(self) -> bool:
76
+ """True if *anything* answered (a hop or the destination)."""
77
+ return self.address is not None and self.status in (
78
+ IP_SUCCESS,
79
+ IP_TTL_EXPIRED_TRANSIT,
80
+ )
81
+
82
+
83
+ # --- Win32 structures ------------------------------------------------------
84
+ class IP_OPTION_INFORMATION(ctypes.Structure):
85
+ _fields_ = [
86
+ ("Ttl", ctypes.c_ubyte),
87
+ ("Tos", ctypes.c_ubyte),
88
+ ("Flags", ctypes.c_ubyte),
89
+ ("OptionsSize", ctypes.c_ubyte),
90
+ ("OptionsData", ctypes.c_void_p), # PUCHAR
91
+ ]
92
+
93
+
94
+ class ICMP_ECHO_REPLY(ctypes.Structure):
95
+ _fields_ = [
96
+ ("Address", ctypes.c_uint32), # IPAddr, network byte order
97
+ ("Status", ctypes.c_ulong),
98
+ ("RoundTripTime", ctypes.c_ulong), # milliseconds
99
+ ("DataSize", ctypes.c_ushort),
100
+ ("Reserved", ctypes.c_ushort),
101
+ ("Data", ctypes.c_void_p),
102
+ ("Options", IP_OPTION_INFORMATION),
103
+ ]
104
+
105
+
106
+ _AVAILABLE = sys.platform == "win32"
107
+ _INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
108
+
109
+ if _AVAILABLE:
110
+ _iphlpapi = ctypes.WinDLL("iphlpapi.dll", use_last_error=True)
111
+
112
+ _IcmpCreateFile = _iphlpapi.IcmpCreateFile
113
+ _IcmpCreateFile.restype = wintypes.HANDLE
114
+ _IcmpCreateFile.argtypes = []
115
+
116
+ _IcmpCloseHandle = _iphlpapi.IcmpCloseHandle
117
+ _IcmpCloseHandle.restype = wintypes.BOOL
118
+ _IcmpCloseHandle.argtypes = [wintypes.HANDLE]
119
+
120
+ _IcmpSendEcho = _iphlpapi.IcmpSendEcho
121
+ _IcmpSendEcho.restype = wintypes.DWORD
122
+ _IcmpSendEcho.argtypes = [
123
+ wintypes.HANDLE, # IcmpHandle
124
+ ctypes.c_uint32, # DestinationAddress (IPAddr)
125
+ ctypes.c_char_p, # RequestData
126
+ wintypes.WORD, # RequestSize
127
+ ctypes.POINTER(IP_OPTION_INFORMATION), # RequestOptions
128
+ ctypes.c_void_p, # ReplyBuffer
129
+ wintypes.DWORD, # ReplySize
130
+ wintypes.DWORD, # Timeout (ms)
131
+ ]
132
+
133
+ # IcmpSendEcho has no source-address parameter, so on a multi-homed box the
134
+ # stack picks the interface by route and you cannot ask "what does the path
135
+ # look like *from the BAS VLAN*". IcmpSendEcho2Ex (Vista+) takes one.
136
+ # Passing NULL for both Event and ApcRoutine makes it synchronous, exactly
137
+ # like IcmpSendEcho.
138
+ _IcmpSendEcho2Ex = _iphlpapi.IcmpSendEcho2Ex
139
+ _IcmpSendEcho2Ex.restype = wintypes.DWORD
140
+ _IcmpSendEcho2Ex.argtypes = [
141
+ wintypes.HANDLE, # IcmpHandle
142
+ wintypes.HANDLE, # Event (NULL = synchronous)
143
+ ctypes.c_void_p, # ApcRoutine (NULL)
144
+ ctypes.c_void_p, # ApcContext (NULL)
145
+ ctypes.c_uint32, # SourceAddress (IPAddr)
146
+ ctypes.c_uint32, # DestinationAddress (IPAddr)
147
+ ctypes.c_char_p, # RequestData
148
+ wintypes.WORD, # RequestSize
149
+ ctypes.POINTER(IP_OPTION_INFORMATION), # RequestOptions
150
+ ctypes.c_void_p, # ReplyBuffer
151
+ wintypes.DWORD, # ReplySize
152
+ wintypes.DWORD, # Timeout (ms)
153
+ ]
154
+
155
+
156
+ DEFAULT_PAYLOAD = b"PingerPlot-probe.." # 18 bytes (fallback; the monitor builds its own)
157
+
158
+ # DSCP code points worth having a name for. The wire field is the 8-bit ToS
159
+ # byte, of which DSCP is the top 6 bits — hence the shift in dscp_to_tos.
160
+ DSCP_PRESETS = {
161
+ "CS0 / default": 0,
162
+ "AF31 (signalling)": 26,
163
+ "AF41 (video)": 34,
164
+ "EF (voice)": 46,
165
+ "CS6 (network control)": 48,
166
+ }
167
+
168
+
169
+ def dscp_to_tos(dscp: int) -> int:
170
+ """DSCP code point (0-63) -> the ToS byte that carries it (DSCP << 2).
171
+
172
+ Network people speak DSCP; the IP header field is ToS. Doing the shift in
173
+ one place stops a 46 meant as EF from going on the wire as DSCP 11.
174
+ """
175
+ return (max(0, min(int(dscp), 63)) << 2) & 0xFC
176
+
177
+
178
+ def _ip_to_uint32(ip: str) -> int:
179
+ """Dotted IPv4 -> 32-bit int laid out as the API's network-order IPAddr."""
180
+ return struct.unpack("<I", socket.inet_aton(ip))[0]
181
+
182
+
183
+ def _uint32_to_ip(addr: int) -> str:
184
+ """Inverse of :func:`_ip_to_uint32`."""
185
+ return socket.inet_ntoa(struct.pack("<I", addr & 0xFFFFFFFF))
186
+
187
+
188
+ def _posix():
189
+ """The POSIX backend, imported lazily.
190
+
191
+ Deferred rather than imported at module scope because icmp_posix imports
192
+ names from this module; doing it at the top would be a cycle.
193
+ """
194
+ from . import icmp_posix
195
+ return icmp_posix
196
+
197
+
198
+ def is_available() -> bool:
199
+ """True when an ICMP backend can be used on this machine.
200
+
201
+ On Windows that is the IP Helper API and always true. On POSIX it means an
202
+ unprivileged SOCK_DGRAM ICMP socket can actually be opened, which Linux
203
+ gates on net.ipv4.ping_group_range -- so the platform being supported is
204
+ not on its own enough.
205
+ """
206
+ if _AVAILABLE:
207
+ return True
208
+ return _posix().is_available()
209
+
210
+
211
+ def unavailable_reason() -> str:
212
+ """Why is_available() said no, phrased so it can be acted on. The Linux
213
+ case has a one-line fix and deserves better than "not available"."""
214
+ if is_available():
215
+ return ""
216
+ return _posix().unavailable_reason()
217
+
218
+
219
+ def ping(
220
+ dest_ip: str,
221
+ ttl: int = 128,
222
+ timeout_ms: int = 1000,
223
+ payload: bytes = DEFAULT_PAYLOAD,
224
+ tos: int = 0,
225
+ source_ip: Optional[str] = None,
226
+ ) -> PingResult:
227
+ """Send one ICMP echo to ``dest_ip`` with the given ``ttl``.
228
+
229
+ ``dest_ip`` must already be a dotted IPv4 literal (resolve hostnames first).
230
+ A short ``ttl`` is how we coax intermediate routers into identifying
231
+ themselves for traceroute.
232
+
233
+ ``tos`` is the IP ToS byte (see :func:`dscp_to_tos`), for probing a path as
234
+ the traffic class you actually care about rather than as best-effort.
235
+
236
+ ``source_ip`` picks the outgoing interface on a multi-homed host, which
237
+ needs IcmpSendEcho2Ex rather than IcmpSendEcho. An address the machine does
238
+ not hold fails with ERROR_INVALID_NETNAME (1214) rather than quietly
239
+ falling back to the default route.
240
+ """
241
+ if not _AVAILABLE:
242
+ # Same signature, same PingResult: the engine above never learns which
243
+ # backend answered it.
244
+ return _posix().ping(dest_ip, ttl, timeout_ms, payload, tos, source_ip)
245
+
246
+ handle = _IcmpCreateFile()
247
+ if not handle or handle == _INVALID_HANDLE_VALUE:
248
+ raise OSError(ctypes.get_last_error(), "IcmpCreateFile failed")
249
+ try:
250
+ dest = _ip_to_uint32(dest_ip)
251
+ opts = IP_OPTION_INFORMATION(
252
+ Ttl=max(1, min(int(ttl), 255)), Tos=int(tos) & 0xFF,
253
+ Flags=0, OptionsSize=0, OptionsData=None
254
+ )
255
+ # Reply buffer must hold an ICMP_ECHO_REPLY, the echoed payload, and
256
+ # room for an embedded ICMP error message. Allocate generously.
257
+ reply_size = ctypes.sizeof(ICMP_ECHO_REPLY) + len(payload) + 8 + 128
258
+ reply_buf = ctypes.create_string_buffer(reply_size)
259
+
260
+ if source_ip:
261
+ n = _IcmpSendEcho2Ex(
262
+ handle,
263
+ None, # Event: NULL keeps it synchronous
264
+ None, # ApcRoutine
265
+ None, # ApcContext
266
+ _ip_to_uint32(source_ip),
267
+ dest,
268
+ payload,
269
+ len(payload),
270
+ ctypes.byref(opts),
271
+ reply_buf,
272
+ reply_size,
273
+ int(timeout_ms),
274
+ )
275
+ else:
276
+ n = _IcmpSendEcho(
277
+ handle,
278
+ dest,
279
+ payload,
280
+ len(payload),
281
+ ctypes.byref(opts),
282
+ reply_buf,
283
+ reply_size,
284
+ int(timeout_ms),
285
+ )
286
+ if n == 0:
287
+ # No reply at all: timeout or a send-side error. GetLastError holds
288
+ # an IP_STATUS code in the same range as reply.Status.
289
+ err = ctypes.get_last_error()
290
+ return PingResult(err or IP_REQ_TIMED_OUT, None, None, False)
291
+
292
+ reply = ctypes.cast(reply_buf, ctypes.POINTER(ICMP_ECHO_REPLY)).contents
293
+ status = int(reply.Status)
294
+ address = _uint32_to_ip(reply.Address) if reply.Address else None
295
+ rtt = float(reply.RoundTripTime)
296
+
297
+ if status == IP_SUCCESS:
298
+ return PingResult(status, rtt, address, True)
299
+ if status == IP_TTL_EXPIRED_TRANSIT:
300
+ return PingResult(status, rtt, address, False)
301
+ # Unreachable / other: an address may still be present (the router that
302
+ # reported the problem), but there is no meaningful RTT to record.
303
+ return PingResult(status, None, address, False)
304
+ finally:
305
+ _IcmpCloseHandle(handle)