Module: rtclite.std.ietf.rfc3263
# Copyright (c) 2008, Kundan Singh. All rights reserved. See LICENSE for details.
This file implements RFC3263 (Locating SIP servers)
''' Uses DNS to resolve a domain name into SIP servers using NAPTR, SRV and A/AAAA records. TODO: (1) need to make it multitask compatible or have a separate thread, (3) need to return priority and weight. >>> print resolve('sip:192.1.2.3') # with numeric IP [('192.1.2.3', 5060, 'udp'), ('192.1.2.3', 5060, 'tcp'), ('192.1.2.3', 5061, 'tls')] >>> print resolve('sip:192.1.2.3;maddr=192.3.3.3') # and maddr param [('192.3.3.3', 5060, 'udp'), ('192.3.3.3', 5060, 'tcp'), ('192.3.3.3', 5061, 'tls')] >>> print resolve('sip:192.1.2.3:5062;transport=tcp') # and port, transport param [('192.1.2.3', 5062, 'tcp')] >>> print resolve('sips:192.1.2.3') # and sips [('192.1.2.3', 5061, 'tls')] >>> print resolve('sips:192.1.2.3:5062') # and sips, port [('192.1.2.3', 5062, 'tls')] >>> print resolve('sip:39peers.net') # with non-numeric without NAPTR/SRV [('74.220.215.84', 5060, 'udp'), ('74.220.215.84', 5060, 'tcp'), ('74.220.215.84', 5061, 'tls')] >>> print resolve('sip:39peers.net:5062') # and port [('74.220.215.84', 5062, 'udp'), ('74.220.215.84', 5062, 'tcp'), ('74.220.215.84', 5062, 'tls')] >>> print resolve('sip:39peers.net;transport=tcp') # and transport [('74.220.215.84', 5060, 'tcp')] >>> print resolve('sips:39peers.net') # and sips [('74.220.215.84', 5061, 'tls')] >>> print resolve('sip:iptel.org') # with no NAPTR but has SRV records [('212.79.111.157', 5060, 'udp'), ('212.79.111.157', 5060, 'tcp')] >>> print resolve('sips:iptel.org') # and sips [('212.79.111.155', 5061, 'tls')] >>> print resolve('sip:columbia.edu') # with one NAPTR and two SRV records [('128.59.59.208', 5060, 'udp'), ('128.59.59.229', 5060, 'udp')] >>> print resolve('sips:columbia.edu') # and sips (no NAPTR for sips) [('128.59.105.24', 5061, 'tls')] >>> print resolve('sip:adobe.com') # with multiple NAPTR and multiple SRV [('192.150.16.117', 5060, 'udp')] >>> print resolve('sip:adobe.com', supported=('tcp', 'tls')) # if udp is not supported [('192.150.16.117', 5060, 'tcp')] >>> print resolve('sips:adobe.com') # with multiple NAPTR and multiple SRV [('192.150.12.115', 5061, 'tls')] >>> print list(sorted(resolve('sip:twilio.com'))) [('50.31.227.68', 5060, 'udp'), ('50.31.227.69', 5060, 'udp'), ('50.31.227.70', 5060, 'udp'), ('69.5.92.68', 5060, 'udp'), ('69.5.92.69', 5060, 'udp'), ('69.5.92.70', 5060, 'udp')] ''' import sys, os, time, random, logging if os.name == 'nt': # on windows import RegistryResolve from common import RegistryResolve _nameservers = RegistryResolve() else: _nameservers = None from .rfc2396 import URI, isIPv4 from .rfc1035 import Resolver, C_IN, T_NAPTR, T_SRV, T_A logger = logging.getLogger('rfc3263') _resolver, _cache = None, {} # Name servers, resolver and DNS cache (plus negative cache) _proto = {'udp': ('sip+d2u', 5060), 'tcp': ('sip+d2t', 5060), 'tls': ('sips+d2t', 5061), 'sctp': ('sip+d2s', 5060)} # map from transport to details _rproto = dict([(x[1][0], x[0]) for x in _proto.iteritems()]) # reverse mapping {'sip+d2u': 'udp', ...} _xproto = dict([(x[0], '_%s._%s'%(x[1][0].split('+')[0], x[0] if x[0] != 'tls' else 'tcp')) for x in _proto.iteritems()]) # mapping {'udp' : '_sip._udp', ...} _rxproto = dict([(x[1], x[0]) for x in _xproto.iteritems()]) # mapping { '_sips._tcp': 'tls', ...} _zxproto = dict([(x[0], _proto[x[1]]) for x in _rxproto.iteritems()]) # mapping { '_sips._tcp': ('sip+d2t, 5061), ...} _group = lambda x: sorted(x, lambda a,b: a[1]-b[1]) # sort a list of tuples based on priority def _query(key, negTimeout=60): # key is (target, type) '''Perform a single DNS query, and return the ANSWER section. Uses internal cache to avoid repeating the queries. The timeout of the cache entry is determined by TTL obtained in the results. It always returns a list, even if empty.''' global _resolver; resolver = _resolver or Resolver(_nameservers) if key in _cache and _cache[key][1] < time.time(): return random.shuffle(_cache[key][0]) and _cache[key][0] try: raw = resolver.Raw(key[0], key[1], C_IN, recursion=True, proto=None) if raw and raw['HEADER']['OPCODES']['TC']: # if truncated, try with TCP raw = resolver.Raw(key[0], key[1], C_IN, recursion=False, proto='tcp') answer = raw and raw['HEADER']['ANCOUNT'] > 0 and raw['ANSWER'] or []; random.shuffle(answer) except Exception, e: logger.exception('_query(%r) exception', key) answer = [] _cache[key] = (answer, time.time() + min([(x['TTL'] if 'TTL' in x else negTimeout) for x in answer] + [negTimeout])) return answer
From RFC3263 p.1
   The Session Initiation Protocol (SIP) uses DNS procedures to allow a
   client to resolve a SIP Uniform Resource Identifier (URI) into the IP
   address, port, and transport protocol of the next hop to contact.  It
   also uses DNS to allow a server to send a response to a backup client
   if the primary client has failed.  This document describes those DNS
   procedures in detail.
