aboutsummaryrefslogtreecommitdiffstats
path: root/toys/brhute-py/threaded_resolver.py
blob: a2d347b717926e4263432b71c09a18fb6a9c70b7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# From pyxmpp2 resolver.py
# Made standalone by laurent
# https://raw.github.com/Jajcus/pyxmpp2/master/pyxmpp2/resolver.py

# (C) Copyright 2003-2011 Jacek Konieczny <jajcus@jajcus.net>
# (C) Copyright 2013 Laurent Ghigonis <laurent@p1sec.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License Version
# 2.1 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

"""DNS resolever with SRV record support.

Normative reference:
  - `RFC 1035 <http://www.ietf.org/rfc/rfc1035.txt>`__
  - `RFC 2782 <http://www.ietf.org/rfc/rfc2782.txt>`__
"""

import socket
import random
import logging
import threading
import Queue

import dns.resolver
import dns.name
import dns.exception

DEFAULT_SETTINGS = {"ipv4": True, "ipv6": False, "prefer_ipv6": False}

def is_ipv6_available():
    """Check if IPv6 is available.
    
    :Return: `True` when an IPv6 socket can be created.
    """
    try:
        socket.socket(socket.AF_INET6).close()
    except (socket.error, AttributeError):
        return False
    return True

def is_ipv4_available():
    """Check if IPv4 is available.
    
    :Return: `True` when an IPv4 socket can be created.
    """
    try:
        socket.socket(socket.AF_INET).close()
    except socket.error:
        return False
    return True

def shuffle_srv(records):
    """Randomly reorder SRV records using their weights.

    :Parameters:
        - `records`: SRV records to shuffle.
    :Types:
        - `records`: sequence of :dns:`dns.rdtypes.IN.SRV`

    :return: reordered records.
    :returntype: `list` of :dns:`dns.rdtypes.IN.SRV`"""
    if not records:
        return []
    ret = []
    while len(records) > 1:
        weight_sum = 0
        for rrecord in records:
            weight_sum += rrecord.weight + 0.1
        thres = random.random() * weight_sum
        weight_sum = 0
        for rrecord in records:
            weight_sum += rrecord.weight + 0.1
            if thres < weight_sum:
                records.remove(rrecord)
                ret.append(rrecord)
                break
    ret.append(records[0])
    return ret

def reorder_srv(records):
    """Reorder SRV records using their priorities and weights.

    :Parameters:
        - `records`: SRV records to shuffle.
    :Types:
        - `records`: `list` of :dns:`dns.rdtypes.IN.SRV`

    :return: reordered records.
    :returntype: `list` of :dns:`dns.rdtypes.IN.SRV`"""
    records = list(records)
    records.sort()
    ret = []
    tmp = []
    for rrecord in records:
        if not tmp or rrecord.priority == tmp[0].priority:
            tmp.append(rrecord)
            continue
        ret += shuffle_srv(tmp)
        tmp = [rrecord]
    if tmp:
        ret += shuffle_srv(tmp)
    return ret

