#!/usr/bin/python3.4

# Copyright (C) 2010-2012  Internet Systems Consortium.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
# DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

import sys; sys.path.append ('/usr/lib64/python3.4/site-packages')
import bundy
import bundy.cc
import threading
import struct
import signal
from bundy.config import ModuleSpecError, ModuleCCSessionError
from bundy.server_common.datasrc_clients_mgr import DataSrcClientsMgr
from bundy.datasrc import DataSourceClient, ZoneFinder, ZoneJournalReader
from bundy.server_common.bundy_server import BUNDYServer, BUNDYServerFatal
import bundy.util.cio.socketsession
import os
from bundy.config.ccsession import *
from bundy.cc import SessionError, SessionTimeout
from bundy.statistics.dns import Counters
from bundy.notify import notify_out
import bundy.util.process
import bundy.util.traceback_handler
import fcntl
import socket
import select
import errno
import bundy.server_common.tsig_keyring

from bundy.log_messages.xfrout_messages import *

bundy.log.init("bundy-xfrout", buffer=True)
logger = bundy.log.Logger("xfrout")

# Pending system-wide debug level definitions, the ones we
# use here are hardcoded for now
DBG_PROCESS = logger.DBGLVL_TRACE_BASIC
DBG_COMMANDS = logger.DBGLVL_TRACE_DETAIL

DBG_XFROUT_TRACE = logger.DBGLVL_TRACE_BASIC

try:
    from libutil_io_python import *
    from pydnspp import *
except ImportError as e:
    # C++ loadable module may not be installed; even so the xfrout process
    # must keep running, so we warn about it and move forward.
    logger.error(XFROUT_IMPORT, str(e))

from bundy.acl.acl import ACCEPT, REJECT, DROP, LoaderError
from bundy.acl.dns import REQUEST_LOADER

bundy.util.process.rename()

def _clear_socket():
    """Common initialization/cleanup: remove the socket file, if it exists."""
    if os.path.exists(UNIX_SOCKET_FILE):
        os.remove(UNIX_SOCKET_FILE)

class XfroutConfigError(Exception):
    """An exception indicating an error in updating xfrout configuration.

    This exception is raised when the xfrout process encouters an error in
    handling configuration updates.  Not all syntax error can be caught
    at the module-CC layer, so xfrout needs to (explicitly or implicitly)
    validate the given configuration data itself.  When it finds an error
    it raises this exception (either directly or by converting an exception
    from other modules) as a unified error in configuration.
    """
    pass

class XfroutSessionError(Exception):
    '''An exception raised for some unexpected events during an xfrout session.
    '''
    pass

def init_paths():
    global SPECFILE_PATH
    global AUTH_SPECFILE_PATH
    global UNIX_SOCKET_FILE
    if "BUNDY_FROM_BUILD" in os.environ:
        SPECFILE_PATH = os.environ["BUNDY_FROM_BUILD"] + "/src/bin/xfrout"
        AUTH_SPECFILE_PATH = os.environ["BUNDY_FROM_BUILD"] + "/src/bin/auth"
        if "BUNDY_FROM_SOURCE_LOCALSTATEDIR" in os.environ:
            UNIX_SOCKET_FILE = os.environ["BUNDY_FROM_SOURCE_LOCALSTATEDIR"] + \
                "/auth_xfrout_conn"
        else:
            UNIX_SOCKET_FILE = os.environ["BUNDY_FROM_BUILD"] + "/auth_xfrout_conn"
    else:
        PREFIX = "/usr"
        DATAROOTDIR = "${prefix}/share"
        SPECFILE_PATH = "/usr/share/bundy".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
        AUTH_SPECFILE_PATH = SPECFILE_PATH
        if "BUNDY_XFROUT_SOCKET_FILE" in os.environ:
            UNIX_SOCKET_FILE = os.environ["BUNDY_XFROUT_SOCKET_FILE"]
        else:
            UNIX_SOCKET_FILE = "/var/bundy/auth_xfrout_conn"

init_paths()

SPECFILE_LOCATION = SPECFILE_PATH + "/xfrout.spec"
AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + os.sep + "auth.spec"
XFROUT_DNS_HEADER_SIZE = 12     # protocol constant
XFROUT_MAX_MESSAGE_SIZE = 65535 # ditto

# borrowed from xfrin.py @ #1298.  We should eventually unify it.
def format_zone_str(zone_name, zone_class):
    """Helper function to format a zone name and class as a string of
       the form '<name>/<class>'.
       Parameters:
       zone_name (bundy.dns.Name) name to format
       zone_class (bundy.dns.RRClass) class to format
    """
    return zone_name.to_text(True) + '/' + str(zone_class)

# borrowed from xfrin.py @ #1298.
def format_addrinfo(addrinfo):
    """Helper function to format the addrinfo as a string of the form
       <addr>:<port> (for IPv4) or [<addr>]:port (for IPv6). For unix domain
       sockets, and unknown address families, it returns a basic string
       conversion of the third element of the passed tuple.
       Parameters:
       addrinfo: a 3-tuple consisting of address family, socket type, and,
                 depending on the family, either a 2-tuple with the address
                 and port, or a filename
    """
    try:
        if addrinfo[0] == socket.AF_INET:
            return str(addrinfo[2][0]) + ":" + str(addrinfo[2][1])
        elif addrinfo[0] == socket.AF_INET6:
            return "[" + str(addrinfo[2][0]) + "]:" + str(addrinfo[2][1])
        else:
            return str(addrinfo[2])
    except IndexError:
        raise TypeError("addrinfo argument to format_addrinfo() does not "
                        "appear to be consisting of (family, socktype, (addr, port))")

