########################################################################
#
#  Copyright (C) 2009, CZ.NIC, z.s.p.o.
# 
#  This file is part of dnstester.
#
#  dnstester is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  dnstester 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 General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
########################################################################

import traceback
import dns.resolver
import config
from test import TestBoolean
import dnstests

B_domain = config.dnssec_domain
B_expected_response = '418594c5f87dcde94617b6900f723ff0'

class TestB(TestBoolean):

    def __init__(self):
        TestBoolean.__init__(self, 'B')

    def run(self):
        self.set_result(False)

        try:
            myresolver = dns.resolver.Resolver()
            try:
                dns_result = myresolver.query(B_domain, 'SOA')
            except dns.resolver.NoAnswer:
                self.msg_add("dns query no answer")
                return
            except dns.resolver.NXDOMAIN:
                self.msg_add("dns query nonexistent domain")
                return
            except dns.resolver.NoNameservers:
                self.msg_add("dns query no nameservers")
                return
            except dns.resolver.Timeout:
                self.msg_add("dns query timeout")
                return
            except dns.resolver.Truncated:
                self.msg_add("query truncated")
                return

            if len(dns_result.rrset) <> 1:
                self.msg_add("invalid number of records")
                return

            if dns_result.response.flags & dns.flags.AD:
                self.msg_add("AD flag detected (bind 9.4.1?)")
            
            hexdigest = dnstests.answer_digest(dns_result)
        
            if hexdigest <> B_expected_response:
                self.msg_add("invalid response")
                self.msg_add(str(dns_result.response))
                self.msg_add("response digest = \"%s\"" % hexdigest)
                return

            self.msg_add("pass")
            self.set_result(True)
            return

        except Exception, e:
            log = traceback.format_exc()
            self.msg_add(log)
            return
