jid.py 13.1 KB
Newer Older
Lance Stout's avatar
Lance Stout committed
1
2
# -*- coding: utf-8 -*-
"""
louiz’'s avatar
louiz’ committed
3
    slixmpp.jid
Lance Stout's avatar
Lance Stout committed
4
5
    ~~~~~~~~~~~~~~~~~~~~~~~

Lance Stout's avatar
Lance Stout committed
6
    This module allows for working with Jabber IDs (JIDs).
Lance Stout's avatar
Lance Stout committed
7

louiz’'s avatar
louiz’ committed
8
    Part of Slixmpp: The Slick XMPP Library
Lance Stout's avatar
Lance Stout committed
9
10
11
12
13
14
15
16

    :copyright: (c) 2011 Nathanael C. Fritz
    :license: MIT, see LICENSE for more details
"""

import re
import socket

Lance Stout's avatar
Lance Stout committed
17
from copy import deepcopy
18
from functools import lru_cache
Lance Stout's avatar
Lance Stout committed
19

20
from slixmpp.stringprep import nodeprep, resourceprep, idna, StringprepError
Lance Stout's avatar
Lance Stout committed
21

22
23
HAVE_INET_PTON = hasattr(socket, 'inet_pton')

Lance Stout's avatar
Lance Stout committed
24
25
26
#: The basic regex pattern that a JID must match in order to determine
#: the local, domain, and resource parts. This regex does NOT do any
#: validation, which requires application of nodeprep, resourceprep, etc.
Lance Stout's avatar
Lance Stout committed
27
28
29
JID_PATTERN = re.compile(
    "^(?:([^\"&'/:<>@]{1,1023})@)?([^/@]{1,1023})(?:/(.{1,1023}))?$"
)
Lance Stout's avatar
Lance Stout committed
30

Lance Stout's avatar
Lance Stout committed
31
#: The set of escape sequences for the characters not allowed by nodeprep.
32
33
JID_ESCAPE_SEQUENCES = {'\\20', '\\22', '\\26', '\\27', '\\2f',
                        '\\3a', '\\3c', '\\3e', '\\40', '\\5c'}
Lance Stout's avatar
Lance Stout committed
34

Lance Stout's avatar
Lance Stout committed
35
#: The reverse mapping of escape sequences to their original forms.
Lance Stout's avatar
Lance Stout committed
36
37
38
39
40
41
42
43
44
45
46
JID_UNESCAPE_TRANSFORMATIONS = {'\\20': ' ',
                                '\\22': '"',
                                '\\26': '&',
                                '\\27': "'",
                                '\\2f': '/',
                                '\\3a': ':',
                                '\\3c': '<',
                                '\\3e': '>',
                                '\\40': '@',
                                '\\5c': '\\'}

Lance Stout's avatar
Lance Stout committed
47

48
49
# TODO: Find the best cache size for a standard usage.
@lru_cache(maxsize=1024)
Lance Stout's avatar
Lance Stout committed
50
def _parse_jid(data):
Lance Stout's avatar
Lance Stout committed
51
52
    """
    Parse string data into the node, domain, and resource
Lance Stout's avatar
Lance Stout committed
53
54
55
56
57
58
59
    components of a JID, if possible.

    :param string data: A string that is potentially a JID.

    :raises InvalidJID:

    :returns: tuple of the validated local, domain, and resource strings
Lance Stout's avatar
Lance Stout committed
60
    """
Lance Stout's avatar
Lance Stout committed
61
    match = JID_PATTERN.match(data)
Lance Stout's avatar
Lance Stout committed
62
    if not match:
Lance Stout's avatar
Lance Stout committed
63
        raise InvalidJID('JID could not be parsed')
Lance Stout's avatar
Lance Stout committed
64
65
66

    (node, domain, resource) = match.groups()

Lance Stout's avatar
Lance Stout committed
67
68
69
    node = _validate_node(node)
    domain = _validate_domain(domain)
    resource = _validate_resource(resource)
Lance Stout's avatar
Lance Stout committed
70
71
72
73
74

    return node, domain, resource


def _validate_node(node):
Lance Stout's avatar
Lance Stout committed
75
76
77
78
79
80
    """Validate the local, or username, portion of a JID.

    :raises InvalidJID:

    :returns: The local portion of a JID, as validated by nodeprep.
    """
81
    if node is None:
82
        return None
83

84
85
86
87
88
89
90
91
92
93
    try:
        node = nodeprep(node)
    except StringprepError:
        raise InvalidJID('Nodeprep failed')

    if not node:
        raise InvalidJID('Localpart must not be 0 bytes')
    if len(node) > 1023:
        raise InvalidJID('Localpart must be less than 1024 bytes')
    return node