# This function is not inlined as it is replaced with a mock function
# during testing.
def get_rrset_len(rrset):
    """Returns the wire length of the given RRset"""
    return rrset.get_length()

def get_soa_serial(soa_rdata):
    '''Extract the serial field of an SOA RDATA and returns it as an Serial object.
    '''
    return Serial(int(soa_rdata.to_text().split()[2]))

def make_blocking(filenum, on):
    """A helper function to change blocking mode of the given socket.

    It sets the mode of blocking I/O for the socket associated with filenum
    (descriptor of the socket) according to parameter 'on': if it's True the
    file will be made blocking; otherwise it will be made non-blocking.

    The given filenum must be a descriptor of a socket (not an ordinary file
    etc), but this function doesn't check that condition.

    filenum(int): file number (descriptor) of the socket to update.
    on(bool): whether enable (True) or disable (False) blocking I/O.

    """
    flags = fcntl.fcntl(filenum, fcntl.F_GETFL)
    if on:                      # make it blocking
        flags &= ~os.O_NONBLOCK
    else:                       # make it non blocking
        flags |= os.O_NONBLOCK
    fcntl.fcntl(filenum, fcntl.F_SETFL, flags)

class _SessionCleaner():
    """A helper for XfroutSession and XfroutResponder to clean up resources.

    Objects of these classes will instantiate this class and hold it as
    an attribute so the resources maintained in this class will be released
    in an appropriate way when the last reference to the object is released.
    This will help simplify the resource management and avoid leak since
    XfroutSession and XfroutResponder will share these resources and will be
    run on different threads.

    While it's guaranteed that the resources are automatically released
    eventually, it's generally advisable to explicitly destroy this object
    when the use of it is completed; the automatic cleanup is mainly intended
    as a safeguard against an unexpected exception.

    """
    def __init__(self, sock, xfrout_server):
        self.__sock = sock
        self.__xfrout_server = xfrout_server

    def __del__(self):
        if self.__xfrout_server is not None:
            self.__xfrout_server.decrease_transfers_counter()
        self.__sock.close()