class BlockingResolver():
    """Blocking resolver using the DNSPython package.

    Both `resolve_srv` and `resolve_address` will block until the 
    lookup completes or fail and then call the callback immediately.
    """
    def __init__(self, settings =  None):
        if settings:
            self.settings = settings
        else:
            self.settings = DEFAULT_SETTINGS
        
    def resolve_srv(self, domain, service, protocol, callback):
        """Start looking up an SRV record for `service` at `domain`.

        `callback` will be called with a properly sorted list of (hostname,
        port) pairs on success. The list will be empty on error and it will
        contain only (".", 0) when the service is explicitely disabled.

        :Parameters:
            - `domain`: domain name to look up
            - `service`: service name e.g. 'xmpp-client'
            - `protocol`: protocol name, e.g. 'tcp'
            - `callback`: a function to be called with a list of received
                addresses
        :Types:
            - `domain`: `unicode`
            - `service`: `unicode`
            - `protocol`: `unicode`
            - `callback`: function accepting a single argument
        """
        if isinstance(domain, unicode):
            domain = domain.encode("idna").decode("us-ascii")
        domain = "_{0}._{1}.{2}".format(service, protocol, domain)
        try:
            records = dns.resolver.query(domain, 'SRV')
        except dns.exception.DNSException, err:
            logger.warning("Could not resolve {0!r}: {1}"
                                .format(domain, err.__class__.__name__))
            callback([])
            return
        if not records:
            callback([])
            return

        result = []
        for record in reorder_srv(records):
            hostname = record.target.to_text()
            if hostname in (".", ""):
                continue
            result.append((hostname, record.port))

        if not result:
            callback([(".", 0)])
        else:
            callback(result)
        return

    def resolve_address(self, hostname, callback, allow_cname = True):
        """Start looking up an A or AAAA record.

        `callback` will be called with a list of (family, address) tuples
        (each holiding socket.AF_*  and IPv4 or IPv6 address literal) on
        success. The list will be empty on error.

        :Parameters:
            - `hostname`: the host name to look up
            - `callback`: a function to be called with a list of received
                addresses
            - `allow_cname`: `True` if CNAMEs should be followed
        :Types:
            - `hostname`: `unicode`
            - `callback`: function accepting a single argument
            - `allow_cname`: `bool`
        """
        if isinstance(hostname, unicode):
            hostname = hostname.encode("idna").decode("us-ascii")
        rtypes = []
        if self.settings["ipv6"]:
            rtypes.append(("AAAA", socket.AF_INET6))
        if self.settings["ipv4"]:
            rtypes.append(("A", socket.AF_INET))
        if not self.settings["prefer_ipv6"]:
            rtypes.reverse()
        exception = None
        result = []
        for rtype, rfamily in rtypes:
            try:
                try:
                    records = dns.resolver.query(hostname, rtype)
                except dns.exception.DNSException:
                    records = dns.resolver.query(hostname + ".", rtype)
            except dns.exception.DNSException, err:
                exception = err
                continue
            if not allow_cname and records.rrset.name != dns.name.from_text(
                                                                hostname):
                logger.warning("Unexpected CNAME record found for {0!r}"
                                                        .format(hostname))
                continue
            if records:
                for record in records:
                    result.append((rfamily, record.to_text()))

        if not result and exception:
            logger.warning("Could not resolve {0!r}: {1}".format(hostname,
                                            exception.__class__.__name__))
        callback(result)

class ThreadedResolver():
    """Base class for threaded resolvers.

    Starts worker threads, each running a blocking resolver implementation
    and communicates with them to provide non-blocking asynchronous API.
    """
    def __init__(self, settings = None, max_threads = 1):
        if settings:
            self.settings = settings
        else:
            self.settings = DEFAULT_SETTINGS
        self.threads = []
        self.queue = Queue.Queue()
        self.lock = threading.RLock()
        self.max_threads = max_threads
        self.last_thread_n = 0

def _make_resolver(self):    
    """Threaded resolver implementation using the DNSPython
    :dns:`dns.resolver` module.
    """
    return BlockingResolver(self.settings)

    def stop(self):
        """Stop the resolver threads.
        """
        with self.lock:
            for dummy in self.threads:
                self.queue.put(None)
        
    def _start_thread(self):
        """Start a new working thread unless the maximum number of threads
        has been reached or the request queue is empty.
        """
        with self.lock:
            if self.threads and self.queue.empty():
                return
            if len(self.threads) >= self.max_threads:
                return
            thread_n = self.last_thread_n + 1
            self.last_thread_n = thread_n
            thread = threading.Thread(target = self._run,
                            name = "{0!r} #{1}".format(self, thread_n),
                            args = (thread_n,))
            self.threads.append(thread)
            thread.daemon = True
            thread.start()

    def resolve_address(self, hostname, callback, allow_cname = True):
        request = ("resolve_address", (hostname, callback, allow_cname))
        self._start_thread()
        self.queue.put(request)
    
    def resolve_srv(self, domain, service, protocol, callback):
        request = ("resolve_srv", (domain, service, protocol, callback))
        self._start_thread()
        self.queue.put(request)

    def _run(self, thread_n):
        """The thread function."""
        try:
            logger.debug("{0!r}: entering thread #{1}"
                                                .format(self, thread_n))
            resolver = self._make_resolver()
            while True:
                request = self.queue.get()
                if request is None:
                    break
                method, args = request
                logger.debug(" calling {0!r}.{1}{2!r}"
                                            .format(resolver, method, args))
                getattr(resolver, method)(*args) # pylint: disable=W0142
                self.queue.task_done()
            logger.debug("{0!r}: leaving thread #{1}"
                                                .format(self, thread_n))
        finally:
            self.threads.remove(threading.currentThread())

# vi: sts=4 et sw=4