homer.py 22.9 KB
Newer Older
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
1
2
#!/usr/bin/env python3

3
4
5
6
7
# Homer is a DoH (DNS-over-HTTPS) and DoT (DNS-over-TLS) client. Its
# main purpose is to test DoH and DoT resolvers. Reference site is
# <https://framagit.org/bortzmeyer/homer/> See author, documentation,
# etc, there, or in the README.md included with the distribution.

Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
8
9
10
11
12
13
# http://pycurl.io/docs/latest
import pycurl

# http://www.dnspython.org/
import dns.message

14
15
16
# https://github.com/drkjam/netaddr/
import netaddr

17
18
19
20
21
# Octobre 2019: the Python GnuTLS bindings don't work with Python 3. So we use OpenSSL.
# https://www.pyopenssl.org/
# https://pyopenssl.readthedocs.io/
import OpenSSL

Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
22
23
24
25
26
27
import io
import sys
import base64
import getopt
import urllib.parse
import time
28
29
import socket
import ctypes
30
import re
31
import os.path
32
33
import hashlib
import base64
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
34

35
# Values that can be changed from the command line
36
dot = False # DoH by default
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
37
38
verbose = False
insecure = False
39
post = False
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
40
41
head = False
rtype = 'AAAA'
42
vhostname = None
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
43
tests = 1 # Number of repeated tests
44
ifile = None # Input file
45
delay = None
46
47
48
forceIPv4 = False
forceIPv6 = False
connectTo = None
49
50
51
# Monitoring plugin only:
host = None
path = None
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
52

53
54
55
# Do not change these
re_host = re.compile(r'^([0-9a-z][0-9a-z-\.]*)|([0-9:]+)|([0-9\.])$')

56
57
58
59
60
61
62
# For the monitoring plugin
STATE_OK = 0
STATE_WARNING = 1
STATE_CRITICAL = 2
STATE_UNKNOWN = 3
STATE_DEPENDENT = 4

Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
63
64
65
def error(msg=None):
    if msg is None:
        msg = "Unknown error"
66
67
    if monitoring:
        print("%s: %s" % (url, msg))
Alexandre's avatar
Alexandre committed
68
        sys.exit(STATE_CRITICAL)
69
70
71
    else:
        print(msg,file=sys.stderr)
        sys.exit(1)
Alexandre's avatar
Alexandre committed
72

Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
73
74
75
def usage(msg=None):
    if msg:
        print(msg,file=sys.stderr)
76
77
    print("Usage: %s [--dot] url-or-servername domain-name [DNS type]" % sys.argv[0], file=sys.stderr)
    print("See the README.md for more details.", file=sys.stderr)
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
78

79
def is_valid_hostname(name):
80
    name = canonicalize(name)
81
    return re_host.search(name)
82

83
84
85
86
87
88
89
90
91
def canonicalize(hostname):
    result = hostname.lower()
    # TODO handle properly the case where it fails with UnicodeError
    # (two consecutive dots for instance) to get a custom exception
    result = result.encode('idna').decode()
    if result[len(result)-1] == '.':
        result = result[:-1]
    return result

92
93
94
95
def is_valid_ip_address(addr):
    try:
        baddr = netaddr.IPAddress(addr)
    except netaddr.core.AddrFormatError:
96
97
        return (False, None)
    return (True, baddr.version)
98

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def is_valid_url(url):
  try:
    result = urllib.parse.urlparse(url) # A very poor validation, many
    # errors (for instance whitespaces, IPv6 address litterals without
    # brackets...) are ignored.
    return (result.scheme=="https" and result.netloc != "")
  except ValueError:
    return False

def get_certificate_san(x509cert):
    san = ""
    ext_count = x509cert.get_extension_count()
    for i in range(0, ext_count):
        ext = x509cert.get_extension(i)
        if "subjectAltName" in str(ext.get_short_name()):
            san = str(ext)
    return san

117
118
119
120
121
122
123
124
125
126
127
# Try one possible name. Names must be already canonicalized.
def match_hostname(hostname, possibleMatch):
    if possibleMatch.startswith("*."): # Wildcard
        base = possibleMatch[1:] # Skip the star
        # RFC 6125 says that we MAY accept left-most labels with
        # wildcards included (foo*bar). We don't do it here.
        try:
            (first, rest) = hostname.split(".", maxsplit=1)
        except ValueError: # One-label name
            rest = hostname
        if rest == base[1:]:
128
            return True
129
        if hostname == base[1:]:
130
            return True
131
132
133
134
135
136
137
138
        return False
    else:
        return hostname == possibleMatch

# Try all the names in the certificate
def validate_hostname(hostname, cert):
    # Complete specification is in RFC 6125. It is long and
    # complicated and I'm not sure we do it perfectly.
139
    (is_addr, family) = is_valid_ip_address(hostname)
140
    hostname = canonicalize(hostname)
141
    for alt_name in get_certificate_san(cert).split(", "):
142
        if alt_name.startswith("DNS:") and not is_addr:
143
            (start, base) = alt_name.split("DNS:")
144
            base = canonicalize(base)
145
146
            found = match_hostname(hostname, base)
            if found:
147
                return True
148
149
        elif alt_name.startswith("IP Address:") and is_addr:
            host_i = netaddr.IPAddress(hostname)
150
151
152
            (start, base) = alt_name.split("IP Address:")
            if base.endswith("\n"):
                base = base[:-1]
153
154
155
156
            try:
                base_i = netaddr.IPAddress(base)
            except netaddr.core.AddrFormatError:
                continue # Ignore broken IP addresses in certificates. Are we too liberal?
Alexandre's avatar
Alexandre committed
157
            if host_i == base_i:
158
159
                return True
        else:
160
161
162
            pass # Ignore unknown alternative name types. May be
                 # accept URI alternative names for DoH,
    # According to RFC 6125, we MUST NOT try the Common Name before the Subject Alternative Names.
163
    cn = canonicalize(cert.get_subject().commonName)
164
165
166
    found = match_hostname(hostname, cn)
    if found:
        return True
167
168
    return False

169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190

class RequestDoH:
    def __init__(self, qname, qtype=rtype):
        self.message = dns.message.make_query(qname, dns.rdatatype.from_text(qtype), use_edns=True, want_dnssec=True)
        self.message.id = 0 # DoH requests that
        self.data = self.message.to_wire()

    def create_handle(self, curl_opt):
        self.handle = pycurl.Curl()
        for opt, value in curl_opt.items():
            try:
                self.handle.setopt(opt, value)
            except AttributeError:
                pass # Probably an old version of libcurl, without CONNECT_TO. It appeared with 7.49.0

    def close_handle(self):
        self.handle.close()

    def perform(self):
        self.handle.perform()


191
class Connection:
192
193
    def __init__(self, server, servername=None, connect=None, forceIPv4=False, forceIPv6=False,
                 dot=False, verbose=verbose, insecure=insecure, post=post, head=head):
194
        if dot and not is_valid_hostname(server):
195
            error("DoT requires a host name or IP address, not \"%s\"" % server)
196
197
        if not dot and not is_valid_url(url):
            error("DoH requires a valid HTTPS URL, not \"%s\"" % server)
198
199
        if forceIPv4 and forceIPv6:
            raise Exception("Force IPv4 *or* IPv6 but not both")
200
        self.server = server
201
202
        self.servername = servername
        if self.servername is not None:
Alexandre's avatar
Alexandre committed
203
            self.check = self.servername
204
        else:
Alexandre's avatar
Alexandre committed
205
            self.check = self.server
206
207
208
        self.dot = dot
        self.verbose = verbose
        self.insecure = insecure
209

210
211
    def __str__(self):
        return self.server
212

213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
    def check_ip_address(self, addr):
        (is_addr, self.family) = is_valid_ip_address(addr)
        if not is_addr and not self.dot:
            raise Exception("%s is not IPv4 and not IPv6" % addr)
        if forceIPv4 and self.family == 6:
            raise Exception("You cannot force IPv4 with a litteral IPv6 address (%s)" % addr)
        elif forceIPv6 and self.family == 4:
            raise Exception("You cannot force IPv6 with a litteral IPv4 address (%s)" % addr)
        if forceIPv4 or self.family == 4:
            self.family = socket.AF_INET
            self.repraddress = addr
        elif forceIPv6 or self.family == 6:
            self.family = socket.AF_INET6
            self.repraddress = f'[{addr}]'
        else:
            self.family = 0