class XfroutSession():
    """Handle a single xfrout session.

    This class is responsible for handling an xfrout session:
    - parse the query
    - authenticate the client
    - build response
    - send response
    The latter half, which can be time consuming and/or involve blocking
    operations, is delegated to a helper class, XfroutResponder.

    """
    def __init__(self, sock, request_data, server, tsig_key_ring, remote,
                 default_acl, zone_config, counters):
        self._sock = sock
        self._request_data = request_data
        self._server = server
        self._tsig_key_ring = tsig_key_ring
        self._tsig_ctx = None
        self._tsig_len = 0
        self._remote = remote
        self._request_type = None
        self._request_typestr = None
        self._acl = default_acl
        self._zone_config = zone_config
        self._soa = None # will be set in _xfrout_setup or in tests
        self._iterator = None # will be set to an iterator to build response
        self._jnl_reader = None # will be set to a reader for IXFR
        # Creation of self.counters should be done before of
        # invoking self._handle()
        self._counters = counters
        self.__cleaner = None

        # Now handle the xfr query.
        self._handle()

    def create_tsig_ctx(self, tsig_record, tsig_key_ring):
        return TSIGContext(tsig_record.get_name(),
                           tsig_record.get_rdata().get_algorithm(),
                           tsig_key_ring)

    def _handle(self):
        """Handle a xfrout query, initiate sending xfrout response(s).

        This is separated from the constructor so that we can override
        it from tests.

        """
        # Check the xfrout quota, and setup _SessionCleaner to make sure
        # necessary cleanup is performed no matter how the session is completed.
        quota_ok = self._server.increase_transfers_counter()
        self.__cleaner = _SessionCleaner(self._sock,
                                         self._server if quota_ok else None)
        try:
            self.dns_xfrout_start(self._request_data, quota_ok)
        except Exception as e:
            logger.error(XFROUT_HANDLE_QUERY_ERROR, e)

        self.__cleaner = None

    def _check_request_tsig(self, msg, request_data):
        ''' If request has a tsig record, perform tsig related checks '''
        tsig_record = msg.get_tsig_record()
        if tsig_record is not None:
            self._tsig_len = tsig_record.get_length()
            self._tsig_ctx = self.create_tsig_ctx(tsig_record,
                                                  self._tsig_key_ring)
            tsig_error = self._tsig_ctx.verify(tsig_record, request_data)
            if tsig_error != TSIGError.NOERROR:
                return Rcode.NOTAUTH

        return Rcode.NOERROR

    def _parse_query_message(self, mdata):
        ''' parse query message to [socket,message]'''
        #TODO, need to add parseHeader() in case the message header is invalid
        try:
            msg = Message(Message.PARSE)
            Message.from_wire(msg, mdata)
        except Exception as err: # Exception is too broad
            logger.error(XFROUT_PARSE_QUERY_ERROR, err)
            return Rcode.FORMERR, None

        # TSIG related checks
        rcode = self._check_request_tsig(msg, mdata)
        if rcode != Rcode.NOERROR:
            return rcode, msg

        # Make sure the question is valid.  This should be ensured by
        # the auth server, but since it's far from xfrout itself, we check
        # it by ourselves.  A viloation would be an internal bug, so we
        # raise and stop here rather than returning a FORMERR or SERVFAIL.
        if msg.get_rr_count(Message.SECTION_QUESTION) != 1:
            raise RuntimeError('Invalid number of question for XFR: ' +
                               str(msg.get_rr_count(Message.SECTION_QUESTION)))
        question = msg.get_question()[0]

        # Identify the request type
        self._request_type = question.get_type()
        if self._request_type == RRType.AXFR:
            self._request_typestr = 'AXFR'
        elif self._request_type == RRType.IXFR:
            self._request_typestr = 'IXFR'
        else:
            # Likewise, this should be impossible.
            raise RuntimeError('Unexpected XFR type: ' +
                               str(self._request_type))

        # ACL checks
        zone_name = question.get_name()
        zone_class = question.get_class()
        acl = self._get_transfer_acl(zone_name, zone_class)
        acl_result = acl.execute(
            bundy.acl.dns.RequestContext(self._remote[2], msg.get_tsig_record()))
        if acl_result == DROP:
            logger.debug(DBG_XFROUT_TRACE, XFROUT_QUERY_DROPPED,
                         self._request_type, format_addrinfo(self._remote),
                         format_zone_str(zone_name, zone_class))
            return None, None
        elif acl_result == REJECT:
            # count rejected Xfr request by each zone name
            self._counters.inc('zones', zone_class.to_text(),
                               zone_name.to_text(), 'xfrrej')
            logger.debug(DBG_XFROUT_TRACE, XFROUT_QUERY_REJECTED,
                         self._request_type, format_addrinfo(self._remote),
                         format_zone_str(zone_name, zone_class))
            return Rcode.REFUSED, msg

        return rcode, msg

    def _get_transfer_acl(self, zone_name, zone_class):
        '''Return the ACL that should be applied for a given zone.

        The zone is identified by a tuple of name and RR class.
        If a per zone configuration for the zone exists and contains
        transfer_acl, that ACL will be used; otherwise, the default
        ACL will be used.

        '''
        # Internally zone names are managed in lower cased label characters,
        # so we first need to convert the name.
        zone_name_lower = Name(zone_name.to_text(), True)
        config_key = (zone_class.to_text(), zone_name_lower.to_text())
        if config_key in self._zone_config and \
                'transfer_acl' in self._zone_config[config_key]:
            return self._zone_config[config_key]['transfer_acl']
        return self._acl

    def _reply_with_error_rcode(self, msg, rcode):
        if not msg:
            return # query message is invalid. send nothing back.

        responder = XfroutResponder(self._sock, self._server, self._tsig_ctx,
                                    self.__cleaner)

        # Start a thread that sends the resposne.  We'll make it as
        # a daemon thread so if the main thread dies unexpectedly the
        # child thread will be automatically killed.
        th = threading.Thread(target=responder.respond_with_rcode,
                              args=(msg, rcode))
        th.daemon = True
        th.start()

    def _get_zone_soa(self, finder, zone_name):
        """Retrieve the SOA RR of the given zone.

        It returns a pair of RCODE and the SOA (in the form of RRset).
        On success RCODE is NOERROR and returned SOA is not None;
        on failure RCODE indicates the appropriate code in the context of
        xfr processing, and the returned SOA is None.
        """
        result, soa_rrset, _ = finder.find(zone_name, RRType.SOA)
        if result != ZoneFinder.SUCCESS:
            return (Rcode.SERVFAIL, None)
        # Especially for database-based zones, a working zone may be in
        # a broken state where it has more than one SOA RR.  We proactively
        # check the condition and abort the xfr attempt if we identify it.
        if soa_rrset.get_rdata_count() != 1:
            return (Rcode.SERVFAIL, None)
        return (Rcode.NOERROR, soa_rrset)

    def __axfr_setup(self, zone_name, datasrc_client):
        """Setup a zone iterator for AXFR or AXFR-style IXFR."""
        try:
            # Note that we enable 'separate_rrs'.  In xfr-out we need to
            # preserve as many things as possible (even if it's half broken)
            # stored in the zone.
            self._iterator = datasrc_client.get_iterator(zone_name, True)
        except bundy.datasrc.Error:
            # If the current name server does not have authority for the
            # zone, xfrout can't serve for it, return rcode NOTAUTH.
            # Note: this exception can happen for other reasons.  We should
            # update get_iterator() API so that we can distinguish "no such
            # zone" and other cases (#1373).  For now we consider all these
            # cases as NOTAUTH.
            return Rcode.NOTAUTH

        # If we are an authoritative name server for the zone, but fail
        # to find the zone's SOA record in datasource, xfrout can't
        # provide zone transfer for it.
        self._soa = self._iterator.get_soa()
        if self._soa is None or self._soa.get_rdata_count() != 1:
            return Rcode.SERVFAIL

        return Rcode.NOERROR

    def __ixfr_setup(self, request_msg, zone_name, zone_class, datasrc_client,
                     finder):
        '''Setup a zone journal reader for IXFR.

        If the underlying data source does not know the requested range
        of zone differences it automatically falls back to AXFR-style
        IXFR by setting up a zone iterator instead of a journal reader.

        '''
        # Check the authority section.  Look for a SOA record with
        # the same name and class as the question.
        remote_soa = None
        for auth_rrset in request_msg.get_section(Message.SECTION_AUTHORITY):
            # Ignore data whose owner name is not the zone apex, and
            # ignore non-SOA or different class of records.
            if auth_rrset.get_name() != zone_name or \
                    auth_rrset.get_type() != RRType.SOA or \
                    auth_rrset.get_class() != zone_class:
                continue
            if auth_rrset.get_rdata_count() != 1:
                logger.info(XFROUT_IXFR_MULTIPLE_SOA,
                            format_addrinfo(self._remote))
                return Rcode.FORMERR
            remote_soa = auth_rrset
        if remote_soa is None:
            logger.info(XFROUT_IXFR_NO_SOA, format_addrinfo(self._remote))
            return Rcode.FORMERR

        # Retrieve the local SOA
        rcode, self._soa = self._get_zone_soa(finder, zone_name)
        if rcode != Rcode.NOERROR:
            return rcode

        # RFC1995 says "If an IXFR query with the same or newer version
        # number than that of the server is received, it is replied to with
        # a single SOA record of the server's current version, just as
        # in AXFR".  The claim about AXFR is incorrect, but other than that,
        # we do as the RFC says.
        begin_serial = get_soa_serial(remote_soa.get_rdata()[0])
        end_serial = get_soa_serial(self._soa.get_rdata()[0])
        if begin_serial >= end_serial:
            # clear both iterator and jnl_reader to signal we won't do
            # iteration in response generation
            self._iterator = None
            self._jnl_reader = None
            logger.info(XFROUT_IXFR_UPTODATE, format_addrinfo(self._remote),
                        format_zone_str(zone_name, zone_class),
                        begin_serial, end_serial)
            return Rcode.NOERROR

        # Set up the journal reader or fall back to AXFR-style IXFR
        try:
            code, self._jnl_reader = datasrc_client.get_journal_reader(
                zone_name, begin_serial.get_value(), end_serial.get_value())
        except bundy.datasrc.NotImplemented as ex:
            # The underlying data source doesn't support journaling.
            # Fall back to AXFR-style IXFR.
            logger.info(XFROUT_IXFR_NO_JOURNAL_SUPPORT,
                        format_addrinfo(self._remote),
                        format_zone_str(zone_name, zone_class))
            return self.__axfr_setup(zone_name, datasrc_client)
        if code == ZoneJournalReader.NO_SUCH_VERSION:
            logger.info(XFROUT_IXFR_NO_VERSION, format_addrinfo(self._remote),
                        format_zone_str(zone_name, zone_class),
                        begin_serial, end_serial)
            return self.__axfr_setup(zone_name, datasrc_client)
        if code == ZoneJournalReader.NO_SUCH_ZONE:
            # this is quite unexpected as we know zone's SOA exists.
            # It might be a bug or the data source is somehow broken,
            # but it can still happen if someone has removed the zone
            # between these two operations.  We treat it as NOTAUTH.
            logger.warn(XFROUT_IXFR_NO_ZONE, format_addrinfo(self._remote),
                        format_zone_str(zone_name, zone_class))
            return Rcode.NOTAUTH

        # Use the reader as the iterator to generate the response.
        self._iterator = self._jnl_reader

        return Rcode.NOERROR

    def _xfrout_setup(self, request_msg, zone_name, zone_class):
        """Setup a context for xfr responses according to the request type.

        This method identifies the most appropriate data source for the
        request and set up a zone iterator or journal reader depending on
        whether the request is AXFR or IXFR.  If it identifies any protocol
        level error it returns an RCODE other than NOERROR.
        """
        # Identify the data source for the requested zone of the requested
        # RR class.  If not found, return NOTAUTH as described in RFC5936.
        _, clients_map = self._server._datasrc_clients_mgr.get_clients_map()
        clist = clients_map.get(zone_class)
        if clist is None:
            return Rcode.NOTAUTH
        datasrc_client, finder, _ = clist.find(zone_name, True, True)
        if datasrc_client is None:
            return Rcode.NOTAUTH
        if self._request_type == RRType.AXFR:
            return self.__axfr_setup(zone_name, datasrc_client)
        else:
            return self.__ixfr_setup(request_msg, zone_name, zone_class,
                                     datasrc_client, finder)

    def dns_xfrout_start(self, msg_query, quota_ok=True):
        rcode_, msg = self._parse_query_message(msg_query)
        #TODO. create query message and parse header
        if rcode_ is None: # Dropped by ACL
            return
        elif rcode_ == Rcode.NOTAUTH or rcode_ == Rcode.REFUSED:
            return self._reply_with_error_rcode(msg, rcode_)
        elif rcode_ != Rcode.NOERROR:
            return self._reply_with_error_rcode(msg, Rcode.FORMERR)
        elif not quota_ok:
            logger.warn(XFROUT_QUERY_QUOTA_EXCEEDED, self._request_typestr,
                        format_addrinfo(self._remote),
                        self._server._max_transfers_out)
            return self._reply_with_error_rcode(msg, Rcode.REFUSED)

        question = msg.get_question()[0]
        zone_name = question.get_name()
        zone_class = question.get_class()
        zone_str = format_zone_str(zone_name, zone_class) # for logging

        try:
            rcode_ = self._xfrout_setup(msg, zone_name, zone_class)
        except Exception as ex:
            logger.error(XFROUT_XFR_TRANSFER_CHECK_ERROR, self._request_typestr,
                         format_addrinfo(self._remote), zone_str, ex)
            rcode_ = Rcode.SERVFAIL
        if rcode_ != Rcode.NOERROR:
            logger.info(XFROUT_XFR_TRANSFER_FAILED, self._request_typestr,
                        format_addrinfo(self._remote), zone_str, rcode_)
            return self._reply_with_error_rcode(msg, rcode_)

        responder = XfroutResponder(self._sock, self._server,
                                    self._tsig_ctx, self.__cleaner,
                                    self._remote, zone_name,
                                    zone_class, self._request_type,
                                    self._soa, self._iterator,
                                    self._jnl_reader, self._tsig_len)
        th = threading.Thread(target=responder.respond, args=(msg,))
        th.daemon = True
        th.start()