def resolve(uri, supported=('udp', 'tcp', 'tls'), secproto=('tls',)): '''Resolve a URI using RFC3263 to list of (IP address, port) tuples each with its order, preference, transport and TTL information. The application can supply a list of supported protocols if needed.''' if not isinstance(uri, URI): uri = URI(uri) transport = uri.param['transport'] if 'transport' in uri.param else None target = uri.param['maddr'] if 'maddr' in uri.param else uri.host numeric, port, naptr, srv, result = isIPv4(target), uri.port, None, None, None if uri.secure: supported = secproto # only support secproto for "sips"
From rfc3263 p.6
4.1 Selecting a Transport Protocol

   First, the client selects a transport protocol.

   If the URI specifies a transport protocol in the transport parameter,
   that transport protocol SHOULD be used.

   Otherwise, if no transport protocol is specified, but the TARGET is a
   numeric IP address, the client SHOULD use UDP for a SIP URI, and TCP
   for a SIPS URI.  Similarly, if no transport protocol is specified,
   and the TARGET is not numeric, but an explicit port is provided, the
   client SHOULD use UDP for a SIP URI, and TCP for a SIPS URI.  This is
   because UDP is the only mandatory transport in RFC 2543 [6], and thus
   the only one guaranteed to be interoperable for a SIP URI.  It was
   also specified as the default transport in RFC 2543 when no transport
   was present in the SIP URI.  However, another transport, such as TCP,
   MAY be used if the guidelines of SIP mandate it for this particular
   request.  That is the case, for example, for requests that exceed the
   path MTU.

   Otherwise, if no transport protocol or port is specified, and the
   target is not a numeric IP address, the client SHOULD perform a NAPTR
   query for the domain in the URI.  The services relevant for the task
   of transport protocol selection are those with NAPTR service fields
   with values "SIP+D2X" and "SIPS+D2X", where X is a letter that
   corresponds to a transport protocol supported by the domain.  This
   specification defines D2U for UDP, D2T for TCP, and D2S for SCTP.  We
   also establish an IANA registry for NAPTR service name to transport
   protocol mappings.

   These NAPTR records provide a mapping from a domain to the SRV record
   for contacting a server with the specific transport protocol in the
   NAPTR services field.  The resource record will contain an empty
   regular expression and a replacement value, which is the SRV record
   for that particular transport protocol.  If the server supports
   multiple transport protocols, there will be multiple NAPTR records,
   each with a different service value.  As per RFC 2915 [3], the client
   discards any records whose services fields are not applicable.  For
   the purposes of this specification, several rules are defined.
   First, a client resolving a SIPS URI MUST discard any services that
   do not contain "SIPS" as the protocol in the service field.  The
   converse is not true, however.  A client resolving a SIP URI SHOULD
   retain records with "SIPS" as the protocol, if the client supports
   TLS.  Second, a client MUST discard any service fields that identify
   a resolution service whose value is not "D2X", for values of X that
   indicate transport protocols supported by the client.  The NAPTR
   processing as described in RFC 2915 will result in the discovery of
   the most preferred transport protocol of the server that is supported
   by the client, as well as an SRV record for the server.  It will also
   allow the client to discover if TLS is available and its preference
   for its usage.

   As an example, consider a client that wishes to resolve
   sip:user@example.com.  The client performs a NAPTR query for that
   domain, and the following NAPTR records are returned:

   ;          order pref flags service      regexp  replacement
      IN NAPTR 50   50  "s"  "SIPS+D2T"     ""  _sips._tcp.example.com.
      IN NAPTR 90   50  "s"  "SIP+D2T"      ""  _sip._tcp.example.com
      IN NAPTR 100  50  "s"  "SIP+D2U"      ""  _sip._udp.example.com.

   This indicates that the server supports TLS over TCP, TCP, and UDP,
   in that order of preference.  Since the client supports TCP and UDP,
   TCP will be used, targeted to a host determined by an SRV lookup of
   _sip._tcp.example.com.  That lookup would return:

   ;;          Priority Weight Port   Target
       IN SRV  0        1      5060   server1.example.com
       IN SRV  0        2      5060   server2.example.com

   If a SIP proxy, redirect server, or registrar is to be contacted
   through the lookup of NAPTR records, there MUST be at least three
   records - one with a "SIP+D2T" service field, one with a "SIP+D2U"
   service field, and one with a "SIPS+D2T" service field.  The records
   with SIPS as the protocol in the service field SHOULD be preferred
   (i.e., have a lower value of the order field) above records with SIP
   as the protocol in the service field.  A record with a "SIPS+D2U"
   service field SHOULD NOT be placed into the DNS, since it is not
   possible to use TLS over UDP.

   It is not necessary for the domain suffixes in the NAPTR replacement
   field to match the domain of the original query (i.e., example.com
   above).  However, for backwards compatibility with RFC 2543, a domain
   MUST maintain SRV records for the domain of the original query, even
   if the NAPTR record is in a different domain.  As an example, even
   though the SRV record for TCP is _sip._tcp.school.edu, there MUST
   also be an SRV record at _sip._tcp.example.com.
      RFC 2543 will look up the SRV records for the domain directly.  If
      these do not exist because the NAPTR replacement points to a
      different domain, the client will fail.

   For NAPTR records with SIPS protocol fields, (if the server is using
   a site certificate), the domain name in the query and the domain name
   in the replacement field MUST both be valid based on the site
   certificate handed out by the server in the TLS exchange.  Similarly,
   the domain name in the SRV query and the domain name in the target in
   the SRV record MUST both be valid based on the same site certificate.
   Otherwise, an attacker could modify the DNS records to contain
   replacement values in a different domain, and the client could not
   validate that this was the desired behavior or the result of an
   attack.

   If no NAPTR records are found, the client constructs SRV queries for
   those transport protocols it supports, and does a query for each.
   Queries are done using the service identifier "_sip" for SIP URIs and
   "_sips" for SIPS URIs.  A particular transport is supported if the
   query is successful.  The client MAY use any transport protocol it
   desires which is supported by the server.

      This is a change from RFC 2543.  It specified that a client would
      lookup SRV records for all transports it supported, and merge the
      priority values across those records.  Then, it would choose the
      most preferred record.

   If no SRV records are found, the client SHOULD use TCP for a SIPS
   URI, and UDP for a SIP URI.  However, another transport protocol,
   such as TCP, MAY be used if the guidelines of SIP mandate it for this
   particular request.  That is the case, for example, for requests that
   exceed the path MTU.