Alexandre's avatar
Alexandre committed
230
231
232
233
234
235
236
237
    def do_test(self, qname, qtype=rtype):
        # Routine doing one actual test. Returns a tuple, first member is a
        # result (boolean indicating success for DoT, HTTP status code for
        # DoH), second member is a DNS message (or a string if there is an
        # error), third member is the size of the DNS message (or None if no
        # proper response).
        pass

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
    def print_result(self, rcode, msg, size):
        ok = True
        if (self.dot and rcode) or (not self.dot and rcode == 200):
            if not monitoring:
                print(msg)
            else:
                if size is not None and size > 0:
                    print("%s OK - %s" % (self.server, "No error for %s/%s, %i bytes received" % (name, rtype, size)))
                else:
                    print("%s OK - %s" % (self.server, "No error"))
                sys.exit(STATE_OK)
        else:
            if not monitoring:
                if dot:
                    print("Error: %s" % msg, file=sys.stderr)
                else:
                   try:
                       msg = msg.decode()
                   except (UnicodeDecodeError, AttributeError):
                       pass # Sometimes, msg can be binary, or Latin-1
                   print("HTTP error %i: %s" % (rcode, msg), file=sys.stderr)
            else:
                if not dot:
                    print("%s HTTP error - %i: %s" % (self.server, rcode, msg))
                else:
                    print("%s Error - %i: %s" % (self.server, rcode, msg))
                sys.exit(STATE_CRITICAL)
            ok = False
        return ok

268
269
270
271
272
273
274

class ConnectionDoT(Connection):
    def __init__(self, server, servername=None, connect=None, forceIPv4=False, forceIPv6=False,
                 dot=False, verbose=verbose, insecure=insecure, post=post, head=head):
        Connection.__init__(self, server, servername=servername, connect=connect,
                forceIPv4=forceIPv4, forceIPv6=forceIPv6, dot=dot,
                verbose=verbose, insecure=insecure, post=post, head=head)
275
        self.check_ip_address(self.server)
276
        self.hasher = hashlib.sha256()
277
        addrinfo = socket.getaddrinfo(server, 853, self.family)
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
        # May be loop over the results of getaddrinfo, to test all
        # the IP addresses? See #13.
        self.sock = socket.socket(addrinfo[0][0], socket.SOCK_STREAM)
        self.addr = addrinfo[0][4]
        if self.verbose:
            print("Connecting to %s ..." % str(self.addr))
        # With typical DoT servers, we *must* use TLS 1.2 (otherwise,
        # do_handshake fails with "OpenSSL.SSL.SysCallError: (-1, 'Unexpected
        # EOF')" Typical HTTP servers are more lax.
        self.context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD)
        if self.insecure:
            self.context.set_verify(OpenSSL.SSL.VERIFY_NONE, lambda *x: True)
        else:
            self.context.set_default_verify_paths()
            self.context.set_verify_depth(4) # Seems ignored
            self.context.set_verify(OpenSSL.SSL.VERIFY_PEER | OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT | \
                                    OpenSSL.SSL.VERIFY_CLIENT_ONCE,
                                    lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
        self.session = OpenSSL.SSL.Connection(self.context, self.sock)
        self.session.set_tlsext_host_name(canonicalize(self.check).encode()) # Server Name Indication (SNI)
        self.session.connect((self.addr))
        # TODO We may here have exceptions such as OpenSSL.SSL.ZeroReturnError
        self.session.do_handshake()
        self.cert = self.session.get_peer_certificate()
        # RFC 7858, section 4.2 and appendix A
        self.publickey = self.cert.get_pubkey()
        if verbose:
            print("Certificate #%x for \"%s\", delivered by \"%s\"" % \
                  (self.cert.get_serial_number(),
                   self.cert.get_subject().commonName,
                   self.cert.get_issuer().commonName))
            self.hasher.update(OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_ASN1,
                                                  self.publickey))
            self.digest = self.hasher.digest()
            print("Public key is pin-sha256=\"%s\"" % \
                  base64.standard_b64encode(self.digest).decode())
        if not insecure:
            valid = validate_hostname(self.check, self.cert)
            if not valid:
                error("Certificate error: \"%s\" is not in the certificate" % (self.check))