class XfroutResponder():
    """Build and send an xfr response.

    This is a helper class of XfroutSession, and deals with time consuming
    operations (iterating over possibly large zone data and sending it
    to the client).

    """
    def __init__(self, sock, server, tsig_ctx, session_cleaner, *opt_args):
        """Constructor.

        XfroutResponder can be constructed for both normal and error responses.
        For normal responses 'opt_args' will contain other information to
        build the response.

        """
        # The class attributes are essentially private, but most of them are
        # defined as 'protected' so test code can inspect or tweak them.
        if opt_args:
            (self.__remote,     # tuple: see format_addrinfo()
             self.__zone_name,  # dns.Name, the zone name to be transferred
             self.__zone_class, # dns.RRClass, the RR class of the zone
             self.__req_type,   # dns.RRType: either AXFR or IXFR
             self._soa,
             self._iterator,
             self._jnl_reader,
             self._tsig_len) = opt_args
        self._sock = sock
        self.__server = server
        self.__session_cleaner = session_cleaner
        self._tsig_ctx = tsig_ctx
        self.__counters = self.__server._counters

        # Before start, make sure the socket uses blocking I/O because
        # responses will be sent in the blocking mode; otherwise it could
        # result in EWOULDBLOCK and disrupt the session.
        make_blocking(self._sock.fileno(), True)

    def _send_data(self, data):
        size = len(data)
        total_count = 0
        while total_count < size:
            count = self._sock.send(data[total_count:])
            total_count += count

    def _send_message(self, msg, tsig_ctx=None):
        render = MessageRenderer()
        # As defined in RFC5936 section3.4, perform case-preserving name
        # compression for AXFR message.
        render.set_compress_mode(MessageRenderer.CASE_SENSITIVE)
        render.set_length_limit(XFROUT_MAX_MESSAGE_SIZE)

        msg.to_wire(render, tsig_ctx)

        header_len = struct.pack('H', socket.htons(render.get_length()))
        self._send_data(header_len)
        self._send_data(render.get_data())

    def _clear_message(self, msg):
        qid = msg.get_qid()
        opcode = msg.get_opcode()
        rcode = msg.get_rcode()

        msg.clear(Message.RENDER)
        msg.set_qid(qid)
        msg.set_opcode(opcode)
        msg.set_rcode(rcode)
        msg.set_header_flag(Message.HEADERFLAG_AA)
        msg.set_header_flag(Message.HEADERFLAG_QR)
        return msg

    def respond_with_rcode(self, msg, rcode):
        msg.make_response()
        msg.set_rcode(rcode)
        self._send_message(msg, self._tsig_ctx)
        self.__session_cleaner = None

    def __update_running_counter(self, update_fn, req_type):
        update_fn('axfr_running' if req_type == RRType.AXFR else 'ixfr_running')

    def respond(self, msg):
        """Public interface to building and sending a normal response."""
        zone_str = format_zone_str(self.__zone_name, self.__zone_class)
        logger.info(XFROUT_XFR_TRANSFER_STARTED, self.__req_type,
                    format_addrinfo(self.__remote), zone_str)

        self.__update_running_counter(self.__counters.inc, self.__req_type)
        try:
            self._do_respond(msg)
        except Exception as err:
            # count unixsockets send errors
            self.__counters.inc('socket', 'unixdomain', 'senderr')
            logger.error(XFROUT_XFR_TRANSFER_ERROR, self.__req_type,
                    format_addrinfo(self.__remote), zone_str, err)

        self.__update_running_counter(self.__counters.dec, self.__req_type)
        self.__counters.inc('zones', self.__zone_class.to_text(),
                            self.__zone_name.to_text(), 'xfrreqdone')
        logger.info(XFROUT_XFR_TRANSFER_DONE, self.__req_type,
                    format_addrinfo(self.__remote), zone_str)
        self.__session_cleaner = None

    def _do_respond(self, msg):
        """Perform actual job of building and sending a normal response.

        This is essentially a dedicated private subroutine of respond(),
        but defined as 'protected' so tests can replace it.

        """
        msg.make_response()
        msg.set_header_flag(Message.HEADERFLAG_AA)
        # Reserved space for the fixed header size, the size of the question
        # section, and TSIG size (when included).  The size of the question
        # section is the sum of the qname length and the size of the
        # fixed-length fields (type and class, 2 bytes each).
        message_upper_len = XFROUT_DNS_HEADER_SIZE + \
            msg.get_question()[0].get_name().get_length() + 4 + \
            self._tsig_len

        # If the iterator is None, we are responding to IXFR with a single
        # SOA RR.
        if self._iterator is None:
            self._send_message_with_last_soa(msg, self._soa, message_upper_len)
            return

        # Add the beginning SOA
        msg.add_rrset(Message.SECTION_ANSWER, self._soa)
        message_upper_len += get_rrset_len(self._soa)

        # Add the rest of the zone/diff contets
        for rrset in self._iterator:
            # Check if xfrout is shutdown
            if  self.__server._shutdown_event.is_set():
                logger.info(XFROUT_STOPPING)
                return

            # For AXFR (or AXFR-style IXFR), in which case _jnl_reader is None,
            # we should skip SOAs from the iterator.
            if self._jnl_reader is None and rrset.get_type() == RRType.SOA:
                continue

            # We calculate the maximum size of the RRset (i.e. the
            # size without compression) and use that to see if we
            # may have reached the limit
            rrset_len = get_rrset_len(rrset)

            if message_upper_len + rrset_len <= XFROUT_MAX_MESSAGE_SIZE:
                msg.add_rrset(Message.SECTION_ANSWER, rrset)
                message_upper_len += rrset_len
                continue

            # RR would not fit.  If there are other RRs in the buffer, send
            # them now and leave this RR to the next message.
            self._send_message(msg, self._tsig_ctx)

            # Create a new message and reserve space for the carried-over
            # RR (and TSIG space in case it's to be TSIG signed)
            msg = self._clear_message(msg)
            message_upper_len = XFROUT_DNS_HEADER_SIZE + rrset_len + \
                self._tsig_len

            # If this RR overflows the buffer all by itself, fail.  In theory
            # some RRs might fit in a TCP message when compressed even if they
            # do not fit when uncompressed, but surely we don't want to send
            # such monstrosities to an unsuspecting slave.
            if message_upper_len > XFROUT_MAX_MESSAGE_SIZE:
                raise XfroutSessionError('RR too large for zone transfer (' +
                                         str(rrset_len) + ' bytes)')

            # Add the RRset to the new message
            msg.add_rrset(Message.SECTION_ANSWER, rrset)

        # Add and send the trailing SOA
        self._send_message_with_last_soa(msg, self._soa, message_upper_len)

    def _send_message_with_last_soa(self, msg, rrset_soa, message_upper_len):
        '''Add the SOA record to the end of message.

        If it would exceed the maximum allowable size of a message, a new
        message will be created to send out the last SOA.

        We assume a message with a single SOA can always fit the buffer
        with or without TSIG.  In theory this could be wrong if TSIG is
        stupidly large, but in practice this assumption should be reasonable.
        '''
        if message_upper_len + get_rrset_len(rrset_soa) > \
                XFROUT_MAX_MESSAGE_SIZE:
            self._send_message(msg, self._tsig_ctx)
            msg = self._clear_message(msg)

        msg.add_rrset(Message.SECTION_ANSWER, rrset_soa)
        self._send_message(msg, self._tsig_ctx)