Lance Stout's avatar
Lance Stout committed
94
95
96


def _validate_domain(domain):
Lance Stout's avatar
Lance Stout committed
97
98
99
100
101
102
103
104
105
106
107
108
109
    """Validate the domain portion of a JID.

    IP literal addresses are left as-is, if valid. Domain names
    are stripped of any trailing label separators (`.`), and are
    checked with the nameprep profile of stringprep. If the given
    domain is actually a punyencoded version of a domain name, it
    is converted back into its original Unicode form. Domains must
    also not start or end with a dash (`-`).

    :raises InvalidJID:

    :returns: The validated domain name
    """
Lance Stout's avatar
Lance Stout committed
110
111
    ip_addr = False

Lance Stout's avatar
Lance Stout committed
112
    # First, check if this is an IPv4 address
Lance Stout's avatar
Lance Stout committed
113
114
115
116
117
118
    try:
        socket.inet_aton(domain)
        ip_addr = True
    except socket.error:
        pass

Lance Stout's avatar
Lance Stout committed
119
    # Check if this is an IPv6 address
120
    if not ip_addr and HAVE_INET_PTON and domain[0] == '[' and domain[-1] == ']':
Lance Stout's avatar
Lance Stout committed
121
        try:
122
123
            ip = domain[1:-1]
            socket.inet_pton(socket.AF_INET6, ip)
Lance Stout's avatar
Lance Stout committed
124
            ip_addr = True
125
        except (socket.error, ValueError):
Lance Stout's avatar
Lance Stout committed
126
127
128
            pass

    if not ip_addr:
Lance Stout's avatar
Lance Stout committed
129
130
        # This is a domain name, which must be checked further

131
132
133
        if domain and domain[-1] == '.':
            domain = domain[:-1]

134
135
136
137
        try:
            domain = idna(domain)
        except StringprepError:
            raise InvalidJID('idna validation failed')
Lance Stout's avatar
Lance Stout committed
138

139
140
141
142
143
        if ':' in domain:
            raise InvalidJID('Domain containing a port')
        for label in domain.split('.'):
            if not label:
                raise InvalidJID('Domain containing too many dots')
Lance Stout's avatar
Lance Stout committed
144
            if '-' in (label[0], label[-1]):
Lance Stout's avatar
Lance Stout committed
145
                raise InvalidJID('Domain started or ended with -')
Lance Stout's avatar
Lance Stout committed
146

Lance Stout's avatar
Lance Stout committed
147
    if not domain:
148
        raise InvalidJID('Domain must not be 0 bytes')
149
150
    if len(domain) > 1023:
        raise InvalidJID('Domain must be less than 1024 bytes')
Lance Stout's avatar
Lance Stout committed
151

Lance Stout's avatar
Lance Stout committed
152
153
    return domain

Lance Stout's avatar
Lance Stout committed
154
155

def _validate_resource(resource):
Lance Stout's avatar
Lance Stout committed
156
157
158
159
160
161
    """Validate the resource portion of a JID.

    :raises InvalidJID:

    :returns: The local portion of a JID, as validated by resourceprep.
    """
162
    if resource is None:
163
        return None
Lance Stout's avatar
Lance Stout committed
164

165
166
167
168
    try:
        resource = resourceprep(resource)
    except StringprepError:
        raise InvalidJID('Resourceprep failed')
Lance Stout's avatar
Lance Stout committed
169

170
171
172
173
174
    if not resource:
        raise InvalidJID('Resource must not be 0 bytes')
    if len(resource) > 1023:
        raise InvalidJID('Resource must be less than 1024 bytes')
    return resource
Lance Stout's avatar
Lance Stout committed
175
176
177


def _unescape_node(node):
Lance Stout's avatar
Lance Stout committed
178
179
180
181
182
183
    """Unescape a local portion of a JID.

    .. note::
        The unescaped local portion is meant ONLY for presentation,
        and should not be used for other purposes.
    """
Lance Stout's avatar
Lance Stout committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
    unescaped = []
    seq = ''
    for i, char in enumerate(node):
        if char == '\\':
            seq = node[i:i+3]
            if seq not in JID_ESCAPE_SEQUENCES:
                seq = ''
        if seq:
            if len(seq) == 3:
                unescaped.append(JID_UNESCAPE_TRANSFORMATIONS.get(seq, char))

            # Pop character off the escape sequence, and ignore it
            seq = seq[1:]
        else:
            unescaped.append(char)
199
    return ''.join(unescaped)
Lance Stout's avatar
Lance Stout committed
200
201
202


def _format_jid(local=None, domain=None, resource=None):
Lance Stout's avatar
Lance Stout committed
203
204
205
206
207
208
209
210
    """Format the given JID components into a full or bare JID.

    :param string local: Optional. The local portion of the JID.
    :param string domain: Required. The domain name portion of the JID.
    :param strin resource: Optional. The resource portion of the JID.

    :return: A full or bare JID string.
    """
