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/provider.py ADDED
@@ -0,0 +1,500 @@
1
+ """Standard-SIP trunk to a hosted provider (sip.linphone.org) or a PBX (Asterisk)."""
2
+
3
+ import logging
4
+ import queue
5
+ import re
6
+ import socket
7
+ import threading
8
+ import time
9
+ from types import SimpleNamespace
10
+
11
+ from metzler.media.srtp import SrtpSession
12
+ from metzler.sip.digest import digest_response
13
+ from metzler.sip.message import UA, Packet, branch, call_id, tag, uri_of, userpart
14
+
15
+ log = logging.getLogger("indoor")
16
+
17
+
18
+ class SipProvider:
19
+ """Standard-SIP trunk to a hosted provider (e.g. sip.linphone.org).
20
+
21
+ Everything the public-SIP side needs lives here so the station only ever
22
+ delegates: REGISTER (digest auth, NAT learn via the echoed Via), one
23
+ outbound INVITE leg per bridged Call, and ACK/CANCEL/BYE for that leg.
24
+
25
+ Packet flow:
26
+ station listener -> is_reg_response() -> reg_queue (REGISTER replies)
27
+ -> calls[Call-ID] -> handle_response() (INVITE replies)
28
+ on_invite bridge -> invite(call) (offer built by offer_sdp())
29
+ provider 200 OK -> station.provider_answered() -> ack()
30
+ teardown -> cancel() / bye()
31
+
32
+ The provider object sends on the station's UDP socket (shared source port)
33
+ via the `st` back-reference; it owns no sockets of its own."""
34
+
35
+ FORK_TTL = 600 # s a forked-back Call-ID stays recognisable in own_ids
36
+
37
+ def __init__(self, st, o):
38
+ self.st, self.o = st, o
39
+ self.label = "provider"
40
+ self.proxy = (o.sip_host, o.sip_port)
41
+ self.reg_call_id = call_id()
42
+ self.reg_cseq = 1
43
+ self.reg_queue = queue.Queue()
44
+ self.registered = threading.Event()
45
+ self.public_ip = None # Via received= learned from the proxy
46
+ self.public_port = None # Via rport= (our NAT'ed source port)
47
+ self.calls = {} # provider-leg Call-ID -> Call
48
+ self.own_ids = {} # Call-ID we originated -> added-at (loop guard)
49
+ try:
50
+ self.proxy_ip = socket.gethostbyname(o.sip_host)
51
+ except OSError:
52
+ self.proxy_ip = None
53
+ # SIP identity: the account name, or - for a credential-less PBX trunk
54
+ # (e.g. Asterisk with IP auth) - the station's own extension number
55
+ self.user = o.sip_user or o.username
56
+ # station number -> display name (--sip-names) for _from_header {name}
57
+ self.names = {s[0]: s[1] for s in (p.split("=", 1) for p in (o.sip_names or "").split(",")) if len(s) == 2}
58
+
59
+ def needs_register(self):
60
+ """hosted providers need REGISTER; an IP-authenticated PBX trunk does not"""
61
+ return bool(self.o.sip_user and self.o.sip_pass)
62
+
63
+ # -- identity -------------------------------------------------------------
64
+
65
+ def sdp_ip(self):
66
+ """address we advertise in provider-leg SDP/Contact (public if known)"""
67
+ return self.public_ip or self.o.local_ip
68
+
69
+ def sdp_port(self):
70
+ return self.public_port or self.st.bind_port
71
+
72
+ def _base(self, method, uri, frm, br=None):
73
+ p = Packet()
74
+ p.status_line = f"{method} {uri} SIP/2.0"
75
+ p.set("Via", f"SIP/2.0/UDP {self.o.local_ip}:{self.st.bind_port};rport;branch={br or branch()}")
76
+ p.set("Max-Forwards", "70")
77
+ p.set("From", frm)
78
+ p.set("User-Agent", UA)
79
+ return p
80
+
81
+ def owns(self, call_id):
82
+ """did we ever originate this Call-ID? (forked-call loop guard - kept
83
+ a while after the call ends so late fork retransmits still don't look
84
+ like new calls; lazily pruned so it cannot grow forever)"""
85
+ now = time.time()
86
+ for cid in [c for c, ts in self.own_ids.items() if now - ts > self.FORK_TTL]:
87
+ del self.own_ids[cid]
88
+ return call_id in self.own_ids
89
+
90
+ def is_provider_addr(self, addr):
91
+ """request came from the provider proxy/PBX (not from an intercom
92
+ station); ip+port, so a PBX sharing a host with other SIP gear works"""
93
+ return (addr[0], addr[1]) == (self.proxy_ip, self.proxy[1])
94
+
95
+ def is_reg_response(self, pkt):
96
+ return pkt.get("Call-ID") == self.reg_call_id
97
+
98
+ # -- REGISTER -------------------------------------------------------------
99
+
100
+ def _register_pkt(self, auth=None):
101
+ p = self._base(
102
+ "REGISTER",
103
+ f"sip:{self.o.sip_domain}",
104
+ f"<sip:{self.o.sip_user}@{self.o.sip_domain}>;tag={self.st.local_tag}",
105
+ )
106
+ p.set("To", f"<sip:{self.o.sip_user}@{self.o.sip_domain}>")
107
+ p.set("Contact", f"<sip:{self.o.sip_user}@{self.o.local_ip}:{self.st.bind_port}>")
108
+ p.set("Call-ID", self.reg_call_id)
109
+ p.set("CSeq", f"{self.reg_cseq} REGISTER")
110
+ p.set("Expires", "600")
111
+ if auth:
112
+ p.set("Authorization", auth)
113
+ return p
114
+
115
+ def register_loop(self):
116
+ """keeps the account registered: REGISTER -> 401 digest retry -> 200.
117
+ Every response's Via carries received=/rport= = our public identity."""
118
+ while self.st.running:
119
+ try:
120
+ self._register_once()
121
+ except (RuntimeError, OSError) as e:
122
+ log.warning("%s register failed: %s", self.label, e)
123
+ self.registered.clear()
124
+ time.sleep(240)
125
+
126
+ def _register_once(self):
127
+ """one REGISTER round: unauthed -> <=2 digest retries -> 200."""
128
+ while True: # drain stale replies
129
+ try:
130
+ self.reg_queue.get_nowait()
131
+ except queue.Empty:
132
+ break
133
+ self.st.send(self._register_pkt(), self.proxy)
134
+ for attempt in range(3):
135
+ resp = self._wait_reply(time.time() + 10)
136
+ if resp is None:
137
+ return log.warning("%s register timed out (next retry in 30s)", self.label)
138
+ self._learn_public(resp)
139
+ if resp.status_line.startswith("SIP/2.0 2"):
140
+ return self._mark_registered()
141
+ if resp.status_line.startswith(("SIP/2.0 401", "SIP/2.0 407")):
142
+ if attempt == 2:
143
+ return log.warning("%s auth failed (check sip password)", self.label)
144
+ self.reg_cseq += 1
145
+ self.st.send(self._register_pkt(self._reg_auth(resp)), self.proxy)
146
+ elif re.match(r"SIP/2\.0 [456]", resp.status_line):
147
+ return log.warning("%s register rejected: %s", self.label, resp.status_line)
148
+
149
+ def _wait_reply(self, deadline):
150
+ try:
151
+ return self.reg_queue.get(timeout=max(0.1, deadline - time.time()))
152
+ except queue.Empty:
153
+ return None
154
+
155
+ def _reg_auth(self, resp):
156
+ hdr = resp.get("WWW-Authenticate") or resp.get("Proxy-Authenticate")
157
+ return digest_response(hdr, "REGISTER", f"sip:{self.o.sip_domain}", self.o.sip_user, self.o.sip_pass)
158
+
159
+ def _mark_registered(self):
160
+ if not self.registered.is_set():
161
+ log.info(
162
+ "%s REGISTERED at %s:%d as %s@%s (public %s:%s)",
163
+ self.label,
164
+ *self.proxy,
165
+ self.o.sip_user,
166
+ self.o.sip_domain,
167
+ self.public_ip,
168
+ self.public_port,
169
+ )
170
+ self.registered.set()
171
+
172
+ def unregister(self):
173
+ try:
174
+ p = self._register_pkt()
175
+ p.set("Expires", "0", replace=True)
176
+ self.st.send(p, self.proxy)
177
+ except OSError:
178
+ pass
179
+
180
+ def _learn_public(self, pkt):
181
+ """NAT detection without STUN: the proxy echoes our Via back with
182
+ received=<ip>/rport=<port> - that is our public identity for SDP."""
183
+ via = pkt.get("Via") or ""
184
+ m = re.search(r"received=([0-9.]+)", via)
185
+ if m:
186
+ self.public_ip = m.group(1)
187
+ m = re.search(r"rport=(\d+)", via)
188
+ if m:
189
+ self.public_port = int(m.group(1))
190
+
191
+ # -- outbound INVITE leg --------------------------------------------------
192
+
193
+ def offer_sdp(self, call):
194
+ """provider leg offer: PCMU audio (intercom calls) or audio + H264
195
+ video (door calls). With --sip-srtp each m= line is RTP/SAVP carrying
196
+ its own SDES key; the media objects keep the matching SrtpSession."""
197
+ if call.kind == "intercom":
198
+ streams = [("audio", call.media)]
199
+ if call.media.video: # door call: door's RTSP H264
200
+ streams.append(("video", call.media.video))
201
+ else:
202
+ streams = [("audio", call.audio), ("video", call.video)]
203
+ ip = self.sdp_ip()
204
+ body = f"v=0\r\no=- 0 0 IN IP4 {ip}\r\ns=Talk session\r\nc=IN IP4 {ip}\r\nt=0 0\r\n"
205
+ for kind, media in streams:
206
+ media.srtp = SrtpSession() if self.o.sip_srtp and not call.prov_plain else None
207
+ body += self._media_block(kind, media)
208
+ return body
209
+
210
+ def answer_sdp(self, offer, media):
211
+ """200 OK body for an inbound provider call: accept the first audio
212
+ m= line (SRTP when the offer was SAVP and we bound a session),
213
+ reject every other stream (port 0, offered proto kept)"""
214
+ ip = self.sdp_ip()
215
+ body = f"v=0\r\no=- 0 0 IN IP4 {ip}\r\ns=Talk session\r\nc=IN IP4 {ip}\r\nt=0 0\r\n"
216
+ answered = False
217
+ for m in offer["media"]:
218
+ if m["type"] == "audio" and m["port"] and not answered:
219
+ body += self._media_block("audio", media)
220
+ answered = True
221
+ else:
222
+ body += f"m={m['type']} 0 {m.get('proto') or 'RTP/AVP'} {' '.join(m['formats']) or '0'}\r\n"
223
+ return body
224
+
225
+ @staticmethod
226
+ def _media_block(kind, media):
227
+ port = media.rtp_port
228
+ proto = "RTP/SAVP" if media.srtp else "RTP/AVP"
229
+ crypto = media.srtp.crypto_attr() if media.srtp else ""
230
+ if kind == "audio":
231
+ return (
232
+ f"m=audio {port} {proto} 0 101\r\n{crypto}"
233
+ "a=rtpmap:0 PCMU/8000\r\na=rtpmap:101 telephone-event/8000\r\n"
234
+ "a=fmtp:101 0-16\r\na=sendrecv\r\n"
235
+ )
236
+ return (
237
+ f"m=video {port} {proto} 96\r\n{crypto}a=rtpmap:96 H264/90000\r\n"
238
+ "a=fmtp:96 packetization-mode=1;profile-level-id=4D001E\r\na=sendrecv\r\n"
239
+ )
240
+
241
+ @staticmethod
242
+ def bind_srtp(media, answer_media):
243
+ """take the peer's key from its answered m= line; a plain RTP/AVP
244
+ answer drops SRTP for that stream. Returns 'srtp'|'rtp' for logging."""
245
+ if media.srtp and answer_media and media.srtp.accept_answer(answer_media):
246
+ return "srtp"
247
+ media.srtp = None
248
+ return "rtp"
249
+
250
+ def _caller_name(self, call):
251
+ """the calling station's --sip-names entry, else its number"""
252
+ num = userpart(call.invite.get("From") or "") if call else ""
253
+ return self.names.get(num, num) or None
254
+
255
+ def _from_header(self, call):
256
+ """From for the provider INVITE leg: --sip-from sets the DISPLAY NAME
257
+ ({num} = calling station's number, {name} = its --sip-names entry)
258
+ while the URI stays our account - providers answer 403 for a foreign
259
+ From user. A full 'Name <sip:u@h>' or 'u@h' spec is sent verbatim
260
+ (for trunks that allow arbitrary caller IDs)."""
261
+ spec = (self.o.sip_from or "").strip()
262
+ num = userpart(call.invite.get("From") or "") if call else ""
263
+ name = self.names.get(num, num)
264
+ spec = spec.replace("{num}", num).replace("{name}", name)
265
+ if "<" in spec or "sip:" in spec:
266
+ return f"{spec};tag={tag()}"
267
+ if "@" in spec:
268
+ user, _, dom = spec.partition("@")
269
+ return f'"{user}" <sip:{user}@{dom}>;tag={tag()}'
270
+ return f'"{spec or self.o.name}" <sip:{self.user}@{self.o.sip_domain}>;tag={tag()}'
271
+
272
+ def invite(self, call):
273
+ """send the outbound INVITE for a bridged call; registers the leg so
274
+ listener() can route its replies via calls[prov_call_id]"""
275
+ self.calls[call.prov_call_id] = call
276
+ self.own_ids[call.prov_call_id] = time.time()
277
+ self.st.send(self._invite_pkt(call), self.proxy)
278
+ call.state = "bridging"
279
+
280
+ def _invite_pkt(self, call, auth=None, auth_name="Authorization"):
281
+ uri = self.o.sip_target
282
+ call.prov_branch = branch()
283
+ call.prov_cseq += 1
284
+ p = self._base("INVITE", uri, self._from_header(call), call.prov_branch)
285
+ p.set("Contact", f"<sip:{self.user}@{self.sdp_ip()}:{self.sdp_port()}>")
286
+ p.set("To", f"<{uri}>")
287
+ p.set("Call-ID", call.prov_call_id)
288
+ p.set("CSeq", f"{call.prov_cseq} INVITE")
289
+ subj = self._caller_name(call)
290
+ if subj:
291
+ p.set("Subject", subj) # linphone renders the subject too
292
+ p.set("Allow", "INVITE, ACK, CANCEL, BYE, REFER, INFO, OPTIONS, MESSAGE")
293
+ p.set("Content-Type", "application/sdp")
294
+ if auth:
295
+ p.set(auth_name, auth)
296
+ p.body = self.offer_sdp(call)
297
+ call.prov_from = p.get("From")
298
+ call.prov_uri = uri
299
+ return p
300
+
301
+ def _ack_failure(self, call, resp):
302
+ """a non-2xx final response to INVITE must be ACK'ed (same branch,
303
+ same CSeq number) or the proxy retransmits it ~7 times"""
304
+ p = self._base("ACK", call.prov_uri or self.o.sip_target, resp.get("From"), call.prov_branch)
305
+ p.set("To", resp.get("To"))
306
+ p.set("Call-ID", call.prov_call_id)
307
+ p.set("CSeq", f"{call.prov_cseq} ACK")
308
+ self.st.send(p, self.proxy)
309
+
310
+ def handle_response(self, call, resp):
311
+ """dispatch one response on the provider INVITE leg"""
312
+ code = int(resp.status_line.split()[1])
313
+ self._learn_public(resp)
314
+ if code in (401, 407): # digest challenge
315
+ self._ack_failure(call, resp) # stop the retransmits
316
+ call.prov_auths += 1
317
+ if call.prov_auths > 2:
318
+ log.warning("provider INVITE auth failed - busy to indoor caller")
319
+ return "fail"
320
+ # 407 needs Proxy-Authorization (header + challenge); 401 uses Authorization
321
+ hdr = resp.get("Proxy-Authenticate" if code == 407 else "WWW-Authenticate")
322
+ auth = digest_response(hdr, "INVITE", call.prov_uri, self.o.sip_user, self.o.sip_pass)
323
+ name = "Proxy-Authorization" if code == 407 else "Authorization"
324
+ self.st.send(self._invite_pkt(call, auth, name), self.proxy)
325
+ return "auth"
326
+ if code < 200:
327
+ # 18x carrying SDP = early media: the callee's media address is
328
+ # known, door video can start flowing before the answer
329
+ return "early" if "m=" in resp.body else "ringing"
330
+ if 200 <= code < 300:
331
+ return "answered"
332
+ self._ack_failure(call, resp) # >=300 final: ACK to stop retransmits
333
+ if code == 488 and self.o.sip_srtp and not call.prov_plain:
334
+ # peer without SRTP support (e.g. a stock Asterisk) - re-offer plain RTP once
335
+ log.info("provider refused the SRTP offer (488) - retrying with plain RTP")
336
+ call.prov_plain = True
337
+ self.st.send(self._invite_pkt(call), self.proxy)
338
+ return "auth"
339
+ return "fail"
340
+
341
+ def ack(self, call, resp):
342
+ """ACK the provider 200 OK; To/From echo the response, target = its Contact"""
343
+ to = resp.get("To")
344
+ contact = resp.get("Contact") or f"<{self.o.sip_target}>"
345
+ uri = uri_of(contact)
346
+ call.prov_to, call.prov_uri = to, uri
347
+ p = self._base("ACK", uri, resp.get("From"))
348
+ p.set("Contact", self.st.contact())
349
+ p.set("To", to)
350
+ p.set("Call-ID", call.prov_call_id)
351
+ p.set("CSeq", "1 ACK")
352
+ self.st.send(p, self.proxy)
353
+
354
+ # -- leg teardown ---------------------------------------------------------
355
+
356
+ def _leg_pkt(self, call, method, cseq):
357
+ uri = call.prov_uri or self.o.sip_target
358
+ p = self._base(method, uri, call.prov_from)
359
+ p.set("To", call.prov_to if method == "BYE" and call.prov_to else f"<{uri}>")
360
+ p.set("Call-ID", call.prov_call_id)
361
+ p.set("CSeq", cseq)
362
+ return p
363
+
364
+ def cancel(self, call):
365
+ """CANCEL only matches the INVITE transaction when it echoes the live
366
+ INVITE's Via branch and CSeq number (RFC 3261 9.1); a fresh branch is
367
+ a new transaction the proxy doesn't know - 481, app keeps ringing"""
368
+ try:
369
+ uri = self.o.sip_target # must equal the INVITE's RURI
370
+ p = self._base("CANCEL", uri, call.prov_from, call.prov_branch)
371
+ p.set("To", f"<{uri}>")
372
+ p.set("Call-ID", call.prov_call_id)
373
+ p.set("CSeq", f"{call.prov_cseq} CANCEL")
374
+ self.st.send(p, self.proxy)
375
+ except OSError:
376
+ pass
377
+
378
+ def bye(self, call):
379
+ try:
380
+ self.st.send(self._leg_pkt(call, "BYE", "2 BYE"), self.proxy)
381
+ except OSError:
382
+ pass
383
+
384
+
385
+ class FritzTrunk(SipProvider):
386
+ """A second SIP account on the same socket: --fritz makes the station
387
+ REGISTER as an IP phone at a Fritz!Box. Inbound fritz calls bridge to
388
+ --inbound-target like provider app calls. Every bridged call ALSO rings
389
+ --fritz-call-button in parallel with the provider app (first answer wins).
390
+
391
+ The racing leg keeps its own state in call.fritz_leg - the call's
392
+ prov_* fields belong to the provider leg while both race; the winner
393
+ gets promoted into them."""
394
+
395
+ def __init__(self, st, o):
396
+ fo = SimpleNamespace(**vars(o))
397
+ fo.sip_host, fo.sip_port = o.fritz_host, o.fritz_port
398
+ fo.sip_domain = o.fritz_domain
399
+ fo.sip_user, fo.sip_pass = o.fritz_user, o.fritz_pass
400
+ fo.sip_target, fo.sip_from = "", ""
401
+ fo.sip_srtp = False # Fritz!Box IP phones talk plain RTP
402
+ super().__init__(st, fo)
403
+ self.label = "fritz"
404
+
405
+ # -- racing fritzfon leg (state: call.fritz_leg dict) --------------------
406
+
407
+ def invite(self, call):
408
+ """ring --fritz-call-button in parallel with the provider leg; the box
409
+ forks this back at our registered contact, so the Call-ID goes into
410
+ own_ids like a provider leg's"""
411
+ call.fritz_leg = {
412
+ "cid": call_id(),
413
+ "cseq": 0,
414
+ "branch": None,
415
+ "from": None,
416
+ "uri": self.o.fritz_target,
417
+ "auths": 0,
418
+ }
419
+ leg = call.fritz_leg
420
+ self.calls[leg["cid"]] = call
421
+ self.own_ids[leg["cid"]] = time.time()
422
+ self.st.send(self._fritz_invite_pkt(call, leg), self.proxy)
423
+
424
+ def _fritz_invite_pkt(self, call, leg, auth=None, auth_name="Authorization"):
425
+ """audio-only RTP/AVP offer for the fritzfon (no video, no SRTP);
426
+ From user stays the account, display name + Subject carry the
427
+ calling station like on the provider leg"""
428
+ leg["cseq"] += 1
429
+ leg["branch"] = branch()
430
+ num = userpart(call.invite.get("From") or "")
431
+ name = self.names.get(num, num) or self.o.name
432
+ p = self._base(
433
+ "INVITE", leg["uri"], f'"{name}" <sip:{self.o.sip_user}@{self.o.sip_domain}>;tag={tag()}', leg["branch"]
434
+ )
435
+ p.set("Contact", f"<sip:{self.o.sip_user}@{self.sdp_ip()}:{self.sdp_port()}>")
436
+ p.set("To", f"<{leg['uri']}>")
437
+ p.set("Call-ID", leg["cid"])
438
+ p.set("CSeq", f"{leg['cseq']} INVITE")
439
+ p.set("Subject", name)
440
+ p.set("Content-Type", "application/sdp")
441
+ if auth:
442
+ p.set(auth_name, auth)
443
+ media = call.media if call.kind == "intercom" else call.audio
444
+ ip = self.sdp_ip()
445
+ p.body = (
446
+ f"v=0\r\no=- 0 0 IN IP4 {ip}\r\ns=Talk session\r\n"
447
+ f"c=IN IP4 {ip}\r\nt=0 0\r\n"
448
+ f"m=audio {media.rtp_port} RTP/AVP 0 101\r\n"
449
+ "a=rtpmap:0 PCMU/8000\r\na=rtpmap:101 telephone-event/8000\r\n"
450
+ "a=fmtp:101 0-16\r\na=sendrecv\r\n"
451
+ )
452
+ leg["from"] = p.get("From")
453
+ return p
454
+
455
+ def _ack_leg_failure(self, leg, resp):
456
+ """non-2xx final responses need an ACK on the same branch"""
457
+ p = self._base("ACK", leg["uri"], resp.get("From"), leg["branch"])
458
+ p.set("To", resp.get("To"))
459
+ p.set("Call-ID", leg["cid"])
460
+ p.set("CSeq", f"{leg['cseq']} ACK")
461
+ self.st.send(p, self.proxy)
462
+
463
+ def handle_response(self, call, resp):
464
+ """dispatch one response on the racing fritz leg (early media is
465
+ ignored - a fritzfon rings, it does not stream to the door early)"""
466
+ code = int(resp.status_line.split()[1])
467
+ leg = call.fritz_leg
468
+ if code in (401, 407):
469
+ self._ack_leg_failure(leg, resp)
470
+ leg["auths"] += 1
471
+ if leg["auths"] > 2:
472
+ log.warning("fritz INVITE auth failed")
473
+ return "fail"
474
+ hdr = resp.get("Proxy-Authenticate" if code == 407 else "WWW-Authenticate")
475
+ auth = digest_response(hdr, "INVITE", leg["uri"], self.o.sip_user, self.o.sip_pass)
476
+ name = "Proxy-Authorization" if code == 407 else "Authorization"
477
+ self.st.send(self._fritz_invite_pkt(call, leg, auth, name), self.proxy)
478
+ return "auth"
479
+ if code < 200:
480
+ return "ringing"
481
+ if 200 <= code < 300:
482
+ return "answered"
483
+ self._ack_leg_failure(leg, resp)
484
+ return "fail"
485
+
486
+ def cancel_leg(self, call):
487
+ """CANCEL the still-racing fritz leg (echoes its branch/CSeq like the
488
+ provider CANCEL) and drop it from the routing dict"""
489
+ leg = call.fritz_leg
490
+ if not leg:
491
+ return
492
+ try:
493
+ p = self._base("CANCEL", leg["uri"], leg["from"], leg["branch"])
494
+ p.set("To", f"<{leg['uri']}>")
495
+ p.set("Call-ID", leg["cid"])
496
+ p.set("CSeq", f"{leg['cseq']} CANCEL")
497
+ self.st.send(p, self.proxy)
498
+ except OSError:
499
+ pass
500
+ self.calls.pop(leg["cid"], None)
metzler/py.typed ADDED
File without changes
@@ -0,0 +1 @@
1
+ """SIP building blocks: message model, Digest auth, SDP (incl. the hicore private attributes)."""
metzler/sip/digest.py ADDED
@@ -0,0 +1,45 @@
1
+ """SIP Digest authentication (RFC 2617/7616/8760: MD5 and SHA-256, qop=auth)."""
2
+
3
+ import hashlib
4
+ import random
5
+ import re
6
+
7
+
8
+ def md5(s):
9
+ return hashlib.md5(s.encode()).hexdigest()
10
+
11
+
12
+ def digest_response(auth_hdr, method, uri, username, password):
13
+ """RFC 2617/8760 digest - honors the server's algorithm= (MD5 or SHA-256).
14
+ Params may be quoted or bare (linphone sends algorithm=SHA-256 unquoted)."""
15
+
16
+ def f(n):
17
+ m = re.search(n + r'="(.*?)"', auth_hdr) or re.search(n + r"=([^,\s]+)", auth_hdr)
18
+ return m.group(1) if m else ""
19
+
20
+ realm, nonce, opaque = f("realm"), f("nonce"), f("opaque")
21
+ algo = (f("algorithm") or "MD5").upper()
22
+ H = (lambda s: hashlib.sha256(s.encode()).hexdigest()) if algo.startswith("SHA-256") else md5
23
+ ha1 = H(f"{username}:{realm}:{password}")
24
+ if algo.endswith("-SESS"):
25
+ c0 = f"{random.getrandbits(64):016x}"
26
+ ha1 = H(f"{ha1}:{nonce}:{c0}")
27
+ ha2 = H(f"{method}:{uri}")
28
+ if "qop=" in auth_hdr:
29
+ qop = f("qop").split(",")[0].strip() or "auth"
30
+ nc, cnonce = "00000001", f"{random.getrandbits(128):032x}"
31
+ resp = H(f"{ha1}:{nonce}:{nc}:{cnonce}:{qop}:{ha2}")
32
+ out = (
33
+ f'Digest username="{username}",realm="{realm}",nonce="{nonce}",'
34
+ f'uri="{uri}",response="{resp}",cnonce="{cnonce}",nc={nc},'
35
+ f"qop={qop},algorithm={algo}"
36
+ )
37
+ else:
38
+ resp = H(f"{ha1}:{nonce}:{ha2}")
39
+ out = (
40
+ f'Digest username="{username}",realm="{realm}",nonce="{nonce}",'
41
+ f'uri="{uri}",response="{resp}",algorithm={algo}'
42
+ )
43
+ if opaque:
44
+ out += f',opaque="{opaque}"'
45
+ return out
metzler/sip/message.py ADDED
@@ -0,0 +1,81 @@
1
+ """SIP message model: header list + body, and the random ids/tags/branches."""
2
+
3
+ import random
4
+ import re
5
+
6
+ UA = "eXosip/3.6.0"
7
+
8
+
9
+ class Packet(list):
10
+ def __init__(self):
11
+ super().__init__()
12
+ self.status_line = ""
13
+ self.body = ""
14
+
15
+ def set(self, k, v, replace=False):
16
+ if replace:
17
+ for i, (kk, _) in enumerate(self):
18
+ if kk == k:
19
+ self[i] = (k, v)
20
+ return
21
+ self.append((k, v))
22
+
23
+ def get(self, k):
24
+ for kk, v in self:
25
+ if kk.lower() == k.lower():
26
+ return v
27
+ return None
28
+
29
+ def get_all(self, k):
30
+ return [v for kk, v in self if kk.lower() == k.lower()]
31
+
32
+ @staticmethod
33
+ def parse(data):
34
+ p = Packet()
35
+ lines = data.replace("\r\n", "\n").split("\n")
36
+ p.status_line = lines[0].strip()
37
+ _i = 1
38
+ for _i, line in enumerate(lines[1:], 1):
39
+ if not line.strip():
40
+ break
41
+ if ":" in line:
42
+ k, v = line.split(":", 1)
43
+ p.set(k.strip(), v.strip())
44
+ p.body = "\n".join(lines[_i + 1 :])
45
+ return p
46
+
47
+ def __str__(self):
48
+ out = self.status_line + "\r\n"
49
+ out += "".join(f"{k}: {v}\r\n" for k, v in self)
50
+ return out + "\r\n" + self.body
51
+
52
+
53
+ def sip_uri(target, domain):
54
+ """'6000' (Asterisk extension) or 'user@host' -> full sip: URI"""
55
+ if not target or target.startswith(("sip:", "sips:")):
56
+ return target
57
+ return f"sip:{target}" if "@" in target else f"sip:{target}@{domain}"
58
+
59
+
60
+ def uri_of(header):
61
+ """'"Name" <sip:x@y>;tag=1' (Contact/To/From value) -> 'sip:x@y'"""
62
+ return (re.findall(r"<(.*?)>", header) or [header.strip()])[0]
63
+
64
+
65
+ def userpart(header):
66
+ """'"Name" <sip:10000000003@1.2.3.4>;tag=x' -> '10000000003'"""
67
+ uri = uri_of(header).split(":", 1)
68
+ uri = uri[1] if len(uri) > 1 else uri[0]
69
+ return uri.split("@")[0].split(";")[0]
70
+
71
+
72
+ def call_id():
73
+ return "".join(random.choice("0123456789") for _ in range(10))
74
+
75
+
76
+ def tag():
77
+ return f"{random.getrandbits(32):08x}"
78
+
79
+
80
+ def branch():
81
+ return f"z9hG4bK{random.getrandbits(32):08x}"