netk-cli 0.2.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.
- netk/__init__.py +70 -0
- netk/__main__.py +10 -0
- netk/cli.py +229 -0
- netk/commands/__init__.py +1 -0
- netk/commands/dns.py +121 -0
- netk/commands/doctor.py +96 -0
- netk/commands/http.py +385 -0
- netk/commands/ping.py +203 -0
- netk/commands/schema.py +187 -0
- netk/commands/tcp.py +67 -0
- netk/commands/tls.py +200 -0
- netk/contract.py +132 -0
- netk/dns/__init__.py +18 -0
- netk/dns/client.py +225 -0
- netk/dns/codec.py +232 -0
- netk/dns/resolver.py +81 -0
- netk/py.typed +0 -0
- netk/render.py +221 -0
- netk/slo.py +74 -0
- netk/targets.py +196 -0
- netk_cli-0.2.0.dist-info/METADATA +238 -0
- netk_cli-0.2.0.dist-info/RECORD +26 -0
- netk_cli-0.2.0.dist-info/WHEEL +5 -0
- netk_cli-0.2.0.dist-info/entry_points.txt +2 -0
- netk_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
- netk_cli-0.2.0.dist-info/top_level.txt +1 -0
netk/commands/http.py
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
"""One HTTP request, timed in six phases, with the body actually understood.
|
|
2
|
+
|
|
3
|
+
Why not ``curl -w``: parsing human output breaks on locale and version changes, and
|
|
4
|
+
``curl`` cannot tell you that the 300 ms you lost was certificate validation rather
|
|
5
|
+
than server think-time. Here the phases are measured separately, chunked framing is
|
|
6
|
+
decoded, and gzip/deflate bodies are decompressed before sizing and previewing.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import gzip
|
|
12
|
+
import io
|
|
13
|
+
import socket
|
|
14
|
+
import ssl
|
|
15
|
+
import time
|
|
16
|
+
import zlib
|
|
17
|
+
from urllib.parse import urljoin, urlsplit
|
|
18
|
+
|
|
19
|
+
from ..contract import RC_NEGATIVE, RC_OK, RC_TIMEOUT, VERSION, NetkError, envelope
|
|
20
|
+
from ..targets import connect_addresses, resolve
|
|
21
|
+
|
|
22
|
+
DEFAULT_UA = f"netk/{VERSION} (+single-file diagnostics; zero deps)"
|
|
23
|
+
MAX_HEAD = 256 * 1024
|
|
24
|
+
REDIRECT_CODES = (301, 302, 303, 307, 308)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class _Feed:
|
|
28
|
+
"""Socket buffer that lets the chunk parser pull exactly what it needs."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, sock: socket.socket, initial: bytes) -> None:
|
|
31
|
+
self.sock = sock
|
|
32
|
+
self.buffer = initial
|
|
33
|
+
self.eof = False
|
|
34
|
+
|
|
35
|
+
def _fill(self) -> bool:
|
|
36
|
+
if self.eof:
|
|
37
|
+
return False
|
|
38
|
+
try:
|
|
39
|
+
chunk = self.sock.recv(4096)
|
|
40
|
+
except socket.timeout:
|
|
41
|
+
raise NetkError("timeout", "reading the response body timed out", RC_TIMEOUT) from None
|
|
42
|
+
if not chunk:
|
|
43
|
+
self.eof = True
|
|
44
|
+
return False
|
|
45
|
+
self.buffer += chunk
|
|
46
|
+
return True
|
|
47
|
+
|
|
48
|
+
def read_line(self) -> bytes | None:
|
|
49
|
+
while b"\r\n" not in self.buffer:
|
|
50
|
+
if not self._fill():
|
|
51
|
+
if self.buffer:
|
|
52
|
+
line, self.buffer = self.buffer, b""
|
|
53
|
+
return line
|
|
54
|
+
return None
|
|
55
|
+
line, _, self.buffer = self.buffer.partition(b"\r\n")
|
|
56
|
+
return line
|
|
57
|
+
|
|
58
|
+
def read_exact(self, size: int) -> bytes:
|
|
59
|
+
while len(self.buffer) < size:
|
|
60
|
+
if not self._fill():
|
|
61
|
+
break
|
|
62
|
+
data, self.buffer = self.buffer[:size], self.buffer[size:]
|
|
63
|
+
return data
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _read_head(sock: socket.socket, timeout: float) -> tuple[bytes, bytes, float]:
|
|
67
|
+
buffer, ttfb, started = b"", None, time.perf_counter()
|
|
68
|
+
sock.settimeout(timeout)
|
|
69
|
+
while b"\r\n\r\n" not in buffer:
|
|
70
|
+
if len(buffer) > MAX_HEAD:
|
|
71
|
+
raise NetkError("http", "response head larger than 256 KiB")
|
|
72
|
+
try:
|
|
73
|
+
chunk = sock.recv(4096)
|
|
74
|
+
except socket.timeout:
|
|
75
|
+
raise NetkError("timeout", f"no response within {timeout}s", RC_TIMEOUT) from None
|
|
76
|
+
if not chunk:
|
|
77
|
+
if not buffer:
|
|
78
|
+
raise NetkError("http", "no response before connection closed")
|
|
79
|
+
raise NetkError("http", "connection closed inside the response head")
|
|
80
|
+
if ttfb is None:
|
|
81
|
+
ttfb = time.perf_counter() - started
|
|
82
|
+
buffer += chunk
|
|
83
|
+
head, _, rest = buffer.partition(b"\r\n\r\n")
|
|
84
|
+
return head, rest, ttfb
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _parse_head(head: bytes) -> tuple[str, int, str, dict[str, str], list[str]]:
|
|
88
|
+
lines = head.decode("iso-8859-1").split("\r\n")
|
|
89
|
+
status_line = lines[0].strip()
|
|
90
|
+
parts = status_line.split(" ", 2)
|
|
91
|
+
if len(parts) < 2:
|
|
92
|
+
raise NetkError("http", f"bad status line: {status_line!r}")
|
|
93
|
+
version_token, status_text = parts[0], parts[1]
|
|
94
|
+
try:
|
|
95
|
+
status = int(status_text)
|
|
96
|
+
except ValueError:
|
|
97
|
+
raise NetkError("http", f"bad status code in {status_line!r}") from None
|
|
98
|
+
reason = parts[2] if len(parts) > 2 else ""
|
|
99
|
+
version = version_token.split("/", 1)[1] if "/" in version_token else version_token
|
|
100
|
+
|
|
101
|
+
collected: dict[str, list[str]] = {}
|
|
102
|
+
for line in lines[1:]:
|
|
103
|
+
name, separator, value = line.partition(":")
|
|
104
|
+
if not separator:
|
|
105
|
+
continue
|
|
106
|
+
key = name.strip().lower()
|
|
107
|
+
if key:
|
|
108
|
+
collected.setdefault(key, []).append(value.strip())
|
|
109
|
+
headers = {key: ", ".join(values) for key, values in collected.items()}
|
|
110
|
+
set_cookie = collected.get("set-cookie", [])
|
|
111
|
+
return version, status, reason, headers, set_cookie
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _read_capped(feed: _Feed, limit: int) -> tuple[bytes, bool]:
|
|
115
|
+
body = bytearray(feed.buffer[:limit])
|
|
116
|
+
truncated = len(feed.buffer) > limit
|
|
117
|
+
feed.buffer = b"" if truncated else feed.buffer[limit:]
|
|
118
|
+
if truncated:
|
|
119
|
+
return bytes(body), True
|
|
120
|
+
while True:
|
|
121
|
+
try:
|
|
122
|
+
chunk = feed.sock.recv(4096)
|
|
123
|
+
except socket.timeout:
|
|
124
|
+
raise NetkError("timeout", "reading the response body timed out", RC_TIMEOUT) from None
|
|
125
|
+
if not chunk:
|
|
126
|
+
return bytes(body), False
|
|
127
|
+
room = limit - len(body)
|
|
128
|
+
if room <= 0:
|
|
129
|
+
return bytes(body), True
|
|
130
|
+
if len(chunk) > room:
|
|
131
|
+
body += chunk[:room]
|
|
132
|
+
return bytes(body), True
|
|
133
|
+
body += chunk
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _read_chunked(feed: _Feed, max_body: int) -> tuple[bytes, int, bool]:
|
|
137
|
+
body, wire, truncated = bytearray(), 0, False
|
|
138
|
+
while True:
|
|
139
|
+
line = feed.read_line()
|
|
140
|
+
if line is None:
|
|
141
|
+
raise NetkError("http", "chunked body ended without a final chunk")
|
|
142
|
+
token = line.split(b";", 1)[0].strip()
|
|
143
|
+
try:
|
|
144
|
+
size = int(token, 16)
|
|
145
|
+
except ValueError:
|
|
146
|
+
raise NetkError("http", f"bad chunk size {token!r}") from None
|
|
147
|
+
if size == 0:
|
|
148
|
+
while True:
|
|
149
|
+
trailer = feed.read_line()
|
|
150
|
+
if trailer in (b"", None):
|
|
151
|
+
break
|
|
152
|
+
break
|
|
153
|
+
data = feed.read_exact(size)
|
|
154
|
+
wire += len(data)
|
|
155
|
+
room = max_body - len(body)
|
|
156
|
+
if len(data) <= room:
|
|
157
|
+
body += data
|
|
158
|
+
else:
|
|
159
|
+
body += data[: max(0, room)]
|
|
160
|
+
truncated = True
|
|
161
|
+
if len(data) < size:
|
|
162
|
+
truncated = True
|
|
163
|
+
break
|
|
164
|
+
if feed.read_line() is None:
|
|
165
|
+
break
|
|
166
|
+
return bytes(body), wire, truncated
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _decode_body(body: bytes, encoding: str) -> tuple[bytes, str | None]:
|
|
170
|
+
lowered = encoding.lower().strip()
|
|
171
|
+
if not body or not lowered or lowered == "identity":
|
|
172
|
+
return body, None
|
|
173
|
+
try:
|
|
174
|
+
if lowered in ("gzip", "x-gzip"):
|
|
175
|
+
with gzip.GzipFile(fileobj=io.BytesIO(body)) as handle:
|
|
176
|
+
return handle.read(), None
|
|
177
|
+
if lowered == "deflate":
|
|
178
|
+
try:
|
|
179
|
+
return zlib.decompress(body), None
|
|
180
|
+
except zlib.error:
|
|
181
|
+
return zlib.decompress(body, -zlib.MAX_WBITS), None
|
|
182
|
+
except (OSError, EOFError, zlib.error) as exc:
|
|
183
|
+
return body, f"{type(exc).__name__}: {exc}"
|
|
184
|
+
return body, f"unsupported content-encoding {encoding!r}"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def probe_http(
|
|
188
|
+
url: str,
|
|
189
|
+
method: str = "GET",
|
|
190
|
+
extra_headers: list[str] | None = None,
|
|
191
|
+
body: bytes = b"",
|
|
192
|
+
follow: int = 0,
|
|
193
|
+
timeout: float = 5.0,
|
|
194
|
+
max_body: int = 65536,
|
|
195
|
+
insecure: bool = False,
|
|
196
|
+
want_headers: bool = False,
|
|
197
|
+
want_body: bool = False,
|
|
198
|
+
started_at: float | None = None,
|
|
199
|
+
redirects: list[dict] | None = None,
|
|
200
|
+
decode: bool = True,
|
|
201
|
+
) -> dict:
|
|
202
|
+
"""Perform one request (plus redirects) and return the timed payload."""
|
|
203
|
+
parts = urlsplit(url)
|
|
204
|
+
scheme = (parts.scheme or "https").lower()
|
|
205
|
+
if scheme not in ("http", "https"):
|
|
206
|
+
raise NetkError("usage", f"unsupported scheme {scheme!r}", 2)
|
|
207
|
+
host = parts.hostname
|
|
208
|
+
if not host:
|
|
209
|
+
raise NetkError("usage", f"bad URL {url!r}", 2)
|
|
210
|
+
port = parts.port or (443 if scheme == "https" else 80)
|
|
211
|
+
path = (parts.path or "/") + (f"?{parts.query}" if parts.query else "")
|
|
212
|
+
|
|
213
|
+
t0 = started_at if started_at is not None else time.perf_counter()
|
|
214
|
+
addrs, dns_s = resolve(host, port)
|
|
215
|
+
sock, sockaddr, connect_s = connect_addresses(addrs, host, port, timeout)
|
|
216
|
+
|
|
217
|
+
tls_s, tls_info = 0.0, None
|
|
218
|
+
try:
|
|
219
|
+
if scheme == "https":
|
|
220
|
+
context = ssl.create_default_context()
|
|
221
|
+
context.check_hostname = not insecure
|
|
222
|
+
context.verify_mode = ssl.CERT_NONE if insecure else ssl.CERT_REQUIRED
|
|
223
|
+
started = time.perf_counter()
|
|
224
|
+
try:
|
|
225
|
+
sock = context.wrap_socket(sock, server_hostname=host)
|
|
226
|
+
except ssl.SSLCertVerificationError as exc:
|
|
227
|
+
raise NetkError("tls", f"certificate verification failed: {exc}") from exc
|
|
228
|
+
except ssl.SSLError as exc:
|
|
229
|
+
raise NetkError("tls", f"TLS handshake failed: {exc}") from exc
|
|
230
|
+
tls_s = time.perf_counter() - started
|
|
231
|
+
cipher = sock.cipher() or (None, None, None)
|
|
232
|
+
tls_info = {
|
|
233
|
+
"version": sock.version(),
|
|
234
|
+
"cipher": cipher[0],
|
|
235
|
+
"alpn": sock.selected_alpn_protocol(),
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
request = _build_request(
|
|
239
|
+
method, path, host, port, scheme, extra_headers or [], body, decode
|
|
240
|
+
)
|
|
241
|
+
started = time.perf_counter()
|
|
242
|
+
sock.sendall(request)
|
|
243
|
+
write_s = time.perf_counter() - started
|
|
244
|
+
|
|
245
|
+
head, rest, ttfb = _read_head(sock, timeout)
|
|
246
|
+
version, status, reason, headers, set_cookie = _parse_head(head)
|
|
247
|
+
|
|
248
|
+
if method == "HEAD":
|
|
249
|
+
wire_body, wire_size, truncated = b"", 0, False
|
|
250
|
+
elif "chunked" in headers.get("transfer-encoding", "").lower():
|
|
251
|
+
wire_body, wire_size, truncated = _read_chunked(_Feed(sock, rest), max_body)
|
|
252
|
+
elif headers.get("content-length", "").isdigit():
|
|
253
|
+
length = int(headers["content-length"])
|
|
254
|
+
truncated = length > max_body
|
|
255
|
+
wire_body = _Feed(sock, rest).read_exact(min(length, max_body)) if max_body > 0 else b""
|
|
256
|
+
wire_size = len(wire_body)
|
|
257
|
+
else:
|
|
258
|
+
wire_body, truncated = _read_capped(_Feed(sock, rest), max_body)
|
|
259
|
+
wire_size = len(wire_body)
|
|
260
|
+
|
|
261
|
+
read_s = time.perf_counter() - started - (ttfb or 0)
|
|
262
|
+
total_s = time.perf_counter() - t0
|
|
263
|
+
finally:
|
|
264
|
+
sock.close()
|
|
265
|
+
|
|
266
|
+
content_encoding = headers.get("content-encoding", "")
|
|
267
|
+
decoded, decode_error = (
|
|
268
|
+
_decode_body(wire_body, content_encoding) if decode else (wire_body, None)
|
|
269
|
+
)
|
|
270
|
+
if truncated and content_encoding and decode:
|
|
271
|
+
decoded, decode_error = wire_body, "body truncated; not decoded"
|
|
272
|
+
size = len(decoded)
|
|
273
|
+
|
|
274
|
+
location = headers.get("location")
|
|
275
|
+
if follow > 0 and status in REDIRECT_CODES and location:
|
|
276
|
+
nxt = urljoin(url, location)
|
|
277
|
+
chain = (redirects or []) + [{"url": url, "status": status, "location": nxt}]
|
|
278
|
+
next_method = "GET" if status in (301, 302, 303) and method not in ("HEAD",) else method
|
|
279
|
+
next_body = b"" if next_method != method else body
|
|
280
|
+
return probe_http(
|
|
281
|
+
nxt,
|
|
282
|
+
next_method,
|
|
283
|
+
extra_headers or [],
|
|
284
|
+
next_body,
|
|
285
|
+
follow - 1,
|
|
286
|
+
timeout,
|
|
287
|
+
max_body,
|
|
288
|
+
insecure,
|
|
289
|
+
want_headers,
|
|
290
|
+
want_body,
|
|
291
|
+
started_at=t0,
|
|
292
|
+
redirects=chain,
|
|
293
|
+
decode=decode,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
payload = envelope(
|
|
297
|
+
"http",
|
|
298
|
+
rc=RC_OK if status < 400 else RC_NEGATIVE,
|
|
299
|
+
url=url,
|
|
300
|
+
final_url=url,
|
|
301
|
+
status=status,
|
|
302
|
+
reason=reason,
|
|
303
|
+
http_version=version,
|
|
304
|
+
remote_ip=sockaddr[0],
|
|
305
|
+
remote_port=port,
|
|
306
|
+
tls=tls_info,
|
|
307
|
+
phases={
|
|
308
|
+
"dns_ms": round(dns_s * 1000, 3),
|
|
309
|
+
"connect_ms": round(connect_s * 1000, 3),
|
|
310
|
+
"tls_ms": round(tls_s * 1000, 3),
|
|
311
|
+
"write_ms": round(write_s * 1000, 3),
|
|
312
|
+
"wait_ms": round(max(0.0, (ttfb or 0) - write_s) * 1000, 3),
|
|
313
|
+
"transfer_ms": round(max(0.0, read_s) * 1000, 3),
|
|
314
|
+
"total_ms": round(total_s * 1000, 3),
|
|
315
|
+
},
|
|
316
|
+
size=size,
|
|
317
|
+
wire_size=wire_size,
|
|
318
|
+
truncated=truncated,
|
|
319
|
+
content_type=headers.get("content-type"),
|
|
320
|
+
content_encoding=content_encoding or None,
|
|
321
|
+
decode_error=decode_error,
|
|
322
|
+
content_length=int(headers["content-length"])
|
|
323
|
+
if headers.get("content-length", "").isdigit()
|
|
324
|
+
else None,
|
|
325
|
+
server=headers.get("server"),
|
|
326
|
+
redirects=redirects or [],
|
|
327
|
+
)
|
|
328
|
+
if want_headers:
|
|
329
|
+
payload["headers"] = headers
|
|
330
|
+
if set_cookie:
|
|
331
|
+
payload["set_cookie"] = set_cookie
|
|
332
|
+
if want_body:
|
|
333
|
+
payload["body_preview"] = decoded[:2000].decode("utf-8", "replace")
|
|
334
|
+
return payload
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _build_request(
|
|
338
|
+
method: str,
|
|
339
|
+
path: str,
|
|
340
|
+
host: str,
|
|
341
|
+
port: int,
|
|
342
|
+
scheme: str,
|
|
343
|
+
extra_headers: list[str],
|
|
344
|
+
body: bytes,
|
|
345
|
+
decode: bool,
|
|
346
|
+
) -> bytes:
|
|
347
|
+
default_port = 443 if scheme == "https" else 80
|
|
348
|
+
host_header = host if port == default_port else f"{host}:{port}"
|
|
349
|
+
supplied = {line.split(":", 1)[0].strip().lower() for line in extra_headers if ":" in line}
|
|
350
|
+
lines = [f"{method} {path} HTTP/1.1"]
|
|
351
|
+
if "host" not in supplied:
|
|
352
|
+
lines.append(f"Host: {host_header}")
|
|
353
|
+
lines += [
|
|
354
|
+
f"User-Agent: {DEFAULT_UA}",
|
|
355
|
+
"Accept: */*",
|
|
356
|
+
f"Accept-Encoding: {'gzip, deflate' if decode else 'identity'}",
|
|
357
|
+
"Connection: close",
|
|
358
|
+
]
|
|
359
|
+
if body and "content-length" not in supplied:
|
|
360
|
+
lines.append(f"Content-Length: {len(body)}")
|
|
361
|
+
lines.extend(extra_headers)
|
|
362
|
+
return ("\r\n".join(lines) + "\r\n\r\n").encode("iso-8859-1") + body
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def run(args) -> dict:
|
|
366
|
+
headers = []
|
|
367
|
+
for header in args.header or []:
|
|
368
|
+
if ":" not in header:
|
|
369
|
+
raise NetkError("usage", f"bad header {header!r}, want 'Name: value'", 2)
|
|
370
|
+
headers.append(header)
|
|
371
|
+
body = args.data.encode() if args.data else b""
|
|
372
|
+
payload = probe_http(
|
|
373
|
+
args.url,
|
|
374
|
+
args.method,
|
|
375
|
+
headers,
|
|
376
|
+
body,
|
|
377
|
+
args.follow,
|
|
378
|
+
args.timeout,
|
|
379
|
+
args.max_body,
|
|
380
|
+
args.insecure,
|
|
381
|
+
args.headers,
|
|
382
|
+
args.body,
|
|
383
|
+
decode=not args.no_decode,
|
|
384
|
+
)
|
|
385
|
+
return payload
|
netk/commands/ping.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Latency and loss: ICMP where the OS allows it, TCP handshake where it does not.
|
|
2
|
+
|
|
3
|
+
The ``method`` field is part of the answer, because "3 ms average" means something
|
|
4
|
+
different when it is a TCP handshake rather than an ICMP echo. Permission is
|
|
5
|
+
handled by trying ``SOCK_DGRAM`` first (unprivileged ICMP on Linux/macOS), then
|
|
6
|
+
raw sockets, then falling back to TCP -- never by re-executing under sudo.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import random
|
|
12
|
+
import socket
|
|
13
|
+
import struct
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
from ..contract import RC_NEGATIVE, RC_TIMEOUT, NetkError, envelope
|
|
17
|
+
from ..targets import resolve
|
|
18
|
+
|
|
19
|
+
ICMP_ECHO_REQUEST = 8
|
|
20
|
+
ICMP_ECHO_REQUEST_V6 = 128
|
|
21
|
+
ICMP_ECHO_REPLY = 0
|
|
22
|
+
ICMP_ECHO_REPLY_V6 = 129
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _icmp_socket(family: int) -> tuple[socket.socket | None, str | None]:
|
|
26
|
+
"""Try unprivileged ICMP first, then raw. Returns (socket, method label)."""
|
|
27
|
+
proto = socket.IPPROTO_ICMPV6 if family == socket.AF_INET6 else socket.IPPROTO_ICMP
|
|
28
|
+
for socktype, kind in ((socket.SOCK_DGRAM, "icmp"), (socket.SOCK_RAW, "icmp_raw")):
|
|
29
|
+
try:
|
|
30
|
+
return socket.socket(family, socktype, proto), kind
|
|
31
|
+
except OSError:
|
|
32
|
+
continue
|
|
33
|
+
return None, None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def checksum(data: bytes) -> int:
|
|
37
|
+
if len(data) % 2:
|
|
38
|
+
data += b"\x00"
|
|
39
|
+
total = sum(struct.unpack(f"!{len(data) // 2}H", data))
|
|
40
|
+
total = (total >> 16) + (total & 0xFFFF)
|
|
41
|
+
total += total >> 16
|
|
42
|
+
return ~total & 0xFFFF
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def icmp_ping(
|
|
46
|
+
address: str, family: int, count: int, interval: float, timeout: float, size: int
|
|
47
|
+
) -> dict | None:
|
|
48
|
+
"""Echo ``count`` times. Returns None when ICMP is unavailable at all."""
|
|
49
|
+
sock, kind = _icmp_socket(family)
|
|
50
|
+
if sock is None:
|
|
51
|
+
return None
|
|
52
|
+
is_v6 = family == socket.AF_INET6
|
|
53
|
+
ident = random.randint(1, 0xFFFF)
|
|
54
|
+
samples: list[dict] = []
|
|
55
|
+
try:
|
|
56
|
+
sock.settimeout(timeout)
|
|
57
|
+
for seq in range(1, count + 1):
|
|
58
|
+
if is_v6:
|
|
59
|
+
header = struct.pack("!BBHHH", ICMP_ECHO_REQUEST_V6, 0, 0, ident, seq)
|
|
60
|
+
else:
|
|
61
|
+
header = struct.pack("!BBHHH", ICMP_ECHO_REQUEST, 0, 0, ident, seq)
|
|
62
|
+
payload = struct.pack("!d", time.time()) + bytes(size)
|
|
63
|
+
packet = header + payload
|
|
64
|
+
if not is_v6 and kind == "icmp_raw":
|
|
65
|
+
packet = packet[:2] + struct.pack("!H", checksum(packet)) + packet[4:]
|
|
66
|
+
sent = time.perf_counter()
|
|
67
|
+
try:
|
|
68
|
+
sock.sendto(packet, (address, 0))
|
|
69
|
+
except OSError as exc:
|
|
70
|
+
return {"error": str(exc)}
|
|
71
|
+
deadline = sent + timeout
|
|
72
|
+
rtt, ttl = None, None
|
|
73
|
+
while time.perf_counter() < deadline:
|
|
74
|
+
try:
|
|
75
|
+
sock.settimeout(max(0.001, deadline - time.perf_counter()))
|
|
76
|
+
data, _ = sock.recvfrom(2048)
|
|
77
|
+
except OSError:
|
|
78
|
+
break
|
|
79
|
+
offset = 0
|
|
80
|
+
if kind == "icmp_raw" and not is_v6 and len(data) > 20:
|
|
81
|
+
offset = (data[0] & 0x0F) * 4
|
|
82
|
+
ttl = data[8]
|
|
83
|
+
reply = data[offset:]
|
|
84
|
+
if len(reply) < 8:
|
|
85
|
+
continue
|
|
86
|
+
rtype, _, _, _, rseq = struct.unpack("!BBHHH", reply[:8])
|
|
87
|
+
if rtype not in (ICMP_ECHO_REPLY, ICMP_ECHO_REPLY_V6) or rseq != seq:
|
|
88
|
+
continue
|
|
89
|
+
rtt = round((time.perf_counter() - sent) * 1000, 3)
|
|
90
|
+
break
|
|
91
|
+
samples.append({"seq": seq, "rtt_ms": rtt, "ttl": ttl})
|
|
92
|
+
if seq < count:
|
|
93
|
+
time.sleep(interval)
|
|
94
|
+
finally:
|
|
95
|
+
sock.close()
|
|
96
|
+
return {"method": kind, "samples": samples}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def tcp_ping(host: str, port: int, count: int, interval: float, timeout: float) -> dict:
|
|
100
|
+
samples = []
|
|
101
|
+
for seq in range(1, count + 1):
|
|
102
|
+
started = time.perf_counter()
|
|
103
|
+
try:
|
|
104
|
+
sock = socket.create_connection((host, port), timeout=timeout)
|
|
105
|
+
sock.close()
|
|
106
|
+
samples.append({"seq": seq, "rtt_ms": round((time.perf_counter() - started) * 1000, 3)})
|
|
107
|
+
except OSError:
|
|
108
|
+
samples.append({"seq": seq, "rtt_ms": None})
|
|
109
|
+
if seq < count:
|
|
110
|
+
time.sleep(interval)
|
|
111
|
+
return {"method": "tcp", "samples": samples}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def summarize(samples: list[dict]) -> dict:
|
|
115
|
+
got = [s["rtt_ms"] for s in samples if s.get("rtt_ms") is not None]
|
|
116
|
+
sent = len(samples)
|
|
117
|
+
if not got:
|
|
118
|
+
return {
|
|
119
|
+
"sent": sent,
|
|
120
|
+
"received": 0,
|
|
121
|
+
"loss_pct": 100.0,
|
|
122
|
+
"min_ms": None,
|
|
123
|
+
"avg_ms": None,
|
|
124
|
+
"max_ms": None,
|
|
125
|
+
"mdev_ms": None,
|
|
126
|
+
"jitter_ms": None,
|
|
127
|
+
}
|
|
128
|
+
avg = sum(got) / len(got)
|
|
129
|
+
mdev = sum(abs(value - avg) for value in got) / len(got)
|
|
130
|
+
deltas = [abs(got[i] - got[i - 1]) for i in range(1, len(got))]
|
|
131
|
+
return {
|
|
132
|
+
"sent": sent,
|
|
133
|
+
"received": len(got),
|
|
134
|
+
"loss_pct": round(100 * (sent - len(got)) / sent, 1),
|
|
135
|
+
"min_ms": round(min(got), 3),
|
|
136
|
+
"avg_ms": round(avg, 3),
|
|
137
|
+
"max_ms": round(max(got), 3),
|
|
138
|
+
"mdev_ms": round(mdev, 3),
|
|
139
|
+
"jitter_ms": round(sum(deltas) / len(deltas), 3) if deltas else 0.0,
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def run(args) -> dict:
|
|
144
|
+
host = args.host
|
|
145
|
+
if args.count < 1:
|
|
146
|
+
raise NetkError("usage", "--count must be >= 1", 2)
|
|
147
|
+
if args.interval < 0:
|
|
148
|
+
raise NetkError("usage", "--interval must be >= 0", 2)
|
|
149
|
+
if not 0 <= args.size <= 65000:
|
|
150
|
+
raise NetkError("usage", "--size must be within 0..65000", 2)
|
|
151
|
+
|
|
152
|
+
port = args.port if args.method == "tcp" else 0
|
|
153
|
+
family = {"ipv4": socket.AF_INET, "ipv6": socket.AF_INET6}.get(args.ip, socket.AF_UNSPEC)
|
|
154
|
+
addrs, dns_s = resolve(host, port, family)
|
|
155
|
+
address, family = addrs[0][1][0], addrs[0][0]
|
|
156
|
+
|
|
157
|
+
payload = envelope(
|
|
158
|
+
"ping",
|
|
159
|
+
target=host,
|
|
160
|
+
address=address,
|
|
161
|
+
family="IPv6" if family == socket.AF_INET6 else "IPv4",
|
|
162
|
+
dns_ms=round(dns_s * 1000, 3),
|
|
163
|
+
count=args.count,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
outcome = None
|
|
167
|
+
if args.method in ("auto", "icmp"):
|
|
168
|
+
outcome = icmp_ping(address, family, args.count, args.interval, args.timeout, args.size)
|
|
169
|
+
if outcome is None and args.method == "icmp":
|
|
170
|
+
raise NetkError(
|
|
171
|
+
"connection",
|
|
172
|
+
"ICMP unavailable (needs root/Administrator or a permissive ping_group_range)",
|
|
173
|
+
)
|
|
174
|
+
if outcome is not None and "error" in outcome:
|
|
175
|
+
if args.method == "icmp":
|
|
176
|
+
raise NetkError("connection", f"ICMP send failed: {outcome['error']}")
|
|
177
|
+
payload["note"] = f"ICMP send failed ({outcome['error']}), falling back to TCP"
|
|
178
|
+
outcome = None
|
|
179
|
+
|
|
180
|
+
if outcome is None:
|
|
181
|
+
result = tcp_ping(host, args.port, args.count, args.interval, args.timeout)
|
|
182
|
+
payload["note"] = f"ICMP unavailable, measured TCP handshake to {host}:{args.port} instead"
|
|
183
|
+
else:
|
|
184
|
+
result = outcome
|
|
185
|
+
|
|
186
|
+
payload.update(
|
|
187
|
+
{
|
|
188
|
+
"method": result["method"],
|
|
189
|
+
"samples": result["samples"],
|
|
190
|
+
"port": args.port if result["method"] == "tcp" else None,
|
|
191
|
+
}
|
|
192
|
+
)
|
|
193
|
+
payload["stats"] = summarize(result["samples"])
|
|
194
|
+
|
|
195
|
+
received = payload["stats"]["received"]
|
|
196
|
+
if received == 0:
|
|
197
|
+
payload["rc"] = RC_TIMEOUT
|
|
198
|
+
elif payload["stats"]["loss_pct"] > 0:
|
|
199
|
+
payload["rc"] = RC_NEGATIVE
|
|
200
|
+
return payload
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
__all__ = ["icmp_ping", "tcp_ping", "summarize", "checksum", "run"]
|