Link Mauve's avatar
Link Mauve committed
211
212
    if domain is None:
        return ''
213
    if local is not None:
Link Mauve's avatar
Link Mauve committed
214
215
216
        result = local + '@' + domain
    else:
        result = domain
217
    if resource is not None:
Link Mauve's avatar
Link Mauve committed
218
219
        result += '/' + resource
    return result
Lance Stout's avatar
Lance Stout committed
220
221
222


class InvalidJID(ValueError):
Lance Stout's avatar
Lance Stout committed
223
224
    """
    Raised when attempting to create a JID that does not pass validation.
Lance Stout's avatar
Lance Stout committed
225

Lance Stout's avatar
Lance Stout committed
226
227
228
229
    It can also be raised if modifying an existing JID in such a way as
    to make it invalid, such trying to remove the domain from an existing
    full JID while the local and resource portions still exist.
    """
Lance Stout's avatar
Lance Stout committed
230

Lance Stout's avatar
Lance Stout committed
231
# pylint: disable=R0903
232
class UnescapedJID:
Lance Stout's avatar
Lance Stout committed
233

Lance Stout's avatar
Lance Stout committed
234
235
236
237
    """
    .. versionadded:: 1.1.10
    """

238
    __slots__ = ('_node', '_domain', '_resource')
Lance Stout's avatar
Lance Stout committed
239

240
241
242
243
244
245
    def __init__(self, node, domain, resource):
        self._node = node
        self._domain = domain
        self._resource = resource

    def __getattribute__(self, name):
Lance Stout's avatar
Lance Stout committed
246
247
        """Retrieve the given JID component.

Lance Stout's avatar
Lance Stout committed
248
249
250
251
        :param name: one of: user, server, domain, resource,
                     full, or bare.
        """
        if name == 'resource':
252
            return self._resource or ''
253
        if name in ('user', 'username', 'local', 'node'):
254
            return self._node or ''
255
        if name in ('server', 'domain', 'host'):
256
            return self._domain or ''
257
258
259
260
261
        if name in ('full', 'jid'):
            return _format_jid(self._node, self._domain, self._resource)
        if name == 'bare':
            return _format_jid(self._node, self._domain)
        return object.__getattribute__(self, name)
Lance Stout's avatar
Lance Stout committed
262
263
264

    def __str__(self):
        """Use the full JID as the string value."""
265
        return _format_jid(self._node, self._domain, self._resource)
Lance Stout's avatar
Lance Stout committed
266
267

    def __repr__(self):
Lance Stout's avatar
Lance Stout committed
268
        """Use the full JID as the representation."""
269
        return _format_jid(self._node, self._domain, self._resource)
Lance Stout's avatar
Lance Stout committed
270
271


272
class JID:
Lance Stout's avatar
Lance Stout committed
273
274
275
276
277
278
279
280
281
282
283
284

    """
    A representation of a Jabber ID, or JID.

    Each JID may have three components: a user, a domain, and an optional
    resource. For example: user@domain/resource

    When a resource is not used, the JID is called a bare JID.
    The JID is a full JID otherwise.

    **JID Properties:**
        :full: The string value of the full JID.
285
        :jid: Alias for ``full``.
Lance Stout's avatar
Lance Stout committed
286
        :bare: The string value of the bare JID.
287
288
289
290
        :node: The node portion of the JID.
        :user: Alias for ``node``.
        :local: Alias for ``node``.
        :username: Alias for ``node``.
Lance Stout's avatar
Lance Stout committed
291
292
293
294
295
        :domain: The domain name portion of the JID.
        :server: Alias for ``domain``.
        :host: Alias for ``domain``.
        :resource: The resource portion of the JID.

Lance Stout's avatar
Lance Stout committed
296
297
298
299
    :param string jid:
        A string of the form ``'[user@]domain[/resource]'``.

    :raises InvalidJID:
Lance Stout's avatar
Lance Stout committed
300
301
    """

302
    __slots__ = ('_node', '_domain', '_resource', '_bare', '_full')
Joe Hildebrand's avatar
Joe Hildebrand committed
303

304
    def __init__(self, jid=None):
305
        if not jid:
306
307
308
309
310
311
            self._node = ''
            self._domain = ''
            self._resource = ''
            self._bare = ''
            self._full = ''
            return
312
        elif not isinstance(jid, JID):
313
            self._node, self._domain, self._resource = _parse_jid(jid)
314
        else:
315
316
317
            self._node = jid._node
            self._domain = jid._domain
            self._resource = jid._resource
318
        self._update_bare_full()