319
    def end(self):
320
321
322
        self.session.shutdown()
        self.session.close()

Alexandre's avatar
Alexandre committed
323
324
325
326
327
328
329
330
331
332
333
334
335
336
    def do_test(self, qname, qtype=rtype):
        message = dns.message.make_query(qname, dns.rdatatype.from_text(qtype), use_edns=True, want_dnssec=True)
        messagew = message.to_wire()
        length = len(messagew)
        id = message.id
        n = self.session.send(length.to_bytes(2, byteorder='big') + messagew)
        buf = self.session.recv(2)
        received = int.from_bytes(buf, byteorder='big')
        buf = self.session.recv(received)
        response = dns.message.from_wire(buf)
        if response.id != message.id:
            raise Exception("The ID in the answer does not match the one in the query")
        return (True, response, received)

337
338
339
340
341
342
343
344
345
346

class ConnectionDoH(Connection):
    def __init__(self, server, servername=None, connect=None, forceIPv4=False, forceIPv6=False,
                 dot=False, verbose=verbose, insecure=insecure, post=post, head=head):
        Connection.__init__(self, server, servername=servername, connect=connect,
                forceIPv4=forceIPv4, forceIPv6=forceIPv6, dot=dot,
                verbose=verbose, insecure=insecure, post=post, head=head)
        self.post = post
        self.head = head
        self.url = server
347
348
349
350
351
352
        http_header = ["Content-type: application/dns-message"]
        self.curl_opt = {}
        self.curl_opt[pycurl.HTTP_VERSION] = pycurl.CURL_HTTP_VERSION_2 # Does not
            # work if pycurl was not compiled with nghttp2 (recent Debian
            # packages are OK) https://github.com/pycurl/pycurl/issues/477
        self.curl_opt[pycurl.HTTPHEADER] = http_header
353
        if self.verbose:
354
            self.curl_opt[pycurl.VERBOSE] = True
355
        if self.insecure:
356
357
            self.curl_opt[pycurl.SSL_VERIFYPEER] = False
            self.curl_opt[pycurl.SSL_VERIFYHOST] = False
358
        if forceIPv4:
359
            self.curl_opt[pycurl.IPRESOLVE] = pycurl.IPRESOLVE_V4
360
        if forceIPv6:
361
            self.curl_opt[pycurl.IPRESOLVE] = pycurl.IPRESOLVE_V6
362
        if connect is not None:
363
            self.check_ip_address(connect)
364
            self.curl_opt[pycurl.CONNECT_TO] = [f'::{self.repraddress}:443',]
365
366

    def end(self):
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
        self.request.close_handle()

    def prepare_test_get(self, qname, qtype):
        self.request = RequestDoH(qname, qtype)
        dns_req = base64.urlsafe_b64encode(self.request.data).decode('UTF8').rstrip('=')
        self.curl_opt[pycurl.URL] = self.server + ("?dns=%s" % dns_req)

    def prepare_test_post(self, qname, qtype):
        self.request = RequestDoH(qname, qtype)
        self.curl_opt[pycurl.POST] = True
        self.curl_opt[pycurl.POSTFIELDS] = self.request.data
        self.curl_opt[pycurl.URL] = self.server

    def prepare_test_head(self, qname, qtype):
        self.prepare_test_get(qname, qtype)
        self.curl_opt[pycurl.NOBODY] = True
383

Alexandre's avatar
Alexandre committed
384
385
    def do_test(self, qname, qtype=rtype):
        if self.post:
386
387
388
            self.prepare_test_post(qname, qtype)
        elif self.head:
            self.prepare_test_head(qname, qtype)
389
        else:
390
            self.prepare_test_get(qname, qtype)
391
        buffer = io.BytesIO()
392
393
394
395
396
        self.curl_opt[pycurl.WRITEDATA] = buffer
        self.request.create_handle(self.curl_opt)
        self.request.perform()
        size = None
        rcode = self.request.handle.getinfo(pycurl.RESPONSE_CODE)
397
398
        ok = True
        if rcode == 200:
399
            ctype = self.request.handle.getinfo(pycurl.CONTENT_TYPE)
400
401
402
            if ctype != "application/dns-message":
                response = "Content type of the response (\"%s\") invalid" % ctype
                ok = False
