sipua 0.0.1__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.
sipua/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ #
2
+ # Copyright (C) Spacinov SAS
3
+ # Distributed under the 2-clause BSD license
4
+ #
5
+
6
+ import importlib.metadata
7
+
8
+ from .transport import TransportLayer
9
+
10
+ __all__ = [
11
+ "TransportLayer",
12
+ ]
13
+ __version__ = importlib.metadata.version("sipua")
sipua/py.typed ADDED
@@ -0,0 +1 @@
1
+ Marker
sipua/transport.py ADDED
@@ -0,0 +1,327 @@
1
+ #
2
+ # Copyright (C) Spacinov SAS
3
+ # Distributed under the 2-clause BSD license
4
+ #
5
+
6
+ import abc
7
+ import asyncio
8
+ import dataclasses
9
+ import ipaddress
10
+ import logging
11
+ import socket
12
+ import typing
13
+
14
+ import sipmessage
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ MessageHandler = typing.Callable[[sipmessage.Message], typing.Awaitable[None]]
19
+
20
+ AUTO_HOST = "auto"
21
+ AUTO_TRANSPORT = "AUTO"
22
+
23
+
24
+ @dataclasses.dataclass
25
+ class TransportAddress:
26
+ protocol: str
27
+ host: str
28
+ port: int
29
+
30
+
31
+ class BaseTransport(abc.ABC):
32
+ is_reliable: bool
33
+ uri_transport: str
34
+ via_host: str
35
+ via_port: int | None = None
36
+ via_transport: str
37
+
38
+ @abc.abstractmethod
39
+ async def close(self) -> None: ... # pragma: no cover
40
+
41
+ @abc.abstractmethod
42
+ async def send_message(
43
+ self, message: sipmessage.Message, destination: TransportAddress
44
+ ) -> None: ... # pragma: no cover
45
+
46
+
47
+ def get_default_port(protocol: str) -> int:
48
+ """
49
+ Return the default port for the given protocol.
50
+ """
51
+ if protocol in ("ws", "wss"):
52
+ return 0
53
+ elif protocol == "tls":
54
+ return 5061
55
+ else:
56
+ return 5060
57
+
58
+
59
+ async def get_transport_destination(message: sipmessage.Message) -> TransportAddress:
60
+ """
61
+ Determine the protocol, host and port to which a message should be sent.
62
+ """
63
+ protocol: str
64
+ host: str
65
+ port: int
66
+
67
+ if isinstance(message, sipmessage.Request):
68
+ # For requests, use the `Request-URI` or the first `Route` header.
69
+ #
70
+ # https://datatracker.ietf.org/doc/html/rfc3261#section-8.1.2
71
+ route_set = message.route
72
+ if route_set and "lr" in route_set[0].uri.parameters:
73
+ # Loose routing, use the first `Route` header.
74
+ uri = route_set[0].uri
75
+ else:
76
+ # Strict routing or empty route set, use the `Request-URI`.
77
+ uri = message.uri
78
+
79
+ # Check whether the target is a numeric IP address.
80
+ try:
81
+ ipaddress.ip_address(uri.host)
82
+ except ValueError:
83
+ is_ip_address = False
84
+ else:
85
+ is_ip_address = True
86
+
87
+ # Select a transport protocol.
88
+ #
89
+ # As we do not support NAPTR lookups, we diverge from spec and
90
+ # select either UDP or TLS depending on the the URI scheme.
91
+ # This should theoretically only be done if the URI host is a
92
+ # numeric IP address.
93
+ #
94
+ # https://datatracker.ietf.org/doc/html/rfc3263#section-4.1
95
+ if "transport" in uri.parameters and uri.parameters["transport"]:
96
+ # A transport was explicitly specified, use it.
97
+ protocol = uri.parameters["transport"].lower()
98
+ elif uri.scheme == "sips":
99
+ # The URI scheme is "sips", use TLS.
100
+ protocol = "tls"
101
+ else:
102
+ # Default to UDP.
103
+ protocol = "udp"
104
+
105
+ # Determine the IP address and port.
106
+ #
107
+ # https://datatracker.ietf.org/doc/html/rfc3263#section-4.2
108
+ if is_ip_address or protocol == "ws":
109
+ # The host is an IP address, use the specified port or the default
110
+ # port for the transport protocol.
111
+ #
112
+ # We diverge from spec and also handle WebSockets here.
113
+ host = uri.host
114
+ port = uri.port or get_default_port(protocol)
115
+ elif uri.port is not None:
116
+ host = await asyncio.get_running_loop().run_in_executor(
117
+ None, socket.gethostbyname, uri.host
118
+ )
119
+ port = uri.port
120
+ else:
121
+ raise NotImplementedError("SRV lookups are not yet supported")
122
+ else:
123
+ # For responses, use the top-most `Via` header.
124
+ #
125
+ # https://datatracker.ietf.org/doc/html/rfc3261#section-18.2.2
126
+ via = message.via[0]
127
+
128
+ # Select the transport protocol.
129
+ protocol = via.transport.lower()
130
+
131
+ # If the Via contains a "received" parameter, use it. Otherwise
132
+ # use the "sent-by" value which is guaranteed to be an IP address.
133
+ if "received" in via.parameters and via.parameters["received"]:
134
+ host = via.parameters["received"]
135
+ else:
136
+ host = via.host
137
+
138
+ # If the Via contains an "rport" parameter, use it. Otherwise use
139
+ # the "sent-by value".
140
+ if "rport" in via.parameters and via.parameters["rport"]:
141
+ port = int(via.parameters["rport"])
142
+ else:
143
+ port = via.port or get_default_port(protocol)
144
+
145
+ return TransportAddress(protocol=protocol, host=host, port=port)
146
+
147
+
148
+ def set_transport_source(message: sipmessage.Message, transport: BaseTransport) -> None:
149
+ if isinstance(message, sipmessage.Request):
150
+ # Rewrite the top-most Via with our address.
151
+ vias = message.via
152
+ if vias and vias[0].host == AUTO_HOST:
153
+ vias[0] = dataclasses.replace(
154
+ vias[0],
155
+ host=transport.via_host,
156
+ port=transport.via_port,
157
+ transport=transport.via_transport,
158
+ )
159
+ message.via = vias
160
+
161
+ # Rewrite Contact headers with our address.
162
+ contacts = []
163
+ contacts_changed = False
164
+ for contact in message.contact:
165
+ if contact.uri.host == AUTO_HOST:
166
+ contact = dataclasses.replace(
167
+ contact,
168
+ uri=dataclasses.replace(
169
+ contact.uri,
170
+ host=transport.via_host,
171
+ port=transport.via_port,
172
+ parameters=contact.uri.parameters.replace(
173
+ transport=transport.uri_transport
174
+ ),
175
+ ),
176
+ )
177
+ contacts_changed = True
178
+ contacts.append(contact)
179
+ if contacts_changed:
180
+ message.contact = contacts
181
+
182
+
183
+ def update_request_via(request: sipmessage.Request, host: str, port: int) -> None:
184
+ """
185
+ Update the top-most `Via` header based on the IP address and port
186
+ from which the request was received.
187
+ """
188
+ if request.via:
189
+ via = request.via[0]
190
+ via_changed = False
191
+
192
+ # If the host portion of the `sent-by` in the top-most `Via` does
193
+ # not match the IP address from which the request was received.
194
+ #
195
+ # https://datatracker.ietf.org/doc/html/rfc3261#section-18.2.1
196
+ if via.host != host:
197
+ via = dataclasses.replace(
198
+ via, parameters=via.parameters.replace(received=host)
199
+ )
200
+ via_changed = True
201
+
202
+ # If the top-most `Via` contains an `rport` parameter with no value, set
203
+ # the `rport` parameter to the port from which the request was received.
204
+ #
205
+ # https://datatracker.ietf.org/doc/html/rfc3581#section-4
206
+ if "rport" in via.parameters and via.parameters["rport"] is None:
207
+ via = dataclasses.replace(
208
+ via, parameters=via.parameters.replace(rport=str(port))
209
+ )
210
+ via_changed = True
211
+
212
+ if via_changed:
213
+ request.via = [via] + request.via[1:]
214
+
215
+
216
+ class TransportLayer:
217
+ """
218
+ SIP transport layer.
219
+ """
220
+
221
+ def __init__(self, *, message_handler: MessageHandler) -> None:
222
+ self._message_handler = message_handler
223
+ self._transports: set[BaseTransport] = set()
224
+
225
+ async def close(self) -> None:
226
+ """
227
+ Close the transport layer.
228
+ """
229
+ # Iterate over a copy of the transports to allow changes
230
+ # during iteration.
231
+ for transport in set(self._transports):
232
+ await transport.close()
233
+ self._transports.clear()
234
+
235
+ async def listen(self, address: TransportAddress) -> None:
236
+ """
237
+ Start listening on the given transport address.
238
+ """
239
+ assert address.protocol == "udp"
240
+ transport = await create_udp_transport(
241
+ message_handler=self._message_handler,
242
+ local_addr=(address.host, address.port),
243
+ )
244
+ self._transports.add(transport)
245
+
246
+ async def send_message(self, message: sipmessage.Message) -> bool:
247
+ """
248
+ Send the given message and return whether the selected
249
+ transport is reliable.
250
+ """
251
+ # Finalise the message.
252
+ message.content_length = len(message.body)
253
+
254
+ # Determine transport recipient.
255
+ destination = await get_transport_destination(message)
256
+
257
+ # Determine transport to use.
258
+ assert len(self._transports) == 1, "Only a single transport is supported"
259
+ transport = list(self._transports)[0]
260
+
261
+ # Rewrite references to our transport address.
262
+ set_transport_source(message, transport)
263
+
264
+ # Send the message and return whether a reliable transport was used.
265
+ await transport.send_message(message, destination)
266
+ return transport.is_reliable
267
+
268
+
269
+ class UdpTransport(BaseTransport, asyncio.DatagramProtocol):
270
+ is_reliable = False
271
+ uri_transport = "udp"
272
+ via_transport = "UDP"
273
+
274
+ def __init__(self, *, message_handler: MessageHandler) -> None:
275
+ self._message_handler = message_handler
276
+ self._transport: asyncio.DatagramTransport | None = None
277
+
278
+ async def close(self) -> None:
279
+ if self._transport is not None:
280
+ self._transport.close()
281
+
282
+ async def send_message(
283
+ self, message: sipmessage.Message, destination: TransportAddress
284
+ ) -> None:
285
+ message_str = str(message)
286
+ logger.info("=>\n\n" + message_str)
287
+
288
+ if self._transport is not None:
289
+ addr = (destination.host, destination.port)
290
+ self._transport.sendto(message_str.encode("utf8"), addr)
291
+
292
+ # DatagramProtocol
293
+
294
+ def connection_made(self, transport: asyncio.BaseTransport) -> None:
295
+ self._transport = typing.cast(asyncio.DatagramTransport, transport)
296
+
297
+ sockname = transport.get_extra_info("sockname")
298
+ self.via_host = sockname[0]
299
+ self.via_port = sockname[1]
300
+
301
+ def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None:
302
+ message_str = data.decode("utf8")
303
+ logger.info("<=\n\n" + message_str)
304
+
305
+ try:
306
+ message = sipmessage.Message.parse(message_str)
307
+ except ValueError:
308
+ return
309
+ else:
310
+ if isinstance(message, sipmessage.Request):
311
+ update_request_via(message, addr[0], addr[1])
312
+ asyncio.ensure_future(self._message_handler(message))
313
+
314
+
315
+ async def create_udp_transport(
316
+ *,
317
+ message_handler: MessageHandler,
318
+ local_addr: tuple[str, int] | None,
319
+ remote_addr: tuple[str, int] | None = None,
320
+ ) -> UdpTransport:
321
+ loop = asyncio.get_event_loop()
322
+ _, protocol = await loop.create_datagram_endpoint(
323
+ lambda: UdpTransport(message_handler=message_handler),
324
+ local_addr=local_addr,
325
+ remote_addr=remote_addr,
326
+ )
327
+ return protocol
sipua/utils.py ADDED
@@ -0,0 +1,7 @@
1
+ import secrets
2
+ import string
3
+
4
+
5
+ def random_string(length: int) -> str:
6
+ allchar = string.ascii_letters + string.digits
7
+ return "".join(secrets.choice(allchar) for x in range(length))
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: sipua
3
+ Version: 0.0.1
4
+ Summary: Pure python SIP user agent
5
+ Author-email: Spacinov Engineering <opensource@spacinov.com>
6
+ License-Expression: BSD-2-Clause
7
+ Project-URL: Homepage, https://sipua.readthedocs.io/
8
+ Project-URL: Documentation, https://sipua.readthedocs.io/
9
+ Project-URL: Repository, https://github.com/spacinov/sipua
10
+ Project-URL: Issues, https://github.com/spacinov/sipua/issues
11
+ Keywords: SIP,RFC3261
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: Intended Audience :: Telecommunications Industry
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Communications :: Telephony
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/x-rst
25
+ License-File: LICENSE
26
+ Requires-Dist: sipmessage
27
+ Provides-Extra: dev
28
+ Requires-Dist: check-manifest; extra == "dev"
29
+ Requires-Dist: coverage; extra == "dev"
30
+ Requires-Dist: mypy; extra == "dev"
31
+ Requires-Dist: pyroma; extra == "dev"
32
+ Requires-Dist: ruff; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ sipua
36
+ =====
37
+
38
+ |license| |version| |tests| |coverage| |docs|
39
+
40
+ .. |license| image:: https://img.shields.io/pypi/l/sipua.svg
41
+ :target: https://pypi.python.org/pypi/sipua
42
+ :alt: License
43
+
44
+ .. |version| image:: https://img.shields.io/pypi/v/sipua.svg
45
+ :target: https://pypi.python.org/pypi/sipua
46
+ :alt: Version
47
+
48
+ .. |tests| image:: https://github.com/spacinov/sipua/workflows/tests/badge.svg
49
+ :target: https://github.com/spacinov/sipua/actions
50
+ :alt: Tests
51
+
52
+ .. |coverage| image:: https://img.shields.io/codecov/c/github/spacinov/sipua.svg
53
+ :target: https://codecov.io/gh/spacinov/sipua
54
+ :alt: Coverage
55
+
56
+ .. |docs| image:: https://readthedocs.org/projects/sipua/badge/?version=latest
57
+ :target: https://sipua.readthedocs.io/
58
+ :alt: Documentation
59
+
60
+ The ``sipua`` project provides a library for writing SIP user agents in Python.
@@ -0,0 +1,9 @@
1
+ sipua/__init__.py,sha256=8W8KdQWfSb56UBPV0mMHVtmf7M-PJYKkDO9lGJu1O9o,231
2
+ sipua/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7
3
+ sipua/transport.py,sha256=vJ5ONK0NKCqRxBv-Phr6un5IoWaIkZzlVtDan7Ps0Mo,10719
4
+ sipua/utils.py,sha256=5qT9MZ-aOUnAMKlfoQf9YXenzjZMWJ7awt_nu_zcyeE,188
5
+ sipua-0.0.1.dist-info/licenses/LICENSE,sha256=DD5LT_ZPvYNHlVtngdMvFLLM9BGMXkXOi511xl2C_Oo,1295
6
+ sipua-0.0.1.dist-info/METADATA,sha256=Wxh2UYcWXSLnjGDb3mD_07U4pgCd1X7TdS0QO5UJg4w,2148
7
+ sipua-0.0.1.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
8
+ sipua-0.0.1.dist-info/top_level.txt,sha256=t1iPaQ9AzFaV_UpYD4rkADNRFgycoOw2zMGK6WyS3F8,6
9
+ sipua-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (79.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,22 @@
1
+ Copyright (c) Spacinov SAS
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+ 2. Redistributions in binary form must reproduce the above copyright notice,
10
+ this list of conditions and the following disclaimer in the documentation
11
+ and/or other materials provided with the distribution.
12
+
13
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
14
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
17
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1 @@
1
+ sipua