class XfroutServer(BUNDYServer):
    """The top-level server class for Xfrout.

    This class handles xfrout command and configuration updates, accepts
    xfr queries through UNIX domain sockets, and manages sub threads that
    actually handle the queries.

    """
    def __init__(self):
        BUNDYServer.__init__(self)

        self._default_notify_address = ''
        self._default_notify_port = 53

        self.__lock = threading.Lock() # private

        # shared with child threads
        self._shutdown_event = threading.Event()

        # Rest of the "protected" attributes are essentially private, but
        # we allow tests to inspect/tweat them.
        self._transfers_counter = 0
        self._config_data = None
        self._zone_config = {}
        self._acl = None # this will be initialized in update_config_data()
        self._counters = Counters(SPECFILE_LOCATION)
        self._notifier = None
        self._datasrc_clients_mgr = DataSrcClientsMgr()

        # List of the session receivers where we get the requests
        self._socksession_receivers = {}

        self._setup_listen_socket(UNIX_SOCKET_FILE)

    def _setup_listen_socket(self, sock_file):
        """Set up a UNIX domain socket to receive forwarded xfr queries."""
        self._remove_unused_sock_file(sock_file)
        self._listen_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            self._listen_socket.bind(sock_file)
        except:                 # catch it just for statistics
            self._counters.inc('socket', 'unixdomain', 'bindfail')
            raise
        self._listen_socket.listen(16)
        self._counters.inc('socket', 'unixdomain', 'open')
        self.watch_fileno(self._listen_socket, self._accept_forwarder)

    def _remove_unused_sock_file(self, sock_file):
        """Try to remove the given socket file.

        If the file is being used by one running xfrout process, exit from
        python. If it's not a socket file or nobody is listening,
        it will be removed. If it can't be removed, exit from python.

        """
        if self._sock_file_in_use(sock_file):
            logger.error(XFROUT_UNIX_SOCKET_FILE_IN_USE, sock_file)
            sys.exit(0)
        else:
            if not os.path.exists(sock_file):
                return
            try:
                os.unlink(sock_file)
            except OSError as err:
                logger.error(XFROUT_REMOVE_OLD_UNIX_SOCKET_FILE_ERROR,
                             sock_file, str(err))
                sys.exit(0)

    def _sock_file_in_use(self, sock_file):
        """Check whether the socket file 'sock_file' exists and
        is being used by one running xfrout process. If it is,
        return True, or else return False.

        """
        sock = socket.socket(socket.AF_UNIX)
        try:
            sock.connect(sock_file)
        except socket.error:
            return False
        else:
            return True
        finally:
            sock.close()

    def _setup_module(self):
        """Override the BUNDYServer default.

        Some of the setups in this method can fail, but we generally consider
        it a fatal system error and let the process die.

        """
        # We should be reasonably able to assume this to succeed (see xfrin)
        self.mod_ccsession.add_remote_config_by_name(
            'data_sources', self._datasrc_config_handler)
        self.mod_ccsession.add_remote_config(AUTH_SPECFILE_LOCATION)
        bundy.server_common.tsig_keyring.init_keyring(self.mod_ccsession)
        self.__start_notifier()
        logger.debug(DBG_PROCESS, XFROUT_STARTED)

    def _datasrc_config_handler(self, new_config, config_data):
        """Callback of data_sources configuration update.

        This method must be exception free, so we catch all expected
        exceptions internally; unexpected ones should mean a programming
        error and will terminate the program.

        """
        try:
            self._datasrc_clients_mgr.reconfigure(new_config, config_data)
            genid = self._datasrc_clients_mgr.get_clients_map()[0]
            logger.info(XFROUT_DATASRC_RECONFIGURED, genid)
        except bundy.server_common.datasrc_clients_mgr.ConfigError as ex:
            logger.error(XFROUT_DATASRC_CONFIG_ERROR, ex)

    def __start_notifier(self):
        """Subroutine of _setup_module, init and start NotifyOut thread."""
        datasrc = self.get_db_file()
        self._notifier = notify_out.NotifyOut(datasrc, counters=self._counters)
        if 'also_notify' in self._config_data:
            for slave in self._config_data['also_notify']:
                address = self._default_notify_address
                if 'address' in slave:
                    address = slave['address']
                port = self._default_notify_port
                if 'port' in slave:
                    port = slave['port']
                self._notifier.add_slave(address, port)

        # We'll make the notifier thread a daemon in case the main thread
        # dies without a proper shutdown, in which case we'd rather like
        # the notifier to die, too.
        self._notifier.dispatcher(True)

    def _shutdown_module(self):
        """Override the BUNDYServer default.

        We don't expect this method to raise an exception.  If it does,
        that's basically a program error and make the process terminate
        in a non-graceful manner.

        """
        self._listen_socket.close()
        self._counters.inc('socket', 'unixdomain', 'close')
        try:
            os.unlink(UNIX_SOCKET_FILE)
        except Exception as e:
            logger.error(XFROUT_REMOVE_UNIX_SOCKET_FILE_ERROR, UNIX_SOCKET_FILE,
                         e)
        self._shutdown_event.set()
        self._notifier.shutdown()
        self._wait_for_threads()

    def _wait_for_threads(self):
        # Wait for all threads to terminate. this is a call that is only used
        # in _shutdown_module(), but it has its own method, so we can test
        # _shutdown_module() without involving thread operations (the test
        # would override this method)
        main_thread = threading.currentThread()
        for th in threading.enumerate():
            if th is main_thread:
                continue
            th.join()

    def _mod_command_handler(self, cmd, args):
        """Command handler: overriding the BUNDYServer default."""
        if cmd == "notify":
            zone_name = args.get('zone_name')
            zone_class = args.get('zone_class')
            if not zone_class:
                zone_class = str(RRClass.IN)
            if zone_name:
                # log this at a debug level; this can be too noisy if DDNS
                # is busy running.
                logger.debug(DBG_XFROUT_TRACE, XFROUT_NOTIFY_COMMAND, zone_name,
                             zone_class)
                if self._notifier.send_notify(zone_name, zone_class):
                    answer = create_answer(0)
                else:
                    zonestr = notify_out.format_zone_str(Name(zone_name),
                                                         zone_class)
                    answer = create_answer(1, "Unknown zone: " + zonestr)
            else:
                answer = create_answer(1, "Bad command parameter: " + str(args))

        # return statistics data to the stats daemon
        elif cmd == "getstats":
            # The log level is here set to debug in order to avoid
            # that a log becomes too verbose. Because the bundy-stats
            # daemon is periodically asking to the bundy-xfrout daemon.
            answer = create_answer(0, self._counters.get_statistics())
            logger.debug(DBG_XFROUT_TRACE, XFROUT_RECEIVED_GETSTATS_COMMAND,
                         str(answer))
        else:
            answer = create_answer(1, "Unknown command:" + str(cmd))

        return answer

    def _config_handler(self, new_config):
        """Config handler: a mandatory method to implement for BUNDYServer.

        TODO. Do error check

        """
        answer = create_answer(0)
        if self._config_data is None:
            new_config = self.mod_ccsession.get_full_config()
            self._config_data = new_config
        else:
            for key in new_config:
                if key not in self._config_data:
                    answer = create_answer(1, "Unknown config data: " +
                                           str(key))
                    continue
                self._config_data[key] = new_config[key]
        try:
            self.__update_config_data(self._config_data)
        except Exception as e:
            answer = create_answer(1, "Failed to handle new configuration: " +
                                   str(e))
        return answer

    def __update_config_data(self, new_config):
        """Apply the new config setting of xfrout module."""
        with self.__lock:
            logger.info(XFROUT_NEW_CONFIG)
            new_acl = self._acl
            if 'transfer_acl' in new_config:
                try:
                    new_acl = REQUEST_LOADER.load(new_config['transfer_acl'])
                except LoaderError as e:
                    raise XfroutConfigError('Failed to parse transfer_acl: ' +
                                            str(e))

            new_zone_config = self._zone_config
            zconfig_data = new_config.get('zone_config')
            if zconfig_data is not None:
                new_zone_config = self.__create_zone_config(zconfig_data)

            self._acl = new_acl
            self._zone_config = new_zone_config
            self._max_transfers_out = new_config.get('transfers_out')
        logger.info(XFROUT_NEW_CONFIG_DONE)

    def __create_zone_config(self, zone_config_list):
        new_config = {}
        for zconf in zone_config_list:
            # convert the class, origin (name) pair.  First build pydnspp
            # object to reject invalid input.
            zclass_str = zconf.get('class')
            if zclass_str is None:
                zclass_str = self.mod_ccsession.get_default_value(
                    'zone_config/class')
            zclass = RRClass(zclass_str)
            zorigin = Name(zconf['origin'], True)
            config_key = (zclass.to_text(), zorigin.to_text())

            # reject duplicate config
            if config_key in new_config:
                raise XfroutConfigError('Duplicate zone_config for ' +
                                        str(zorigin) + '/' + str(zclass))

            # create a new config entry, build any given (and known) config
            new_config[config_key] = {}
            if 'transfer_acl' in zconf:
                try:
                    new_config[config_key]['transfer_acl'] = \
                        REQUEST_LOADER.load(zconf['transfer_acl'])
                except LoaderError as e:
                    raise XfroutConfigError('Failed to parse transfer_acl ' +
                                            'for ' + zorigin.to_text() + '/' +
                                            zclass_str + ': ' + str(e))
        return new_config

    def get_db_file(self):
        file, is_default = self.mod_ccsession.get_remote_config_value(
            "Auth", "database_file")
        # this too should be unnecessary, but currently the
        # 'from build' override isn't stored in the config
        # (and we don't have indirect python access to datasources yet)
        if is_default and "BUNDY_FROM_BUILD" in os.environ:
            file = os.environ["BUNDY_FROM_BUILD"] + os.sep + \
                   "bundy_zones.sqlite3"
        return file

    def increase_transfers_counter(self):
        """Return if an incoming xfr query can be handled in terms of quota."""
        ret = False
        with self.__lock:
            if self._transfers_counter < self._max_transfers_out:
                self._transfers_counter += 1
                ret = True
        return ret

    def decrease_transfers_counter(self):
        """Called on completion of xfr query, release corresponding quota."""
        with self.__lock:
            self._transfers_counter -= 1

    def _accept_forwarder(self):
        """Accept a new socket session forwarder on the UNIX domain socket."""
        try:
            (sock, remote_addr) = self._listen_socket.accept()
            fileno = sock.fileno()
            logger.debug(DBG_XFROUT_TRACE, XFROUT_NEW_FORWARDER, fileno,
                         remote_addr if remote_addr else '<anonymous address>')
            receiver = bundy.util.cio.socketsession.SocketSessionReceiver(sock)
            self._socksession_receivers[fileno] = (sock, receiver)
            self.watch_fileno(fileno, lambda: self._handle_request(fileno))
            self._counters.inc('socket', 'unixdomain', 'accept')
        except (socket.error, bundy.util.cio.socketsession.SocketSessionError) \
            as e:
            # These exceptions mean the connection didn't work, but we can
            # continue with the rest
            logger.error(XFROUT_ACCEPT_FAILURE, e)
            self._counters.inc('socket', 'unixdomain', 'acceptfail')

    def _handle_request(self, fileno):
        """Callback on a sock session receiver for a new xfr query."""
        logger.debug(DBG_XFROUT_TRACE, XFROUT_REQUEST, fileno)

        # In the context, if we are here we should have a receiver for
        # 'fileno', so this code shouldn't fail:
        (session_socket, receiver) = self._socksession_receivers[fileno]

        try:
            req_session = receiver.pop()
        except bundy.util.cio.socketsession.SocketSessionError as se:
            # No matter why this failed, the connection is in unknown, possibly
            # broken state. So, we close the socket and remove the receiver.
            del self._socksession_receivers[fileno]
            session_socket.close()
            self.unwatch_fileno(fileno, True, False, False)
            logger.warn(XFROUT_DROP_FORWARDER, fileno, se)
            self._counters.inc('socket', 'unixdomain', 'recverr')
            return

        try:
            # The forwarder side should have filtered out non-TCP session,
            # so this should be basically impossible.
            if req_session[0].proto != socket.IPPROTO_TCP:
                raise XfroutSessionError('unexpected session protocol: %d' %
                                         req_session[0].proto)
            (sock, local_addr, remote_addr, req_data) = req_session
        except Exception as ex:
            req_session[0].close()
            logger.error(XFROUT_REQUEST_FAIL, ex)
            return

        # XfroutSession ctor is basically exception free, and takes care of any
        # cleanup on failure, so we just construct it.  The constructor will
        # complete the request (by delegating the sending of the response to
        # a separate thread).
        remote = (sock.family, sock.type, remote_addr)
        XfroutSession(sock, req_data, self,
                      bundy.server_common.tsig_keyring.get_keyring(),
                      remote, self._acl, self._zone_config, self._counters)

def main():
    exit_code = XfroutServer().run('xfrout')
    logger.info(XFROUT_EXITING)
    sys.exit(exit_code)

if '__main__' == __name__:
    bundy.util.traceback_handler.traceback_handler(main)