403
            else:
404
                body = buffer.getvalue()
405
406
407
408
409
410
411
412
413
                if not head:
                    try:
                        size = len(body)
                        response = dns.message.from_wire(body)
                    except dns.message.TrailingJunk: # Not DNS. Should
                        # not happen for a content type
                        # application/dns-message but who knows?
                        response = "ERROR Not proper DNS data, trailing junk \"%s\"" % body
                        ok = False
Alexandre's avatar
Alexandre committed
414
                    except dns.name.BadLabelType: # Not DNS.
415
416
417
                        response = "ERROR Not proper DNS data (wrong path in the URL?) \"%s\"" % body[:100]
                        ok = False
                else:
418
419
420
421
422
                    if len(body) == 0:
                        response = "HEAD successful"
                    else:
                        response = "ERROR Body length is not null \"%s\"" % body[:100]
                        ok = False
423
        else:
424
            ok = False
425
426
            body =  buffer.getvalue()
            if len(body) == 0:
427
428
429
430
                response = "[No details]"
            else:
                response = body
            buffer.close()
431
        return (rcode, response, size)
Alexandre's avatar
Alexandre committed
432

433
# Main program
434
435
436
437
438
439
me = os.path.basename(sys.argv[0])
monitoring = (me == "check_doh" or me == "check_dot")
if not monitoring:
    name = None
    message = None
    try:
440
441
442
        optlist, args = getopt.getopt (sys.argv[1:], "hvPkeV:r:f:d:t46",
                                       ["help", "verbose", "dot", "head", "insecure", "POST", "vhost=",
                                        "repeat=", "file=", "delay=", "v4only", "v6only"])
443
444
445
446
        for option, value in optlist:
            if option == "--help" or option == "-h":
                usage()
                sys.exit(0)
447
448
            elif option == "--dot" or option == "-t":
                dot = True
449
450
            elif option == "--verbose" or option == "-v":
                verbose = True
451
            elif option == "--HEAD" or option == "--head" or option == "-e":
452
                head = True
453
            elif option == "--POST" or option == "--post" or option == "-P":
454
                post = True
455
456
            elif option == "--vhost" or option == "-V":
                vhostname = value
457
458
            elif option == "--insecure" or option == "-k":
                insecure = True
459
460
461
462
463
464
465
466
467
468
            elif option == "--repeat" or option == "-r":
                tests = int(value)
                if tests <= 1:
                    error("--repeat needs a value > 1")
            elif option == "--delay" or option == "-d":
                delay = float(value)
                if delay <= 0:
                    error("--delay needs a value > 0")
            elif option == "--file" or option == "-f":
                ifile = value
469
470
471
472
            elif option == "-4" or option == "v4only":
                forceIPv4 = True
            elif option == "-6" or option == "v6only":
                forceIPv6 = True
473
474
475
476
477
478
479
480
481
482
483
484
            else:
                error("Unknown option %s" % option)
    except getopt.error as reason:
        usage(reason)
        sys.exit(1)
    if tests <= 1 and delay is not None:
        error("--delay makes no sense if there is no repetition")
    if post and head:
        usage("POST or HEAD but not both")
        sys.exit(1)
    if dot and (post or head):
        usage("POST or HEAD makes non sense for DoT")
Alexandre's avatar
Alexandre committed
485
        sys.exit(1)
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
    if ifile is None and (len(args) != 2 and len(args) != 3):
        usage("Wrong number of arguments")
        sys.exit(1)
    if ifile is not None and len(args) != 1:
        usage("Wrong number of arguments (if --file is used, do not indicate the domain name)")
        sys.exit(1)
    url = args[0]
    if ifile is None:
        name = args[1]
        if len(args) == 3:
            rtype = args[2]
else: # Monitoring plugin
    dot = (me == "check_dot")
    name = None
    try:
501
        optlist, args = getopt.getopt (sys.argv[1:], "H:n:p:V:t:Pih46")
502
503
504
505
        for option, value in optlist:
            if option == "-H":
                host = value
            elif option == "-V":
Alexandre's avatar
Alexandre committed
506
                vhostname = value