Lance Stout's avatar
Lance Stout committed
319
320

    def unescape(self):
Lance Stout's avatar
Lance Stout committed
321
322
323
324
325
326
327
328
329
330
        """Return an unescaped JID object.

        Using an unescaped JID is preferred for displaying JIDs
        to humans, and they should NOT be used for any other
        purposes than for presentation.

        :return: :class:`UnescapedJID`

        .. versionadded:: 1.1.10
        """
331
332
333
        return UnescapedJID(_unescape_node(self._node),
                            self._domain,
                            self._resource)
Lance Stout's avatar
Lance Stout committed
334

335
336
337
338
339
340
341
342
343
344
    def _update_bare_full(self):
        """Format the given JID into a bare and a full JID.
        """
        self._bare = (self._node + '@' + self._domain
                      if self._node
                      else self._domain)
        self._full = (self._bare + '/' + self._resource
                      if self._resource
                      else self._bare)

345
    @property
346
    def node(self):
347
        return self._node
Lance Stout's avatar
Lance Stout committed
348

349
350
    @property
    def user(self):
351
        return self._node
Lance Stout's avatar
Lance Stout committed
352

353
354
    @property
    def local(self):
355
        return self._node
356
357
358

    @property
    def username(self):
359
        return self._node
360
361

    @property
362
    def domain(self):
363
        return self._domain
364
365
366

    @property
    def server(self):
367
        return self._domain
368
369
370

    @property
    def host(self):
371
        return self._domain
372
373

    @property
374
    def resource(self):
375
        return self._resource
376
377

    @property
378
    def bare(self):
379
        return self._bare
380
381

    @property
382
    def full(self):
383
        return self._full
384

385
386
    @property
    def jid(self):
387
        return self._full
388

389
390
391
    @node.setter
    def node(self, value):
        self._node = _validate_node(value)
392
        self._update_bare_full()
393
394
395

    @user.setter
    def user(self, value):
396
        self._node = _validate_node(value)
397
        self._update_bare_full()
398
399
400

    @local.setter
    def local(self, value):
401
        self._node = _validate_node(value)
402
        self._update_bare_full()
403

404
405
406
    @username.setter
    def username(self, value):
        self._node = _validate_node(value)
407
        self._update_bare_full()
408
409
410

    @domain.setter
    def domain(self, value):
411
        self._domain = _validate_domain(value)
412
        self._update_bare_full()
413
414
415
416

    @server.setter
    def server(self, value):
        self._domain = _validate_domain(value)
417
        self._update_bare_full()
418
419
420

    @host.setter
    def host(self, value):
421
        self._domain = _validate_domain(value)
422
        self._update_bare_full()
423
424
425
426
427
428
429

    @bare.setter
    def bare(self, value):
        node, domain, resource = _parse_jid(value)
        assert not resource
        self._node = node
        self._domain = domain
430
        self._update_bare_full()
431
432
433
434

    @resource.setter
    def resource(self, value):
        self._resource = _validate_resource(value)
435
        self._update_bare_full()
436
437
438

    @full.setter
    def full(self, value):
439
        self._node, self._domain, self._resource = _parse_jid(value)
440
        self._update_bare_full()
441
442
443

    @jid.setter
    def jid(self, value):
444
        self._node, self._domain, self._resource = _parse_jid(value)
445
        self._update_bare_full()
Lance Stout's avatar
Lance Stout committed
446
447
448

    def __str__(self):
        """Use the full JID as the string value."""
449
        return self._full
Lance Stout's avatar
Lance Stout committed
450
451

    def __repr__(self):
Lance Stout's avatar
Lance Stout committed
452
        """Use the full JID as the representation."""
453
        return self._full
Lance Stout's avatar
Lance Stout committed
454

Lance Stout's avatar
Lance Stout committed
455
    # pylint: disable=W0212
Lance Stout's avatar
Lance Stout committed
456
    def __eq__(self, other):
Lance Stout's avatar
Lance Stout committed
457
        """Two JIDs are equal if they have the same full JID value."""
Lance Stout's avatar
Lance Stout committed
458
459
        if isinstance(other, UnescapedJID):
            return False
460
461
        if not isinstance(other, JID):
            other = JID(other)
Lance Stout's avatar
Lance Stout committed
462

463
464
465
        return (self._node == other._node and
                self._domain == other._domain and
                self._resource == other._resource)
Lance Stout's avatar
Lance Stout committed
466
467
468

    def __ne__(self, other):
        """Two JIDs are considered unequal if they are not equal."""
Lance Stout's avatar
Lance Stout committed
469
        return not self == other
Lance Stout's avatar
Lance Stout committed
470
471
472

    def __hash__(self):
        """Hash a JID based on the string version of its full JID."""
473
        return hash(self._full)