if transport: transports = (transport,) if transport in supported else () # only the given transport is used elif numeric or port is not None: transports = supported else: naptr = _query((target, T_NAPTR)) if naptr: # find the first that is supported ordered = filter(lambda r: r[1] in supported, sorted(map(lambda r: (r['RDATA']['ORDER'], _rproto.get(r['RDATA']['SERVICE'].lower(), ''), r), naptr), lambda a,b: a[0]-b[0])) # filter out unsupported transports if ordered: selected = filter(lambda r: r[0] == ordered[0][0], ordered) # keep only top-ordered values, ignore rest transports, naptr = map(lambda r: r[1], selected), map(lambda r: r[2], selected) # unzip to transports and naptr values else: transports, naptr = supported, None # assume failure if not found; clear the naptr response if not naptr: # do not use "else", because naptr may be cleared in "if" srv = filter(lambda r: r[1], map(lambda p: (_rxproto.get(p, ''), _query(('%s.%s'%(p, target), T_SRV))), map(lambda t: _xproto[t], supported))) if srv: transports = map(lambda s: s[0], srv) else: transports = supported
From rfc3263 p.8
4.2 Determining Port and IP Address

   Once the transport protocol has been determined, the next step is to
   determine the IP address and port.

   If TARGET is a numeric IP address, the client uses that address.  If
   the URI also contains a port, it uses that port.  If no port is
   specified, it uses the default port for the particular transport
   protocol.

   If the TARGET was not a numeric IP address, but a port is present in
   the URI, the client performs an A or AAAA record lookup of the domain
   name.  The result will be a list of IP addresses, each of which can
   be contacted at the specific port from the URI and transport protocol

   determined previously.  The client SHOULD try the first record.  If
   an attempt should fail, based on the definition of failure in Section
   4.3, the next SHOULD be tried, and if that should fail, the next
   SHOULD be tried, and so on.

      This is a change from RFC 2543.  Previously, if the port was
      explicit, but with a value of 5060, SRV records were used.  Now, A
      or AAAA records will be used.

   If the TARGET was not a numeric IP address, and no port was present
   in the URI, the client performs an SRV query on the record returned
   from the NAPTR processing of Section 4.1, if such processing was
   performed.  If it was not, because a transport was specified
   explicitly, the client performs an SRV query for that specific
   transport, using the service identifier "_sips" for SIPS URIs.  For a
   SIP URI, if the client wishes to use TLS, it also uses the service
   identifier "_sips" for that specific transport, otherwise, it uses
   "_sip".  If the NAPTR processing was not done because no NAPTR
   records were found, but an SRV query for a supported transport
   protocol was successful, those SRV records are selected. Irregardless
   of how the SRV records were determined, the procedures of RFC 2782,
   as described in the section titled "Usage rules" are followed,
   augmented by the additional procedures of Section 4.3 of this
   document.

   If no SRV records were found, the client performs an A or AAAA record
   lookup of the domain name.  The result will be a list of IP
   addresses, each of which can be contacted using the transport
   protocol determined previously, at the default port for that
   transport.  Processing then proceeds as described above for an
   explicit port once the A or AAAA records have been looked up.