507
508
509
510
511
512
513
514
515
516
            elif option == "-n":
                name = value
            elif option == "-t":
                rtype = value
            elif option == "-p":
                path = value
            elif option == "-P":
                post = True
            elif option == "-h":
                head = True
517
518
            elif option == "-i":
                insecure = True
519
520
521
522
            elif option == "-4":
                forceIPv4 = True
            elif option == "-6":
                forceIPv6 = True
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
            else:
                # Should never occur, it is trapped by getopt
                print("Unknown option %s" % option)
                sys.exit(STATE_UNKNOWN)
    except getopt.error as reason:
        print("Option parsing problem %s" % reason)
        sys.exit(STATE_UNKNOWN)
    if len(args) > 0:
        print("Too many arguments (\"%s\")" % args)
        sys.exit(STATE_UNKNOWN)
    if host is None or name is None:
        print("Host (-H) and name to lookup (-n) are necessary")
        sys.exit(STATE_UNKNOWN)
    if post and head:
        print("POST or HEAD but not both")
        sys.exit(STATE_UNKNOWN)
539
540
541
542
543
544
    if dot and (post or head):
        print("POST or HEAD makes no sense for DoT")
        sys.exit(STATE_UNKNOWN)
    if dot and path:
        print("URL path makes no sense for DoT")
        sys.exit(STATE_UNKNOWN)
545
546
547
    if dot:
        url = host
    else:
548
549
        if vhostname is None or vhostname == host:
            connectTo = None
550
            url = "https://%s/" % host
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
551
        else:
552
            connectTo = host
Alexandre's avatar
Alexandre committed
553
            url = "https://%s/" % vhostname
554
555
556
557
        if path is not None:
            if path.startswith("/"):
                path = path[1:]
            url += path
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
558
ok = True
Alexandre's avatar
Alexandre committed
559
start = time.time()
560
try:
561
    if dot and vhostname is not None:
562
563
564
        extracheck = vhostname
    else:
        extracheck = None
565
566
567
568
569
570
571
572
    if dot:
        conn = ConnectionDoT(url, dot=dot, servername=extracheck, connect=connectTo, verbose=verbose,
                          forceIPv4=forceIPv4, forceIPv6=forceIPv6,
                          insecure=insecure, post=post, head=head)
    else:
        conn = ConnectionDoH(url, dot=dot, servername=extracheck, connect=connectTo, verbose=verbose,
                          forceIPv4=forceIPv4, forceIPv6=forceIPv6,
                          insecure=insecure, post=post, head=head)
573
574
except TimeoutError:
    error("timeout")
575
576
except ConnectionRefusedError:
    error("Connection to server refused")
577
578
if ifile is not None:
    input = open(ifile)
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
579
for i in range (0, tests):
580
581
582
583
584
585
586
587
588
589
590
    if tests > 1:
        print("\nTest %i" % i)
    if ifile is not None:
        line = input.readline()
        if line[:-1] == "":
            error("Not enough data in %s for the %i tests" % (ifile, tests))
        if line.find(' ') == -1:
            name = line[:-1]
            rtype = 'AAAA'
        else:
            (name, rtype) = line.split()
Alexandre's avatar
Alexandre committed
591
    (rcode, msg, size) = conn.do_test(name, rtype)
592
    ok = conn.print_result(rcode, msg, size)
593
594
    if tests > 1 and i == 0:
        start2 = time.time()
595
596
    if delay is not None:
        time.sleep(delay)
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
597
stop = time.time()
598
599
600
601
if tests > 1:
    extra = ", %.2f ms/request if we ignore the first one" % ((stop-start2)*1000/(tests-1))
else:
    extra = ""
602
603
if not monitoring:
    print("\nTotal elapsed time: %.2f seconds (%.2f ms/request %s)" % (stop-start, (stop-start)*1000/tests, extra))
604
605
if ifile is not None:
    input.close()
606
conn.end()
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
607
if ok:
608
609
610
611
    if not monitoring:
        sys.exit(0)
    else:
        sys.exit(STATE_OK)
Stephane Bortzmeyer's avatar
Stephane Bortzmeyer committed
612
else:
613
614
615
616
    if not monitoring:
        sys.exit(1)
    else:
        sys.exit(STATE_CRITICAL)
Alexandre's avatar
Alexandre committed
617