vdm10-python 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.
- metzler/__init__.py +93 -0
- metzler/__main__.py +18 -0
- metzler/cli.py +262 -0
- metzler/config.py +42 -0
- metzler/discovery.py +525 -0
- metzler/media/__init__.py +1 -0
- metzler/media/g711.py +59 -0
- metzler/media/intercom.py +340 -0
- metzler/media/local.py +219 -0
- metzler/media/rtp.py +106 -0
- metzler/media/rtsp.py +73 -0
- metzler/media/rtsp_puller.py +128 -0
- metzler/media/rtsp_server.py +254 -0
- metzler/media/srtp.py +123 -0
- metzler/provider.py +500 -0
- metzler/py.typed +0 -0
- metzler/sip/__init__.py +1 -0
- metzler/sip/digest.py +45 -0
- metzler/sip/message.py +81 -0
- metzler/sip/sdp.py +89 -0
- metzler/station/__init__.py +6 -0
- metzler/station/bridge.py +284 -0
- metzler/station/call.py +52 -0
- metzler/station/core.py +574 -0
- metzler/station/door_unlock.py +42 -0
- metzler/station/ha_answer.py +92 -0
- metzler/station/ha_media.py +95 -0
- metzler/station/inbound.py +90 -0
- metzler/station/local_answer.py +97 -0
- metzler/station/outbound.py +137 -0
- metzler/station/registration.py +167 -0
- metzler/station/station.py +33 -0
- metzler/station/teardown.py +87 -0
- vdm10_python-0.1.0.dist-info/METADATA +86 -0
- vdm10_python-0.1.0.dist-info/RECORD +38 -0
- vdm10_python-0.1.0.dist-info/WHEEL +4 -0
- vdm10_python-0.1.0.dist-info/entry_points.txt +4 -0
- vdm10_python-0.1.0.dist-info/licenses/LICENSE +674 -0
metzler/discovery.py
ADDED
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
"""LAN discovery for VDM10 devices (stdlib only, no dependencies).
|
|
2
|
+
|
|
3
|
+
Two mechanisms, both verified against live firmware V2.0.24:
|
|
4
|
+
|
|
5
|
+
1. SADP inquiry (Hikvision Secure Active Discovery Protocol): an XML
|
|
6
|
+
``<Probe>`` to the multicast group ``239.255.255.250:37020`` (plus optional
|
|
7
|
+
unicast sweep - multicast may be filtered). Outdoor stations answer with a
|
|
8
|
+
``<ProbeMatch>`` XML (DeviceType/DeviceDescription/DeviceSN/MAC/IPv4).
|
|
9
|
+
The indoor units run the SADP *client* side (``sadpc_*``,
|
|
10
|
+
``confrelatedev_check_doorDev``) to find doors but do not answer inquiries.
|
|
11
|
+
|
|
12
|
+
2. Registrar fingerprint: a kind-1 indoor REGISTER to ``host:5065``. The main
|
|
13
|
+
indoor's registrar replies to ``source-ip:5060`` - ``htons(5060)`` is
|
|
14
|
+
hard-coded in ``send_reply`` (``vdm10_1.0/sip/server/registrar.c``), NOT
|
|
15
|
+
the Via port - so the probing socket must bind :5060. Any SIP reply means
|
|
16
|
+
a registrar is present (main indoor); extension indoors have no registrar
|
|
17
|
+
and stay silent. Status codes map extension-slot state: ``410 Sip Gone``
|
|
18
|
+
= number taken by another device, ``200 OK`` = slot free - but a ``200``
|
|
19
|
+
*inserts* a dev_reg row, so every probe is followed by an ``Expires: 0``
|
|
20
|
+
unregister to clean up (verified: 200 OK).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import random
|
|
26
|
+
import select
|
|
27
|
+
import socket
|
|
28
|
+
import time
|
|
29
|
+
import uuid
|
|
30
|
+
import xml.etree.ElementTree as ET
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
SADP_GROUP = "239.255.255.250"
|
|
34
|
+
SADP_PORT = 37020
|
|
35
|
+
REGISTRAR_PORT = 5065
|
|
36
|
+
SIP_UA_PORT = 5060
|
|
37
|
+
VDM10_OUTDOOR_TYPE = "57619"
|
|
38
|
+
VDM10_MAC_PREFIXES = ("bc:9b:5e",)
|
|
39
|
+
EXT_BASE = "1000000000" # devLongNum prefix; + slot digit = 11-char AOR
|
|
40
|
+
EXT_SLOTS = range(0, 6) # firmware caps registered extensions at idx 5
|
|
41
|
+
|
|
42
|
+
_SADP_PROBE = '<?xml version="1.0" encoding="utf-8"?><Probe><Uuid>{u}</Uuid><Types>inquiry</Types></Probe>'
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _parse_probe_match(data: bytes) -> dict | None:
|
|
46
|
+
try:
|
|
47
|
+
root = ET.fromstring(data.decode("utf-8", "replace"))
|
|
48
|
+
except ET.ParseError:
|
|
49
|
+
return None
|
|
50
|
+
if root.tag != "ProbeMatch":
|
|
51
|
+
return None
|
|
52
|
+
return {c.tag: (c.text or "") for c in root}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def sadp_probe(targets=(), timeout=3.0, multicast=True, iface_ip=None):
|
|
56
|
+
"""SADP inquiry -> list of {tag: value} dicts keyed by responding IP.
|
|
57
|
+
|
|
58
|
+
``targets``: extra unicast (host, port) tuples for the sweep fallback.
|
|
59
|
+
"""
|
|
60
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
61
|
+
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
62
|
+
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
63
|
+
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
|
|
64
|
+
if iface_ip:
|
|
65
|
+
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(iface_ip))
|
|
66
|
+
s.settimeout(timeout)
|
|
67
|
+
s.bind(("", 0))
|
|
68
|
+
probe = _SADP_PROBE.format(u=uuid.uuid4()).encode()
|
|
69
|
+
dests = ([(SADP_GROUP, SADP_PORT)] if multicast else []) + [(h, p) for h, p in targets]
|
|
70
|
+
for d in dests:
|
|
71
|
+
try:
|
|
72
|
+
s.sendto(probe, d)
|
|
73
|
+
except OSError:
|
|
74
|
+
continue
|
|
75
|
+
out, seen = {}, set()
|
|
76
|
+
end = time.time() + timeout
|
|
77
|
+
while time.time() < end:
|
|
78
|
+
try:
|
|
79
|
+
data, addr = s.recvfrom(65535)
|
|
80
|
+
except TimeoutError:
|
|
81
|
+
break
|
|
82
|
+
if addr[0] in seen:
|
|
83
|
+
continue
|
|
84
|
+
m = _parse_probe_match(data)
|
|
85
|
+
if m is None:
|
|
86
|
+
continue
|
|
87
|
+
seen.add(addr[0])
|
|
88
|
+
m["_ip"] = addr[0]
|
|
89
|
+
out[addr[0]] = m
|
|
90
|
+
s.close()
|
|
91
|
+
return list(out.values())
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def is_vdm10_outdoor(match: dict) -> bool:
|
|
95
|
+
mac = (match.get("MAC") or "").lower()
|
|
96
|
+
return match.get("DeviceType") == VDM10_OUTDOOR_TYPE or mac.startswith(VDM10_MAC_PREFIXES)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _reg_packet(host, ext, call_id, expires, serial, mac, floor, local_ip, listen_port, reg_port):
|
|
100
|
+
body = ""
|
|
101
|
+
if expires:
|
|
102
|
+
body = (
|
|
103
|
+
"<regXML>\r\n"
|
|
104
|
+
f"<regDevSerial>{serial}</regDevSerial>\r\n"
|
|
105
|
+
f"<regDevMacAddr>{mac}</regDevMacAddr>\r\n"
|
|
106
|
+
f"<sipNum>{ext}</sipNum>\r\n"
|
|
107
|
+
f"<floorNum>{floor}</floorNum>\r\n"
|
|
108
|
+
"</regXML>"
|
|
109
|
+
)
|
|
110
|
+
via = f"SIP/2.0/UDP {local_ip}:{listen_port};branch=z9hG4bK-{call_id[:16]}"
|
|
111
|
+
return (
|
|
112
|
+
f"REGISTER sip:{host}:{reg_port} SIP/2.0\r\n"
|
|
113
|
+
f"Via: {via}\r\n"
|
|
114
|
+
f"To: <sip:{ext}@{host}:{reg_port}>\r\n"
|
|
115
|
+
f'From: "probe"<sip:{ext}@{local_ip}>;tag=p{call_id[:8]}\r\n'
|
|
116
|
+
f"Call-ID: {call_id}\r\nCSeq: 1 REGISTER\r\n"
|
|
117
|
+
f"Contact: <sip:{ext}@{local_ip}:{listen_port}>\r\n"
|
|
118
|
+
f"Expires: {expires}\r\nMax-Forwards: 70\r\n"
|
|
119
|
+
f"User-Agent: eXosip/3.6.0\r\n"
|
|
120
|
+
f"Content-Type: text/xml\r\nContent-Length: {len(body)}\r\n\r\n{body}"
|
|
121
|
+
).encode()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _status_of(data: bytes) -> int | None:
|
|
125
|
+
try:
|
|
126
|
+
line = data.split(b"\r\n", 1)[0].decode("ascii", "replace")
|
|
127
|
+
if line.startswith("SIP/2.0 "):
|
|
128
|
+
return int(line.split()[1])
|
|
129
|
+
except (IndexError, ValueError):
|
|
130
|
+
pass
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def registrar_probe(
|
|
135
|
+
host,
|
|
136
|
+
ext=None,
|
|
137
|
+
timeout=3.0,
|
|
138
|
+
listen_port=SIP_UA_PORT,
|
|
139
|
+
reg_port=REGISTRAR_PORT,
|
|
140
|
+
serial="Q12345678",
|
|
141
|
+
mac="02:00:11:22:33:44",
|
|
142
|
+
floor=3,
|
|
143
|
+
local_ip=None,
|
|
144
|
+
):
|
|
145
|
+
"""REGISTER fingerprint -> SIP status int, or None when the host is silent.
|
|
146
|
+
|
|
147
|
+
The probe binds ``listen_port`` because the VDM10 registrar replies to
|
|
148
|
+
source-ip:5060 unconditionally (``send_reply`` hard-codes the port). On a
|
|
149
|
+
2xx answer the probe *registered* an extension, so an ``Expires: 0``
|
|
150
|
+
unregister is sent immediately to remove the dev_reg row again.
|
|
151
|
+
"""
|
|
152
|
+
ext = ext or f"{EXT_BASE}0"
|
|
153
|
+
if local_ip is None:
|
|
154
|
+
local_ip = local_ip_for(host)
|
|
155
|
+
u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
156
|
+
u.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
157
|
+
u.settimeout(timeout)
|
|
158
|
+
u.bind(("", listen_port)) # registrar answers only here (firmware)
|
|
159
|
+
call_id = f"vdm10-probe-{uuid.uuid4().hex[:12]}"
|
|
160
|
+
u.sendto(
|
|
161
|
+
_reg_packet(host, ext, call_id, 900, serial, mac, floor, local_ip, listen_port, reg_port),
|
|
162
|
+
(host, reg_port),
|
|
163
|
+
)
|
|
164
|
+
status, end = None, time.time() + timeout
|
|
165
|
+
while time.time() < end:
|
|
166
|
+
try:
|
|
167
|
+
data, _ = u.recvfrom(65535)
|
|
168
|
+
except TimeoutError:
|
|
169
|
+
break
|
|
170
|
+
status = _status_of(data) or status
|
|
171
|
+
if status and status >= 200: # final response (skip 1xx)
|
|
172
|
+
break
|
|
173
|
+
if status and 200 <= status < 300:
|
|
174
|
+
u.sendto(
|
|
175
|
+
_reg_packet(host, ext, f"{call_id}-unreg", 0, serial, mac, floor, local_ip, listen_port, reg_port),
|
|
176
|
+
(host, reg_port),
|
|
177
|
+
)
|
|
178
|
+
try:
|
|
179
|
+
u.recvfrom(65535) # drain the unregister ack
|
|
180
|
+
except TimeoutError:
|
|
181
|
+
pass
|
|
182
|
+
u.close()
|
|
183
|
+
return status
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def scan_extension_slots(host, slots=EXT_SLOTS, **kw):
|
|
187
|
+
"""probe ``{base}{slot}`` for each slot -> {ext_number: status|None}.
|
|
188
|
+
|
|
189
|
+
Live semantics: 410 = slot taken by a device, 200 = free (slot row is
|
|
190
|
+
removed again by the probe's unregister follow-up), None = no registrar.
|
|
191
|
+
"""
|
|
192
|
+
return {f"{EXT_BASE}{slot}": registrar_probe(host, f"{EXT_BASE}{slot}", **kw) for slot in slots}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def free_extension(host, **kw) -> str | None:
|
|
196
|
+
"""lowest free (status 200) extension long-number on the registrar."""
|
|
197
|
+
for ext, status in scan_extension_slots(host, **kw).items():
|
|
198
|
+
if status and 200 <= status < 300:
|
|
199
|
+
return ext
|
|
200
|
+
return None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def is_vdm10_host(ip: str) -> bool:
|
|
204
|
+
"""OUI check via the ARP table - Metzler/Hikvision VDM10 OUIs."""
|
|
205
|
+
try:
|
|
206
|
+
for line in Path("/proc/net/arp").read_text().splitlines()[1:]:
|
|
207
|
+
cols = line.split()
|
|
208
|
+
if cols[0] == ip:
|
|
209
|
+
return cols[3].lower().startswith(VDM10_MAC_PREFIXES)
|
|
210
|
+
except OSError:
|
|
211
|
+
pass
|
|
212
|
+
return True # outside Linux / no arp entry -> don't filter it out
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def docker_detected() -> bool:
|
|
216
|
+
"""running inside a container -> derived IPs are the NAT'd bridge address,
|
|
217
|
+
useless for SIP: callers must ask the user for the host's real LAN IP."""
|
|
218
|
+
if Path("/.dockerenv").exists():
|
|
219
|
+
return True
|
|
220
|
+
try:
|
|
221
|
+
cgroup = Path("/proc/1/cgroup").read_text(errors="replace")
|
|
222
|
+
except OSError:
|
|
223
|
+
return False
|
|
224
|
+
return any(marker in cgroup for marker in ("docker", "containerd", "kubepods", "podman"))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def local_ip_for(host, port=REGISTRAR_PORT) -> str:
|
|
228
|
+
"""the local IP used to reach ``host`` (UDP connect, no traffic sent)."""
|
|
229
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
230
|
+
try:
|
|
231
|
+
s.connect((host, port))
|
|
232
|
+
return s.getsockname()[0]
|
|
233
|
+
finally:
|
|
234
|
+
s.close()
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def subnet_of(ip: str) -> list[str]:
|
|
238
|
+
"""/24 host list derived from an IP (the VDM10 default LAN layout)."""
|
|
239
|
+
base = ip.rsplit(".", 1)[0]
|
|
240
|
+
return [f"{base}.{i}" for i in range(1, 255)]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def tcp_candidates(subnet, ports=(8000, 8102), connect_timeout=0.5):
|
|
244
|
+
"""parallel TCP connect scan -> {ip: [open ports]} - the Hikvision SDK/
|
|
245
|
+
visNet signature narrows REGISTER fingerprinting to a handful of hosts."""
|
|
246
|
+
import concurrent.futures
|
|
247
|
+
|
|
248
|
+
def probe(host, port):
|
|
249
|
+
try:
|
|
250
|
+
t = socket.create_connection((host, port), connect_timeout)
|
|
251
|
+
t.close()
|
|
252
|
+
return port
|
|
253
|
+
except OSError:
|
|
254
|
+
return None
|
|
255
|
+
|
|
256
|
+
out = {}
|
|
257
|
+
with concurrent.futures.ThreadPoolExecutor(64) as ex:
|
|
258
|
+
for host, port in [(h, p) for h in subnet for p in ports]:
|
|
259
|
+
r = ex.submit(probe, host, port)
|
|
260
|
+
if r.result() is not None:
|
|
261
|
+
out.setdefault(host, []).append(r.result())
|
|
262
|
+
return out
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def discover(timeout=3.0, subnet=None, local_ip=None):
|
|
266
|
+
"""full LAN sweep -> {"doors": [...], "registrars": [...], "candidates": [...]}
|
|
267
|
+
|
|
268
|
+
- ``doors``: SADP ProbeMatch dicts of outdoor stations (DeviceType 57619
|
|
269
|
+
or VDM10 OUI)
|
|
270
|
+
- ``registrars``: hosts that answered the :5065 REGISTER fingerprint -
|
|
271
|
+
i.e. the main indoor (extension indoors stay silent)
|
|
272
|
+
- ``candidates``: hosts with the Hikvision TCP signature that were neither
|
|
273
|
+
SADP responders nor registrars - shown as "possible indoor" fallback
|
|
274
|
+
"""
|
|
275
|
+
local_ip = local_ip or _default_local_ip()
|
|
276
|
+
subnet = subnet or (subnet_of(local_ip) if local_ip else [])
|
|
277
|
+
doors = [
|
|
278
|
+
m
|
|
279
|
+
for m in sadp_probe(targets=((h, SADP_PORT) for h in subnet), timeout=timeout, iface_ip=local_ip)
|
|
280
|
+
if is_vdm10_outdoor(m)
|
|
281
|
+
]
|
|
282
|
+
door_ips = {d["_ip"] for d in doors}
|
|
283
|
+
# cheap pre-filter: only Hikvision-signature hosts get the SIP fingerprint
|
|
284
|
+
candidates = tcp_candidates(subnet)
|
|
285
|
+
registrars = [
|
|
286
|
+
h
|
|
287
|
+
for h in candidates
|
|
288
|
+
if h not in door_ips and registrar_probe(h, timeout=min(timeout, 2.0), local_ip=local_ip) is not None
|
|
289
|
+
]
|
|
290
|
+
return {
|
|
291
|
+
"doors": doors,
|
|
292
|
+
"registrars": registrars,
|
|
293
|
+
"candidates": [h for h in candidates if h not in door_ips and h not in registrars],
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _default_local_ip():
|
|
298
|
+
for target in ("192.168.1.1", "10.0.0.1", "8.8.8.8"):
|
|
299
|
+
try:
|
|
300
|
+
return local_ip_for(target, 80)
|
|
301
|
+
except OSError:
|
|
302
|
+
continue
|
|
303
|
+
return None
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
# --- config-flow status probes (vdm10-ha) ----------------------------------
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _reg_xml(serial: str, mac: str, name: str, floor: int = 1) -> str:
|
|
310
|
+
# exact firmware field order (_sip_xml_get_reg_info_xml): serial, mac, name, floorNum
|
|
311
|
+
return (
|
|
312
|
+
f"<regXML>\r\n<regDevSerial>{serial}</regDevSerial>\r\n"
|
|
313
|
+
f"<regDevMacAddr>{mac}</regDevMacAddr>\r\n"
|
|
314
|
+
f"<regDevName>{name}</regDevName>\r\n"
|
|
315
|
+
f"<floorNum>{floor}</floorNum>\r\n</regXML>"
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _build_register(
|
|
320
|
+
host: str, sipnum: str, local_ip: str, expires: int, serial: str, mac: str, port: int = REGISTRAR_PORT
|
|
321
|
+
) -> bytes:
|
|
322
|
+
"""Kind-1 indoor REGISTER per the VDM10 dialect (regXML body, replies are
|
|
323
|
+
routed to the sender's port 5060 by the registrar — see module docstring).
|
|
324
|
+
|
|
325
|
+
The body is sent even for ``Expires: 0``: the registrar's unregister
|
|
326
|
+
delete is ``where serial_no='<s>' or dev_ip='<src ip>'`` and the serial
|
|
327
|
+
is only scraped from regXML — an empty body matches nothing by serial.
|
|
328
|
+
"""
|
|
329
|
+
body = _reg_xml(serial, mac, "vdm10-probe")
|
|
330
|
+
return (
|
|
331
|
+
f"REGISTER sip:{host}:{port} SIP/2.0\r\n"
|
|
332
|
+
f"Via: SIP/2.0/UDP {local_ip}:{SIP_UA_PORT};rport;branch=z9hG4bK{random.randrange(1 << 31)}\r\n"
|
|
333
|
+
f"Max-Forwards: 70\r\n"
|
|
334
|
+
f"Contact: <sip:{sipnum}@{local_ip}:{SIP_UA_PORT}>\r\n"
|
|
335
|
+
f"To: <sip:{sipnum}@{host}:{port}>\r\n"
|
|
336
|
+
f'From: "vdm10-probe"<sip:{sipnum}@{local_ip}>;tag={random.randrange(1 << 31)}\r\n'
|
|
337
|
+
f"Call-ID: {uuid.uuid4().hex}\r\n"
|
|
338
|
+
f"CSeq: 1 REGISTER\r\n"
|
|
339
|
+
f"User-Agent: eXosip/3.6.0\r\n"
|
|
340
|
+
f"Allow: INVITE, ACK, CANCEL, BYE, REFER, INFO, OPTIONS, MESSAGE\r\n"
|
|
341
|
+
f"Expires: {expires}\r\n"
|
|
342
|
+
f"Content-Type: text/xml\r\n"
|
|
343
|
+
f"Content-Length: {len(body.encode())}\r\n\r\n{body}"
|
|
344
|
+
).encode()
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _probe_datagram(sock: socket.socket, timeout: float, expect: str | None = None) -> bytes | None:
|
|
348
|
+
"""Wait for one SIP reply datagram; returns the raw packet or None.
|
|
349
|
+
|
|
350
|
+
``expect`` filters stray datagrams (e.g. a late unregister 200 for the
|
|
351
|
+
previous slot) — the reply's To carries ``sip:<sipnum>@``, so only a
|
|
352
|
+
datagram containing the probed number counts as its answer.
|
|
353
|
+
"""
|
|
354
|
+
deadline = time.monotonic() + timeout
|
|
355
|
+
while (remaining := deadline - time.monotonic()) > 0:
|
|
356
|
+
ready, _, _ = select.select([sock], [], [], remaining)
|
|
357
|
+
if not ready:
|
|
358
|
+
return None
|
|
359
|
+
try:
|
|
360
|
+
data, _ = sock.recvfrom(65535)
|
|
361
|
+
except OSError:
|
|
362
|
+
continue
|
|
363
|
+
if expect is not None and expect.encode() not in data:
|
|
364
|
+
continue
|
|
365
|
+
return data
|
|
366
|
+
return None
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _probe_reply(sock: socket.socket, timeout: float, expect: str | None = None) -> str | None:
|
|
370
|
+
"""Like ``_probe_datagram`` but returns just the SIP status line."""
|
|
371
|
+
data = _probe_datagram(sock, timeout, expect)
|
|
372
|
+
if data is None:
|
|
373
|
+
return None
|
|
374
|
+
return data.split(b"\r\n", 1)[0].decode("utf-8", errors="replace")
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _auth_challenge(data: bytes) -> str | None:
|
|
378
|
+
"""The WWW-/Proxy-Authenticate value from a raw reply, for digest retry."""
|
|
379
|
+
for raw in data.decode("utf-8", errors="replace").split("\r\n"):
|
|
380
|
+
name, _, value = raw.partition(":")
|
|
381
|
+
if name.lower() in ("www-authenticate", "proxy-authenticate"):
|
|
382
|
+
return value.strip()
|
|
383
|
+
return None
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _slot_status(
|
|
387
|
+
sock: socket.socket,
|
|
388
|
+
host: str,
|
|
389
|
+
sipnum: str,
|
|
390
|
+
local_ip: str,
|
|
391
|
+
serial: str,
|
|
392
|
+
mac: str,
|
|
393
|
+
wait: float,
|
|
394
|
+
port: int = REGISTRAR_PORT,
|
|
395
|
+
) -> int | None:
|
|
396
|
+
"""REGISTER ``sipnum`` at ``host:5065``; returns the reply status code.
|
|
397
|
+
|
|
398
|
+
``send_reply`` answers every outcome (200/410/400/500), so silence means
|
|
399
|
+
the packet or its reply was lost — one retry before giving up. A 200
|
|
400
|
+
inserts a dev_reg row; it is removed again with an ``Expires: 0``
|
|
401
|
+
unregister carrying regXML (see ``_build_register``).
|
|
402
|
+
"""
|
|
403
|
+
probe = _build_register(host, sipnum, local_ip, 600, serial, mac, port)
|
|
404
|
+
line = None
|
|
405
|
+
for attempt in range(2):
|
|
406
|
+
sock.sendto(probe, (host, port))
|
|
407
|
+
if line := _probe_reply(sock, wait if attempt == 0 else min(wait, 0.4), sipnum):
|
|
408
|
+
break
|
|
409
|
+
if not line or not line.startswith("SIP/2.0 "):
|
|
410
|
+
return None
|
|
411
|
+
code = int(line.split()[1])
|
|
412
|
+
if code == 200:
|
|
413
|
+
# every insert fires vns_registrarSyncHook — blocking :8102 connects
|
|
414
|
+
# to each extension stall the registrar's SIP loop for seconds and
|
|
415
|
+
# it drops datagrams meanwhile, so retry the unregister past that
|
|
416
|
+
# window (bounded: an unanswered row still expires with its TTL and
|
|
417
|
+
# the next same-IP REGISTER replaces it via the dev_ip dedup match).
|
|
418
|
+
unregister = _build_register(host, sipnum, local_ip, 0, serial, mac, port)
|
|
419
|
+
for _ in range(3):
|
|
420
|
+
sock.sendto(unregister, (host, port))
|
|
421
|
+
if _probe_reply(sock, 1.5, sipnum):
|
|
422
|
+
break
|
|
423
|
+
return code
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def register_status(
|
|
427
|
+
registrar: str,
|
|
428
|
+
sipnum: str,
|
|
429
|
+
serial: str,
|
|
430
|
+
local_ip: str,
|
|
431
|
+
port: int = REGISTRAR_PORT,
|
|
432
|
+
wait: float = 0.8,
|
|
433
|
+
) -> int | None:
|
|
434
|
+
"""Probe-REGISTER ``sipnum`` on ``registrar`` and return the reply code.
|
|
435
|
+
|
|
436
|
+
For the config flow's registration check: ``200`` = the extension can be
|
|
437
|
+
claimed (the probe row is removed again via ``Expires: 0`` inside
|
|
438
|
+
``_slot_status``), ``410`` = held by a different device, ``401``/``403`` =
|
|
439
|
+
the registrar challenged auth, ``None`` = unreachable or :5060 busy.
|
|
440
|
+
``serial`` should be the entry's own so the dedup verdict matches what
|
|
441
|
+
the real registration will see.
|
|
442
|
+
"""
|
|
443
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
444
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
445
|
+
try:
|
|
446
|
+
sock.bind(("0.0.0.0", SIP_UA_PORT))
|
|
447
|
+
except OSError:
|
|
448
|
+
return None
|
|
449
|
+
sock.setblocking(False)
|
|
450
|
+
try:
|
|
451
|
+
mac = f"bc:9b:5e:{random.randrange(1 << 24):06x}"
|
|
452
|
+
return _slot_status(sock, registrar, sipnum, local_ip, serial, mac, wait, port)
|
|
453
|
+
finally:
|
|
454
|
+
sock.close()
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def provider_status(
|
|
458
|
+
host: str,
|
|
459
|
+
port: int,
|
|
460
|
+
user: str,
|
|
461
|
+
password: str,
|
|
462
|
+
domain: str,
|
|
463
|
+
local_ip: str,
|
|
464
|
+
timeout: float = 6.0,
|
|
465
|
+
) -> int | None:
|
|
466
|
+
"""REGISTER ``user`` at a standard SIP server; returns the reply code.
|
|
467
|
+
|
|
468
|
+
For the config flow's provider/trunk check: REGISTER -> one digest retry
|
|
469
|
+
on 401/407 -> status. A ``2xx`` is followed by ``Expires: 0`` cleanup.
|
|
470
|
+
``None`` = unreachable/timeout. Unlike the intercom registrar, providers
|
|
471
|
+
answer on the Via's source port — an ephemeral bind suffices.
|
|
472
|
+
"""
|
|
473
|
+
from metzler.sip.digest import digest_response # lazy: module stays stdlib-only
|
|
474
|
+
|
|
475
|
+
call_id, cseq = uuid.uuid4().hex, 1
|
|
476
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
477
|
+
sock.setblocking(False)
|
|
478
|
+
try:
|
|
479
|
+
sock.bind(("0.0.0.0", 0))
|
|
480
|
+
bind_port = sock.getsockname()[1]
|
|
481
|
+
|
|
482
|
+
def build(expires: int, auth: str | None = None) -> bytes:
|
|
483
|
+
headers = (
|
|
484
|
+
f"REGISTER sip:{domain} SIP/2.0\r\n"
|
|
485
|
+
f"Via: SIP/2.0/UDP {local_ip}:{bind_port};rport;branch=z9hG4bK{random.randrange(1 << 31)}\r\n"
|
|
486
|
+
f"Max-Forwards: 70\r\n"
|
|
487
|
+
f"From: <sip:{user}@{domain}>;tag={random.randrange(1 << 31)}\r\n"
|
|
488
|
+
f"To: <sip:{user}@{domain}>\r\n"
|
|
489
|
+
f"Contact: <sip:{user}@{local_ip}:{bind_port}>\r\n"
|
|
490
|
+
f"Call-ID: {call_id}\r\n"
|
|
491
|
+
f"CSeq: {cseq} REGISTER\r\n"
|
|
492
|
+
f"User-Agent: eXosip/3.6.0\r\n"
|
|
493
|
+
f"Expires: {expires}\r\n"
|
|
494
|
+
f"Content-Length: 0\r\n"
|
|
495
|
+
)
|
|
496
|
+
if auth:
|
|
497
|
+
headers += f"Authorization: {auth}\r\n"
|
|
498
|
+
return f"{headers}\r\n".encode()
|
|
499
|
+
|
|
500
|
+
deadline = time.monotonic() + timeout
|
|
501
|
+
sock.sendto(build(600), (host, port))
|
|
502
|
+
code = None
|
|
503
|
+
for attempt in range(3):
|
|
504
|
+
data = _probe_datagram(sock, max(0.1, deadline - time.monotonic()), expect=call_id)
|
|
505
|
+
if data is None:
|
|
506
|
+
return None
|
|
507
|
+
line = data.split(b"\r\n", 1)[0].decode("utf-8", errors="replace")
|
|
508
|
+
if not line.startswith("SIP/2.0 "):
|
|
509
|
+
return None
|
|
510
|
+
code = int(line.split()[1])
|
|
511
|
+
if code not in (401, 407) or attempt == 2:
|
|
512
|
+
break
|
|
513
|
+
hdr = _auth_challenge(data)
|
|
514
|
+
if hdr is None:
|
|
515
|
+
break
|
|
516
|
+
cseq += 1
|
|
517
|
+
auth = digest_response(hdr, "REGISTER", f"sip:{domain}", user, password)
|
|
518
|
+
sock.sendto(build(600, auth), (host, port))
|
|
519
|
+
if code is not None and 200 <= code < 300:
|
|
520
|
+
cseq += 1
|
|
521
|
+
sock.sendto(build(0), (host, port))
|
|
522
|
+
_probe_datagram(sock, 1.0, expect=call_id)
|
|
523
|
+
return code
|
|
524
|
+
finally:
|
|
525
|
+
sock.close()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Media paths: G.711, RTP relay, SRTP, the intercom RTSP channel and local headset audio."""
|
metzler/media/g711.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""G.711 A-law / mu-law codec tables (stdlib only)."""
|
|
2
|
+
|
|
3
|
+
import struct
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _alaw_decode_table():
|
|
7
|
+
t = []
|
|
8
|
+
for i in range(256):
|
|
9
|
+
a = i ^ 0x55
|
|
10
|
+
v = (a & 0x0F) << 4
|
|
11
|
+
seg = (a & 0x70) >> 4
|
|
12
|
+
v = v + 8 if seg == 0 else (v + 0x108) << (seg - 1) if seg > 1 else v + 0x108
|
|
13
|
+
t.append(v if a & 0x80 else -v)
|
|
14
|
+
return t
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
ALAW_DEC = _alaw_decode_table()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def alaw_to_pcm(alaw):
|
|
21
|
+
return b"".join(struct.pack("<h", ALAW_DEC[b]) for b in alaw)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _ulaw_decode_table():
|
|
25
|
+
t = [0] * 256
|
|
26
|
+
for i in range(256):
|
|
27
|
+
u = ~i & 0xFF
|
|
28
|
+
s = (((u & 0x0F) << 3) + 0x84) << ((u >> 4) & 7)
|
|
29
|
+
s -= 0x84
|
|
30
|
+
t[i] = -s if (u & 0x80) else s
|
|
31
|
+
return t
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
ULAW_DEC = _ulaw_decode_table()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def ulaw_encode_sample(s):
|
|
38
|
+
if s < 0:
|
|
39
|
+
sign, s = 0x80, -s
|
|
40
|
+
else:
|
|
41
|
+
sign = 0
|
|
42
|
+
s = min(s, 32635)
|
|
43
|
+
s += 0x84
|
|
44
|
+
exp, mask = 7, 0x4000
|
|
45
|
+
while exp > 0 and not (s & mask):
|
|
46
|
+
mask >>= 1
|
|
47
|
+
exp -= 1
|
|
48
|
+
return ~(sign | (exp << 4) | ((s >> (exp + 3)) & 0x0F)) & 0xFF
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
ULAW_ENC = bytes(ulaw_encode_sample(i - 65536 if i >= 32768 else i) for i in range(65536))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def ulaw_to_pcm(ulaw):
|
|
55
|
+
return b"".join(struct.pack("<h", ULAW_DEC[b]) for b in ulaw)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def pcm_to_ulaw(pcm):
|
|
59
|
+
return bytes(ULAW_ENC[w & 0xFFFF] for (w,) in struct.iter_unpack("<h", pcm))
|