if numeric: result = map(lambda t: (target, port or _proto[t][1], t), transports) elif port: result = sum(map(lambda t: map(lambda r: (r['RDATA'], port, t), _query((target, T_A))), transports), []) else: service = None if naptr: service = sorted(map(lambda x: (x['RDATA']['REPLACEMENT'].lower(), x['RDATA']['ORDER'], x['RDATA']['PREFERENCE'], x['RDATA']['SERVICE'].lower()), naptr), lambda a,b: a[1]-b[1]) elif transport: service = [('%s.%s'%(_xproto[transport], target), 0, 0, _proto[transport][0])] if not srv: srv = filter(lambda y: y[1], map(lambda s: (_rproto[s[3].lower()], _query((s[0], T_SRV))), service)) if service else [] if srv: # to fix for twilio.com: srv = map(lambda x: (x[0], filter(lambda s: s['TYPE'] == T_SRV, x[1])), srv) out = list(sorted(sum(map(lambda s: map(lambda r: (r['RDATA']['DOMAIN'].lower(), r['RDATA']['PRIORITY'], r['RDATA']['WEIGHT'], r['RDATA']['PORT'], s[0]), s[1]), srv), []), lambda a,b: a[1]-b[1])) result = sum(map(lambda x: map(lambda y: (y['RDATA'], x[1], x[2]), (_query((x[0], T_A)) or [])), map(lambda r: (r[0], r[3], r[4]), out)), []) return result or map(lambda x: (x[0], port or _proto[x[1]][1], x[1]), sum(map(lambda b: map(lambda a: (a, b), map(lambda x: x['RDATA'], _query((target, T_A)))), transports), [])) # finally do A record on target, if nothing else worked if __name__ == '__main__': # Unit test of this module logging.basicConfig() logger.setLevel(logging.CRITICAL) import doctest doctest.testmod()