xfrout.py.in 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  1. #!@PYTHON@
  2. # Copyright (C) 2010-2012 Internet Systems Consortium.
  3. #
  4. # Permission to use, copy, modify, and distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  9. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  10. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  11. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  12. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  13. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  14. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  15. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. import sys; sys.path.append ('@@PYTHONPATH@@')
  17. import isc
  18. import isc.cc
  19. import threading
  20. import struct
  21. import signal
  22. from isc.datasrc import DataSourceClient, ZoneFinder, ZoneJournalReader
  23. from socketserver import *
  24. import os
  25. from isc.config.ccsession import *
  26. from isc.cc import SessionError, SessionTimeout
  27. from isc.statistics.dns import Counters
  28. from isc.notify import notify_out
  29. import isc.util.process
  30. import isc.util.traceback_handler
  31. import fcntl
  32. import socket
  33. import select
  34. import errno
  35. from optparse import OptionParser, OptionValueError
  36. from isc.util import socketserver_mixin
  37. import isc.server_common.tsig_keyring
  38. from isc.log_messages.xfrout_messages import *
  39. isc.log.init("b10-xfrout", buffer=True)
  40. logger = isc.log.Logger("xfrout")
  41. # Pending system-wide debug level definitions, the ones we
  42. # use here are hardcoded for now
  43. DBG_PROCESS = logger.DBGLVL_TRACE_BASIC
  44. DBG_COMMANDS = logger.DBGLVL_TRACE_DETAIL
  45. DBG_XFROUT_TRACE = logger.DBGLVL_TRACE_BASIC
  46. try:
  47. from libutil_io_python import *
  48. from pydnspp import *
  49. except ImportError as e:
  50. # C++ loadable module may not be installed; even so the xfrout process
  51. # must keep running, so we warn about it and move forward.
  52. logger.error(XFROUT_IMPORT, str(e))
  53. from isc.acl.acl import ACCEPT, REJECT, DROP, LoaderError
  54. from isc.acl.dns import REQUEST_LOADER
  55. isc.util.process.rename()
  56. class XfroutConfigError(Exception):
  57. """An exception indicating an error in updating xfrout configuration.
  58. This exception is raised when the xfrout process encouters an error in
  59. handling configuration updates. Not all syntax error can be caught
  60. at the module-CC layer, so xfrout needs to (explicitly or implicitly)
  61. validate the given configuration data itself. When it finds an error
  62. it raises this exception (either directly or by converting an exception
  63. from other modules) as a unified error in configuration.
  64. """
  65. pass
  66. class XfroutSessionError(Exception):
  67. '''An exception raised for some unexpected events during an xfrout session.
  68. '''
  69. pass
  70. def init_paths():
  71. global SPECFILE_PATH
  72. global AUTH_SPECFILE_PATH
  73. global UNIX_SOCKET_FILE
  74. if "B10_FROM_BUILD" in os.environ:
  75. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/xfrout"
  76. AUTH_SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/auth"
  77. if "B10_FROM_SOURCE_LOCALSTATEDIR" in os.environ:
  78. UNIX_SOCKET_FILE = os.environ["B10_FROM_SOURCE_LOCALSTATEDIR"] + \
  79. "/auth_xfrout_conn"
  80. else:
  81. UNIX_SOCKET_FILE = os.environ["B10_FROM_BUILD"] + "/auth_xfrout_conn"
  82. else:
  83. PREFIX = "@prefix@"
  84. DATAROOTDIR = "@datarootdir@"
  85. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  86. AUTH_SPECFILE_PATH = SPECFILE_PATH
  87. if "BIND10_XFROUT_SOCKET_FILE" in os.environ:
  88. UNIX_SOCKET_FILE = os.environ["BIND10_XFROUT_SOCKET_FILE"]
  89. else:
  90. UNIX_SOCKET_FILE = "@@LOCALSTATEDIR@@/@PACKAGE_NAME@/auth_xfrout_conn"
  91. init_paths()
  92. SPECFILE_LOCATION = SPECFILE_PATH + "/xfrout.spec"
  93. AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + os.sep + "auth.spec"
  94. VERBOSE_MODE = False
  95. XFROUT_DNS_HEADER_SIZE = 12 # protocol constant
  96. XFROUT_MAX_MESSAGE_SIZE = 65535 # ditto
  97. # borrowed from xfrin.py @ #1298. We should eventually unify it.
  98. def format_zone_str(zone_name, zone_class):
  99. """Helper function to format a zone name and class as a string of
  100. the form '<name>/<class>'.
  101. Parameters:
  102. zone_name (isc.dns.Name) name to format
  103. zone_class (isc.dns.RRClass) class to format
  104. """
  105. return zone_name.to_text(True) + '/' + str(zone_class)
  106. # borrowed from xfrin.py @ #1298.
  107. def format_addrinfo(addrinfo):
  108. """Helper function to format the addrinfo as a string of the form
  109. <addr>:<port> (for IPv4) or [<addr>]:port (for IPv6). For unix domain
  110. sockets, and unknown address families, it returns a basic string
  111. conversion of the third element of the passed tuple.
  112. Parameters:
  113. addrinfo: a 3-tuple consisting of address family, socket type, and,
  114. depending on the family, either a 2-tuple with the address
  115. and port, or a filename
  116. """
  117. try:
  118. if addrinfo[0] == socket.AF_INET:
  119. return str(addrinfo[2][0]) + ":" + str(addrinfo[2][1])
  120. elif addrinfo[0] == socket.AF_INET6:
  121. return "[" + str(addrinfo[2][0]) + "]:" + str(addrinfo[2][1])
  122. else:
  123. return str(addrinfo[2])
  124. except IndexError:
  125. raise TypeError("addrinfo argument to format_addrinfo() does not "
  126. "appear to be consisting of (family, socktype, (addr, port))")
  127. # This function is not inlined as it is replaced with a mock function
  128. # during testing.
  129. def get_rrset_len(rrset):
  130. """Returns the wire length of the given RRset"""
  131. return rrset.get_length()
  132. def get_soa_serial(soa_rdata):
  133. '''Extract the serial field of an SOA RDATA and returns it as an Serial object.
  134. '''
  135. return Serial(int(soa_rdata.to_text().split()[2]))
  136. def make_blocking(filenum, on):
  137. """A helper function to change blocking mode of the given socket.
  138. It sets the mode of blocking I/O for the socket associated with filenum
  139. (descriptor of the socket) according to parameter 'on': if it's True the
  140. file will be made blocking; otherwise it will be made non-blocking.
  141. The given filenum must be a descriptor of a socket (not an ordinary file
  142. etc), but this function doesn't check that condition.
  143. filenum(int): file number (descriptor) of the socket to update.
  144. on(bool): whether enable (True) or disable (False) blocking I/O.
  145. """
  146. flags = fcntl.fcntl(filenum, fcntl.F_GETFL)
  147. if on: # make it blocking
  148. flags &= ~os.O_NONBLOCK
  149. else: # make it non blocking
  150. flags |= os.O_NONBLOCK
  151. fcntl.fcntl(filenum, fcntl.F_SETFL, flags)
  152. class XfroutSession():
  153. def __init__(self, sock_fd, request_data, server, tsig_key_ring, remote,
  154. default_acl, zone_config, counters,
  155. client_class=DataSourceClient):
  156. self._sock_fd = sock_fd
  157. self._request_data = request_data
  158. self._server = server
  159. self._tsig_key_ring = tsig_key_ring
  160. self._tsig_ctx = None
  161. self._tsig_len = 0
  162. self._remote = remote
  163. self._request_type = None
  164. self._request_typestr = None
  165. self._acl = default_acl
  166. self._zone_config = zone_config
  167. self.ClientClass = client_class # parameterize this for testing
  168. self._soa = None # will be set in _xfrout_setup or in tests
  169. self._jnl_reader = None # will be set to a reader for IXFR
  170. # Creation of self.counters should be done before of
  171. # invoking self._handle()
  172. self._counters = counters
  173. self._handle()
  174. def create_tsig_ctx(self, tsig_record, tsig_key_ring):
  175. return TSIGContext(tsig_record.get_name(), tsig_record.get_rdata().get_algorithm(),
  176. tsig_key_ring)
  177. def _handle(self):
  178. ''' Handle a xfrout query, send xfrout response(s).
  179. This is separated from the constructor so that we can override
  180. it from tests.
  181. '''
  182. # Check the xfrout quota. We do both increase/decrease in this
  183. # method so it's clear we always release it once acquired.
  184. quota_ok = self._server.increase_transfers_counter()
  185. ex = None
  186. try:
  187. # Before start, make sure the socket uses blocking I/O because
  188. # responses will be sent in the blocking mode; otherwise it could
  189. # result in EWOULDBLOCK and disrupt the session.
  190. make_blocking(self._sock_fd, True)
  191. self.dns_xfrout_start(self._sock_fd, self._request_data, quota_ok)
  192. except Exception as e:
  193. # To avoid resource leak we need catch all possible exceptions
  194. # We log it later to exclude the case where even logger raises
  195. # an exception.
  196. ex = e
  197. # Release any critical resources
  198. if quota_ok:
  199. self._server.decrease_transfers_counter()
  200. self._close_socket()
  201. if ex is not None:
  202. logger.error(XFROUT_HANDLE_QUERY_ERROR, ex)
  203. def _close_socket(self):
  204. '''Simply close the socket via the given FD.
  205. This is a dedicated subroutine of handle() and is sepsarated from it
  206. for the convenience of tests.
  207. '''
  208. os.close(self._sock_fd)
  209. def _check_request_tsig(self, msg, request_data):
  210. ''' If request has a tsig record, perform tsig related checks '''
  211. tsig_record = msg.get_tsig_record()
  212. if tsig_record is not None:
  213. self._tsig_len = tsig_record.get_length()
  214. self._tsig_ctx = self.create_tsig_ctx(tsig_record,
  215. self._tsig_key_ring)
  216. tsig_error = self._tsig_ctx.verify(tsig_record, request_data)
  217. if tsig_error != TSIGError.NOERROR:
  218. return Rcode.NOTAUTH
  219. return Rcode.NOERROR
  220. def _parse_query_message(self, mdata):
  221. ''' parse query message to [socket,message]'''
  222. #TODO, need to add parseHeader() in case the message header is invalid
  223. try:
  224. msg = Message(Message.PARSE)
  225. Message.from_wire(msg, mdata)
  226. except Exception as err: # Exception is too broad
  227. logger.error(XFROUT_PARSE_QUERY_ERROR, err)
  228. return Rcode.FORMERR, None
  229. # TSIG related checks
  230. rcode = self._check_request_tsig(msg, mdata)
  231. if rcode != Rcode.NOERROR:
  232. return rcode, msg
  233. # Make sure the question is valid. This should be ensured by
  234. # the auth server, but since it's far from xfrout itself, we check
  235. # it by ourselves. A viloation would be an internal bug, so we
  236. # raise and stop here rather than returning a FORMERR or SERVFAIL.
  237. if msg.get_rr_count(Message.SECTION_QUESTION) != 1:
  238. raise RuntimeError('Invalid number of question for XFR: ' +
  239. str(msg.get_rr_count(Message.SECTION_QUESTION)))
  240. question = msg.get_question()[0]
  241. # Identify the request type
  242. self._request_type = question.get_type()
  243. if self._request_type == RRType.AXFR:
  244. self._request_typestr = 'AXFR'
  245. elif self._request_type == RRType.IXFR:
  246. self._request_typestr = 'IXFR'
  247. else:
  248. # Likewise, this should be impossible.
  249. raise RuntimeError('Unexpected XFR type: ' +
  250. str(self._request_type))
  251. # ACL checks
  252. zone_name = question.get_name()
  253. zone_class = question.get_class()
  254. acl = self._get_transfer_acl(zone_name, zone_class)
  255. acl_result = acl.execute(
  256. isc.acl.dns.RequestContext(self._remote[2], msg.get_tsig_record()))
  257. if acl_result == DROP:
  258. logger.debug(DBG_XFROUT_TRACE, XFROUT_QUERY_DROPPED,
  259. self._request_type, format_addrinfo(self._remote),
  260. format_zone_str(zone_name, zone_class))
  261. return None, None
  262. elif acl_result == REJECT:
  263. # count rejected Xfr request by each zone name
  264. self._counters.inc('zones', zone_class.to_text(),
  265. zone_name.to_text(), 'xfrrej')
  266. logger.debug(DBG_XFROUT_TRACE, XFROUT_QUERY_REJECTED,
  267. self._request_type, format_addrinfo(self._remote),
  268. format_zone_str(zone_name, zone_class))
  269. return Rcode.REFUSED, msg
  270. return rcode, msg
  271. def _get_transfer_acl(self, zone_name, zone_class):
  272. '''Return the ACL that should be applied for a given zone.
  273. The zone is identified by a tuple of name and RR class.
  274. If a per zone configuration for the zone exists and contains
  275. transfer_acl, that ACL will be used; otherwise, the default
  276. ACL will be used.
  277. '''
  278. # Internally zone names are managed in lower cased label characters,
  279. # so we first need to convert the name.
  280. zone_name_lower = Name(zone_name.to_text(), True)
  281. config_key = (zone_class.to_text(), zone_name_lower.to_text())
  282. if config_key in self._zone_config and \
  283. 'transfer_acl' in self._zone_config[config_key]:
  284. return self._zone_config[config_key]['transfer_acl']
  285. return self._acl
  286. def _send_data(self, sock_fd, data):
  287. size = len(data)
  288. total_count = 0
  289. while total_count < size:
  290. count = os.write(sock_fd, data[total_count:])
  291. total_count += count
  292. def _send_message(self, sock_fd, msg, tsig_ctx=None):
  293. render = MessageRenderer()
  294. # As defined in RFC5936 section3.4, perform case-preserving name
  295. # compression for AXFR message.
  296. render.set_compress_mode(MessageRenderer.CASE_SENSITIVE)
  297. render.set_length_limit(XFROUT_MAX_MESSAGE_SIZE)
  298. msg.to_wire(render, tsig_ctx)
  299. header_len = struct.pack('H', socket.htons(render.get_length()))
  300. self._send_data(sock_fd, header_len)
  301. self._send_data(sock_fd, render.get_data())
  302. def _reply_query_with_error_rcode(self, msg, sock_fd, rcode_):
  303. if not msg:
  304. return # query message is invalid. send nothing back.
  305. msg.make_response()
  306. msg.set_rcode(rcode_)
  307. self._send_message(sock_fd, msg, self._tsig_ctx)
  308. def _get_zone_soa(self, zone_name):
  309. '''Retrieve the SOA RR of the given zone.
  310. It returns a pair of RCODE and the SOA (in the form of RRset).
  311. On success RCODE is NOERROR and returned SOA is not None;
  312. on failure RCODE indicates the appropriate code in the context of
  313. xfr processing, and the returned SOA is None.
  314. '''
  315. result, finder = self._datasrc_client.find_zone(zone_name)
  316. if result != DataSourceClient.SUCCESS:
  317. return (Rcode.NOTAUTH, None)
  318. result, soa_rrset, _ = finder.find(zone_name, RRType.SOA)
  319. if result != ZoneFinder.SUCCESS:
  320. return (Rcode.SERVFAIL, None)
  321. # Especially for database-based zones, a working zone may be in
  322. # a broken state where it has more than one SOA RR. We proactively
  323. # check the condition and abort the xfr attempt if we identify it.
  324. if soa_rrset.get_rdata_count() != 1:
  325. return (Rcode.SERVFAIL, None)
  326. return (Rcode.NOERROR, soa_rrset)
  327. def __axfr_setup(self, zone_name):
  328. '''Setup a zone iterator for AXFR or AXFR-style IXFR.
  329. '''
  330. try:
  331. # Note that we enable 'separate_rrs'. In xfr-out we need to
  332. # preserve as many things as possible (even if it's half broken)
  333. # stored in the zone.
  334. self._iterator = self._datasrc_client.get_iterator(zone_name,
  335. True)
  336. except isc.datasrc.Error:
  337. # If the current name server does not have authority for the
  338. # zone, xfrout can't serve for it, return rcode NOTAUTH.
  339. # Note: this exception can happen for other reasons. We should
  340. # update get_iterator() API so that we can distinguish "no such
  341. # zone" and other cases (#1373). For now we consider all these
  342. # cases as NOTAUTH.
  343. return Rcode.NOTAUTH
  344. # If we are an authoritative name server for the zone, but fail
  345. # to find the zone's SOA record in datasource, xfrout can't
  346. # provide zone transfer for it.
  347. self._soa = self._iterator.get_soa()
  348. if self._soa is None or self._soa.get_rdata_count() != 1:
  349. return Rcode.SERVFAIL
  350. return Rcode.NOERROR
  351. def __ixfr_setup(self, request_msg, zone_name, zone_class):
  352. '''Setup a zone journal reader for IXFR.
  353. If the underlying data source does not know the requested range
  354. of zone differences it automatically falls back to AXFR-style
  355. IXFR by setting up a zone iterator instead of a journal reader.
  356. '''
  357. # Check the authority section. Look for a SOA record with
  358. # the same name and class as the question.
  359. remote_soa = None
  360. for auth_rrset in request_msg.get_section(Message.SECTION_AUTHORITY):
  361. # Ignore data whose owner name is not the zone apex, and
  362. # ignore non-SOA or different class of records.
  363. if auth_rrset.get_name() != zone_name or \
  364. auth_rrset.get_type() != RRType.SOA or \
  365. auth_rrset.get_class() != zone_class:
  366. continue
  367. if auth_rrset.get_rdata_count() != 1:
  368. logger.info(XFROUT_IXFR_MULTIPLE_SOA,
  369. format_addrinfo(self._remote))
  370. return Rcode.FORMERR
  371. remote_soa = auth_rrset
  372. if remote_soa is None:
  373. logger.info(XFROUT_IXFR_NO_SOA, format_addrinfo(self._remote))
  374. return Rcode.FORMERR
  375. # Retrieve the local SOA
  376. rcode, self._soa = self._get_zone_soa(zone_name)
  377. if rcode != Rcode.NOERROR:
  378. return rcode
  379. # RFC1995 says "If an IXFR query with the same or newer version
  380. # number than that of the server is received, it is replied to with
  381. # a single SOA record of the server's current version, just as
  382. # in AXFR". The claim about AXFR is incorrect, but other than that,
  383. # we do as the RFC says.
  384. begin_serial = get_soa_serial(remote_soa.get_rdata()[0])
  385. end_serial = get_soa_serial(self._soa.get_rdata()[0])
  386. if begin_serial >= end_serial:
  387. # clear both iterator and jnl_reader to signal we won't do
  388. # iteration in response generation
  389. self._iterator = None
  390. self._jnl_reader = None
  391. logger.info(XFROUT_IXFR_UPTODATE, format_addrinfo(self._remote),
  392. format_zone_str(zone_name, zone_class),
  393. begin_serial, end_serial)
  394. return Rcode.NOERROR
  395. # Set up the journal reader or fall back to AXFR-style IXFR
  396. try:
  397. code, self._jnl_reader = self._datasrc_client.get_journal_reader(
  398. zone_name, begin_serial.get_value(), end_serial.get_value())
  399. except isc.datasrc.NotImplemented as ex:
  400. # The underlying data source doesn't support journaling.
  401. # Fall back to AXFR-style IXFR.
  402. logger.info(XFROUT_IXFR_NO_JOURNAL_SUPPORT,
  403. format_addrinfo(self._remote),
  404. format_zone_str(zone_name, zone_class))
  405. return self.__axfr_setup(zone_name)
  406. if code == ZoneJournalReader.NO_SUCH_VERSION:
  407. logger.info(XFROUT_IXFR_NO_VERSION, format_addrinfo(self._remote),
  408. format_zone_str(zone_name, zone_class),
  409. begin_serial, end_serial)
  410. return self.__axfr_setup(zone_name)
  411. if code == ZoneJournalReader.NO_SUCH_ZONE:
  412. # this is quite unexpected as we know zone's SOA exists.
  413. # It might be a bug or the data source is somehow broken,
  414. # but it can still happen if someone has removed the zone
  415. # between these two operations. We treat it as NOTAUTH.
  416. logger.warn(XFROUT_IXFR_NO_ZONE, format_addrinfo(self._remote),
  417. format_zone_str(zone_name, zone_class))
  418. return Rcode.NOTAUTH
  419. # Use the reader as the iterator to generate the response.
  420. self._iterator = self._jnl_reader
  421. return Rcode.NOERROR
  422. def _xfrout_setup(self, request_msg, zone_name, zone_class):
  423. '''Setup a context for xfr responses according to the request type.
  424. This method identifies the most appropriate data source for the
  425. request and set up a zone iterator or journal reader depending on
  426. whether the request is AXFR or IXFR. If it identifies any protocol
  427. level error it returns an RCODE other than NOERROR.
  428. '''
  429. # Identify the data source for the requested zone and see if it has
  430. # SOA while initializing objects used for request processing later.
  431. # We should eventually generalize this so that we can choose the
  432. # appropriate data source from (possible) multiple candidates.
  433. # We should eventually take into account the RR class here.
  434. # For now, we hardcode a particular type (SQLite3-based), and only
  435. # consider that one.
  436. datasrc_config = '{ "database_file": "' + \
  437. self._server.get_db_file() + '"}'
  438. self._datasrc_client = self.ClientClass('sqlite3', datasrc_config)
  439. if self._request_type == RRType.AXFR:
  440. return self.__axfr_setup(zone_name)
  441. else:
  442. return self.__ixfr_setup(request_msg, zone_name, zone_class)
  443. def dns_xfrout_start(self, sock_fd, msg_query, quota_ok=True):
  444. rcode_, msg = self._parse_query_message(msg_query)
  445. #TODO. create query message and parse header
  446. if rcode_ is None: # Dropped by ACL
  447. return
  448. elif rcode_ == Rcode.NOTAUTH or rcode_ == Rcode.REFUSED:
  449. return self._reply_query_with_error_rcode(msg, sock_fd, rcode_)
  450. elif rcode_ != Rcode.NOERROR:
  451. return self._reply_query_with_error_rcode(msg, sock_fd,
  452. Rcode.FORMERR)
  453. elif not quota_ok:
  454. logger.warn(XFROUT_QUERY_QUOTA_EXCEEDED, self._request_typestr,
  455. format_addrinfo(self._remote),
  456. self._server._max_transfers_out)
  457. return self._reply_query_with_error_rcode(msg, sock_fd,
  458. Rcode.REFUSED)
  459. question = msg.get_question()[0]
  460. zone_name = question.get_name()
  461. zone_class = question.get_class()
  462. zone_str = format_zone_str(zone_name, zone_class) # for logging
  463. try:
  464. rcode_ = self._xfrout_setup(msg, zone_name, zone_class)
  465. except Exception as ex:
  466. logger.error(XFROUT_XFR_TRANSFER_CHECK_ERROR, self._request_typestr,
  467. format_addrinfo(self._remote), zone_str, ex)
  468. rcode_ = Rcode.SERVFAIL
  469. if rcode_ != Rcode.NOERROR:
  470. logger.info(XFROUT_XFR_TRANSFER_FAILED, self._request_typestr,
  471. format_addrinfo(self._remote), zone_str, rcode_)
  472. return self._reply_query_with_error_rcode(msg, sock_fd, rcode_)
  473. try:
  474. # increment Xfr starts by RRType
  475. if self._request_type == RRType.AXFR:
  476. self._counters.inc('axfr_running')
  477. else:
  478. self._counters.inc('ixfr_running')
  479. logger.info(XFROUT_XFR_TRANSFER_STARTED, self._request_typestr,
  480. format_addrinfo(self._remote), zone_str)
  481. self._reply_xfrout_query(msg, sock_fd)
  482. except Exception as err:
  483. # count unixsockets send errors
  484. self._counters.inc('socket', 'unixdomain', 'senderr')
  485. logger.error(XFROUT_XFR_TRANSFER_ERROR, self._request_typestr,
  486. format_addrinfo(self._remote), zone_str, err)
  487. finally:
  488. # decrement Xfr starts by RRType
  489. if self._request_type == RRType.AXFR:
  490. self._counters.dec('axfr_running')
  491. else:
  492. self._counters.dec('ixfr_running')
  493. # count done Xfr requests by each zone name
  494. self._counters.inc('zones', zone_class.to_text(),
  495. zone_name.to_text(), 'xfrreqdone')
  496. logger.info(XFROUT_XFR_TRANSFER_DONE, self._request_typestr,
  497. format_addrinfo(self._remote), zone_str)
  498. def _clear_message(self, msg):
  499. qid = msg.get_qid()
  500. opcode = msg.get_opcode()
  501. rcode = msg.get_rcode()
  502. msg.clear(Message.RENDER)
  503. msg.set_qid(qid)
  504. msg.set_opcode(opcode)
  505. msg.set_rcode(rcode)
  506. msg.set_header_flag(Message.HEADERFLAG_AA)
  507. msg.set_header_flag(Message.HEADERFLAG_QR)
  508. return msg
  509. def _send_message_with_last_soa(self, msg, sock_fd, rrset_soa,
  510. message_upper_len):
  511. '''Add the SOA record to the end of message.
  512. If it would exceed the maximum allowable size of a message, a new
  513. message will be created to send out the last SOA.
  514. We assume a message with a single SOA can always fit the buffer
  515. with or without TSIG. In theory this could be wrong if TSIG is
  516. stupidly large, but in practice this assumption should be reasonable.
  517. '''
  518. if message_upper_len + get_rrset_len(rrset_soa) > \
  519. XFROUT_MAX_MESSAGE_SIZE:
  520. self._send_message(sock_fd, msg, self._tsig_ctx)
  521. msg = self._clear_message(msg)
  522. msg.add_rrset(Message.SECTION_ANSWER, rrset_soa)
  523. self._send_message(sock_fd, msg, self._tsig_ctx)
  524. def _reply_xfrout_query(self, msg, sock_fd):
  525. msg.make_response()
  526. msg.set_header_flag(Message.HEADERFLAG_AA)
  527. # Reserved space for the fixed header size, the size of the question
  528. # section, and TSIG size (when included). The size of the question
  529. # section is the sum of the qname length and the size of the
  530. # fixed-length fields (type and class, 2 bytes each).
  531. message_upper_len = XFROUT_DNS_HEADER_SIZE + \
  532. msg.get_question()[0].get_name().get_length() + 4 + \
  533. self._tsig_len
  534. # If the iterator is None, we are responding to IXFR with a single
  535. # SOA RR.
  536. if self._iterator is None:
  537. self._send_message_with_last_soa(msg, sock_fd, self._soa,
  538. message_upper_len)
  539. return
  540. # Add the beginning SOA
  541. msg.add_rrset(Message.SECTION_ANSWER, self._soa)
  542. message_upper_len += get_rrset_len(self._soa)
  543. # Add the rest of the zone/diff contets
  544. for rrset in self._iterator:
  545. # Check if xfrout is shutdown
  546. if self._server._shutdown_event.is_set():
  547. logger.info(XFROUT_STOPPING)
  548. return
  549. # For AXFR (or AXFR-style IXFR), in which case _jnl_reader is None,
  550. # we should skip SOAs from the iterator.
  551. if self._jnl_reader is None and rrset.get_type() == RRType.SOA:
  552. continue
  553. # We calculate the maximum size of the RRset (i.e. the
  554. # size without compression) and use that to see if we
  555. # may have reached the limit
  556. rrset_len = get_rrset_len(rrset)
  557. if message_upper_len + rrset_len <= XFROUT_MAX_MESSAGE_SIZE:
  558. msg.add_rrset(Message.SECTION_ANSWER, rrset)
  559. message_upper_len += rrset_len
  560. continue
  561. # RR would not fit. If there are other RRs in the buffer, send
  562. # them now and leave this RR to the next message.
  563. self._send_message(sock_fd, msg, self._tsig_ctx)
  564. # Create a new message and reserve space for the carried-over
  565. # RR (and TSIG space in case it's to be TSIG signed)
  566. msg = self._clear_message(msg)
  567. message_upper_len = XFROUT_DNS_HEADER_SIZE + rrset_len + \
  568. self._tsig_len
  569. # If this RR overflows the buffer all by itself, fail. In theory
  570. # some RRs might fit in a TCP message when compressed even if they
  571. # do not fit when uncompressed, but surely we don't want to send
  572. # such monstrosities to an unsuspecting slave.
  573. if message_upper_len > XFROUT_MAX_MESSAGE_SIZE:
  574. raise XfroutSessionError('RR too large for zone transfer (' +
  575. str(rrset_len) + ' bytes)')
  576. # Add the RRset to the new message
  577. msg.add_rrset(Message.SECTION_ANSWER, rrset)
  578. # Add and send the trailing SOA
  579. self._send_message_with_last_soa(msg, sock_fd, self._soa,
  580. message_upper_len)
  581. class UnixSockServer(socketserver_mixin.NoPollMixIn,
  582. ThreadingUnixStreamServer):
  583. '''The unix domain socket server which accept xfr query sent from auth server.'''
  584. def __init__(self, sock_file, handle_class, shutdown_event, config_data,
  585. cc, counters):
  586. self._remove_unused_sock_file(sock_file)
  587. self._sock_file = sock_file
  588. socketserver_mixin.NoPollMixIn.__init__(self)
  589. self._counters = counters
  590. try:
  591. ThreadingUnixStreamServer.__init__(self, sock_file, \
  592. handle_class)
  593. except:
  594. self._counters.inc('socket', 'unixdomain', 'openfail')
  595. raise
  596. else:
  597. self._counters.inc('socket', 'unixdomain', 'open')
  598. self._shutdown_event = shutdown_event
  599. self._write_sock, self._read_sock = socket.socketpair()
  600. self._common_init()
  601. self._cc = cc
  602. self.update_config_data(config_data)
  603. def server_bind(self):
  604. """server_bind() overridden for counting unix domain sockets
  605. bind() failures
  606. """
  607. try:
  608. # call the server_bind() of class
  609. # ThreadingUnixStreamServer
  610. return super().server_bind()
  611. except:
  612. # count bind failed unixsockets
  613. self._counters.inc('socket', 'unixdomain', 'bindfail')
  614. raise
  615. def get_request(self):
  616. """get_request() overridden for counting unix domain sockets
  617. accept() failures and success
  618. """
  619. try:
  620. # call the get_request() of class
  621. # ThreadingUnixStreamServer
  622. ret = super().get_request()
  623. # count successfully accepted unixsockets
  624. self._counters.inc('socket', 'unixdomain', 'accept')
  625. return ret
  626. except:
  627. # count failed accepted unixsockets
  628. self._counters.inc('socket', 'unixdomain', 'acceptfail')
  629. raise
  630. def _common_init(self):
  631. '''Initialization shared with the mock server class used for tests'''
  632. self._lock = threading.Lock()
  633. self._transfers_counter = 0
  634. self._zone_config = {}
  635. self._acl = None # this will be initialized in update_config_data()
  636. def _receive_query_message(self, sock):
  637. ''' receive request message from sock'''
  638. # receive data length
  639. data_len = sock.recv(2)
  640. if not data_len:
  641. return None
  642. msg_len = struct.unpack('!H', data_len)[0]
  643. # receive data
  644. recv_size = 0
  645. msgdata = b''
  646. while recv_size < msg_len:
  647. data = sock.recv(msg_len - recv_size)
  648. if not data:
  649. return None
  650. recv_size += len(data)
  651. msgdata += data
  652. return msgdata
  653. def handle_request(self):
  654. ''' Enable server handle a request until shutdown or auth is closed.'''
  655. try:
  656. request, client_address = self.get_request()
  657. except socket.error:
  658. logger.error(XFROUT_FETCH_REQUEST_ERROR)
  659. return
  660. self._select_loop(request)
  661. def _select_loop(self, request_sock):
  662. '''Main loop for a single session between xfrout and auth.
  663. This is a dedicated subroutine of handle_request(), but is defined
  664. as a separate "protected" method for the convenience of tests.
  665. '''
  666. # Check self._shutdown_event to ensure the real shutdown comes.
  667. # Linux could trigger a spurious readable event on the _read_sock
  668. # due to a bug, so we need perform a double check.
  669. while not self._shutdown_event.is_set(): # Check if xfrout is shutdown
  670. try:
  671. (rlist, wlist, xlist) = select.select([self._read_sock,
  672. request_sock], [], [])
  673. except select.error as e:
  674. if e.args[0] == errno.EINTR:
  675. (rlist, wlist, xlist) = ([], [], [])
  676. continue
  677. else:
  678. logger.error(XFROUT_SOCKET_SELECT_ERROR, e)
  679. break
  680. # self.server._shutdown_event will be set by now, if it is not a
  681. # false alarm
  682. if self._read_sock in rlist:
  683. continue
  684. try:
  685. if not self.process_request(request_sock):
  686. break
  687. except Exception as pre:
  688. # count unixsockets receive errors
  689. self._counters.inc('socket', 'unixdomain', 'recverr')
  690. logger.error(XFROUT_PROCESS_REQUEST_ERROR, pre)
  691. break
  692. def _handle_request_noblock(self):
  693. """Override the function _handle_request_noblock(), it creates a new
  694. thread to handle requests for each auth"""
  695. td = threading.Thread(target=self.handle_request)
  696. td.setDaemon(True)
  697. td.start()
  698. def process_request(self, request):
  699. """Receive socket fd and query message from auth, then
  700. start a new thread to process the request.
  701. Return: True if everything is okay; otherwise False, in which case
  702. the calling thread will terminate.
  703. """
  704. sock_fd = recv_fd(request.fileno())
  705. if sock_fd < 0:
  706. logger.warn(XFROUT_RECEIVE_FD_FAILED)
  707. return False
  708. # receive request msg. If it fails we simply terminate the thread;
  709. # it might be possible to recover from this state, but it's more likely
  710. # that auth and xfrout are in inconsistent states. So it will make
  711. # more sense to restart in a new session.
  712. request_data = self._receive_query_message(request)
  713. if request_data is None:
  714. # The specific exception type doesn't matter so we use session
  715. # error.
  716. raise XfroutSessionError('Failed to get complete xfr request')
  717. t = threading.Thread(target=self.finish_request,
  718. args=(sock_fd, request_data))
  719. if self.daemon_threads:
  720. t.daemon = True
  721. t.start()
  722. return True
  723. def _guess_remote(self, sock_fd):
  724. """Guess remote address and port of the socket.
  725. The sock_fd must be a file descriptor of a socket.
  726. This method retuns a 3-tuple consisting of address family,
  727. socket type, and a 2-tuple with the address (string) and port (int).
  728. """
  729. # This uses a trick. If the socket is IPv4 in reality and we pretend
  730. # it to be IPv6, it returns IPv4 address anyway. This doesn't seem
  731. # to care about the SOCK_STREAM parameter at all (which it really is,
  732. # except for testing)
  733. if socket.has_ipv6:
  734. sock_domain = socket.AF_INET6
  735. else:
  736. # To make it work even on hosts without IPv6 support
  737. # (Any idea how to simulate this in test?)
  738. sock_domain = socket.AF_INET
  739. sock = socket.fromfd(sock_fd, sock_domain, socket.SOCK_STREAM)
  740. peer = sock.getpeername()
  741. sock.close()
  742. # Identify the correct socket family. Due to the above "trick",
  743. # we cannot simply use sock.family.
  744. family = socket.AF_INET6
  745. try:
  746. socket.inet_pton(socket.AF_INET6, peer[0])
  747. except socket.error:
  748. family = socket.AF_INET
  749. return (family, socket.SOCK_STREAM, peer)
  750. def finish_request(self, sock_fd, request_data):
  751. '''Finish one request by instantiating RequestHandlerClass.
  752. This is an entry point of a separate thread spawned in
  753. UnixSockServer.process_request().
  754. This method creates a XfroutSession object.
  755. '''
  756. self._lock.acquire()
  757. acl = self._acl
  758. zone_config = self._zone_config
  759. self._lock.release()
  760. self.RequestHandlerClass(sock_fd, request_data, self,
  761. isc.server_common.tsig_keyring.get_keyring(),
  762. self._guess_remote(sock_fd), acl, zone_config,
  763. self._counters)
  764. def _remove_unused_sock_file(self, sock_file):
  765. '''Try to remove the socket file. If the file is being used
  766. by one running xfrout process, exit from python.
  767. If it's not a socket file or nobody is listening
  768. , it will be removed. If it can't be removed, exit from python. '''
  769. if self._sock_file_in_use(sock_file):
  770. logger.error(XFROUT_UNIX_SOCKET_FILE_IN_USE, sock_file)
  771. sys.exit(0)
  772. else:
  773. if not os.path.exists(sock_file):
  774. return
  775. try:
  776. os.unlink(sock_file)
  777. except OSError as err:
  778. logger.error(XFROUT_REMOVE_OLD_UNIX_SOCKET_FILE_ERROR, sock_file, str(err))
  779. sys.exit(0)
  780. def _sock_file_in_use(self, sock_file):
  781. '''Check whether the socket file 'sock_file' exists and
  782. is being used by one running xfrout process. If it is,
  783. return True, or else return False. '''
  784. try:
  785. sock = socket.socket(socket.AF_UNIX)
  786. sock.connect(sock_file)
  787. except socket.error as err:
  788. sock.close()
  789. return False
  790. else:
  791. sock.close()
  792. return True
  793. def shutdown(self):
  794. self._write_sock.send(b"shutdown") #terminate the xfrout session thread
  795. super().shutdown() # call the shutdown() of class socketserver_mixin.NoPollMixIn
  796. # count closed unixsockets
  797. self._counters.inc('socket', 'unixdomain', 'close')
  798. try:
  799. os.unlink(self._sock_file)
  800. except Exception as e:
  801. logger.error(XFROUT_REMOVE_UNIX_SOCKET_FILE_ERROR, self._sock_file, str(e))
  802. def update_config_data(self, new_config):
  803. '''Apply the new config setting of xfrout module.
  804. '''
  805. self._lock.acquire()
  806. try:
  807. logger.info(XFROUT_NEW_CONFIG)
  808. new_acl = self._acl
  809. if 'transfer_acl' in new_config:
  810. try:
  811. new_acl = REQUEST_LOADER.load(new_config['transfer_acl'])
  812. except LoaderError as e:
  813. raise XfroutConfigError('Failed to parse transfer_acl: ' +
  814. str(e))
  815. new_zone_config = self._zone_config
  816. zconfig_data = new_config.get('zone_config')
  817. if zconfig_data is not None:
  818. new_zone_config = self.__create_zone_config(zconfig_data)
  819. self._acl = new_acl
  820. self._zone_config = new_zone_config
  821. self._max_transfers_out = new_config.get('transfers_out')
  822. except Exception as e:
  823. self._lock.release()
  824. raise e
  825. self._lock.release()
  826. logger.info(XFROUT_NEW_CONFIG_DONE)
  827. def __create_zone_config(self, zone_config_list):
  828. new_config = {}
  829. for zconf in zone_config_list:
  830. # convert the class, origin (name) pair. First build pydnspp
  831. # object to reject invalid input.
  832. zclass_str = zconf.get('class')
  833. if zclass_str is None:
  834. #zclass_str = 'IN' # temporary
  835. zclass_str = self._cc.get_default_value('zone_config/class')
  836. zclass = RRClass(zclass_str)
  837. zorigin = Name(zconf['origin'], True)
  838. config_key = (zclass.to_text(), zorigin.to_text())
  839. # reject duplicate config
  840. if config_key in new_config:
  841. raise XfroutConfigError('Duplicate zone_config for ' +
  842. str(zorigin) + '/' + str(zclass))
  843. # create a new config entry, build any given (and known) config
  844. new_config[config_key] = {}
  845. if 'transfer_acl' in zconf:
  846. try:
  847. new_config[config_key]['transfer_acl'] = \
  848. REQUEST_LOADER.load(zconf['transfer_acl'])
  849. except LoaderError as e:
  850. raise XfroutConfigError('Failed to parse transfer_acl ' +
  851. 'for ' + zorigin.to_text() + '/' +
  852. zclass_str + ': ' + str(e))
  853. return new_config
  854. def get_db_file(self):
  855. file, is_default = self._cc.get_remote_config_value("Auth", "database_file")
  856. # this too should be unnecessary, but currently the
  857. # 'from build' override isn't stored in the config
  858. # (and we don't have indirect python access to datasources yet)
  859. if is_default and "B10_FROM_BUILD" in os.environ:
  860. file = os.environ["B10_FROM_BUILD"] + os.sep + "bind10_zones.sqlite3"
  861. return file
  862. def increase_transfers_counter(self):
  863. '''Return False, if counter + 1 > max_transfers_out, or else
  864. return True
  865. '''
  866. ret = False
  867. self._lock.acquire()
  868. if self._transfers_counter < self._max_transfers_out:
  869. self._transfers_counter += 1
  870. ret = True
  871. self._lock.release()
  872. return ret
  873. def decrease_transfers_counter(self):
  874. self._lock.acquire()
  875. self._transfers_counter -= 1
  876. self._lock.release()
  877. class XfroutServer:
  878. def __init__(self):
  879. self._default_notify_address = ''
  880. self._default_notify_port = 53
  881. self._unix_socket_server = None
  882. self._listen_sock_file = UNIX_SOCKET_FILE
  883. self._shutdown_event = threading.Event()
  884. self._cc = isc.config.ModuleCCSession(SPECFILE_LOCATION, self.config_handler, self.command_handler)
  885. self._config_data = self._cc.get_full_config()
  886. self._counters = Counters(SPECFILE_LOCATION)
  887. self._cc.start()
  888. self._cc.add_remote_config(AUTH_SPECFILE_LOCATION)
  889. isc.server_common.tsig_keyring.init_keyring(self._cc)
  890. self._start_xfr_query_listener()
  891. self._start_notifier()
  892. def _start_xfr_query_listener(self):
  893. '''Start a new thread to accept xfr query. '''
  894. self._unix_socket_server = UnixSockServer(
  895. self._listen_sock_file,
  896. XfroutSession,
  897. self._shutdown_event,
  898. self._config_data,
  899. self._cc, self._counters)
  900. listener = threading.Thread(target=self._unix_socket_server.serve_forever)
  901. listener.start()
  902. def _start_notifier(self):
  903. datasrc = self._unix_socket_server.get_db_file()
  904. self._notifier = notify_out.NotifyOut(datasrc, counters=self._counters)
  905. if 'also_notify' in self._config_data:
  906. for slave in self._config_data['also_notify']:
  907. address = self._default_notify_address
  908. if 'address' in slave:
  909. address = slave['address']
  910. port = self._default_notify_port
  911. if 'port' in slave:
  912. port = slave['port']
  913. self._notifier.add_slave(address, port)
  914. self._notifier.dispatcher()
  915. def send_notify(self, zone_name, zone_class):
  916. return self._notifier.send_notify(zone_name, zone_class)
  917. def config_handler(self, new_config):
  918. '''Update config data. TODO. Do error check'''
  919. answer = create_answer(0)
  920. for key in new_config:
  921. if key not in self._config_data:
  922. answer = create_answer(1, "Unknown config data: " + str(key))
  923. continue
  924. self._config_data[key] = new_config[key]
  925. if self._unix_socket_server:
  926. try:
  927. self._unix_socket_server.update_config_data(self._config_data)
  928. except Exception as e:
  929. answer = create_answer(1,
  930. "Failed to handle new configuration: " +
  931. str(e))
  932. return answer
  933. def shutdown(self):
  934. ''' shutdown the xfrout process. The thread which is doing zone transfer-out should be
  935. terminated.
  936. '''
  937. global xfrout_server
  938. xfrout_server = None #Avoid shutdown is called twice
  939. self._cc.send_stopping()
  940. self._shutdown_event.set()
  941. self._notifier.shutdown()
  942. if self._unix_socket_server:
  943. self._unix_socket_server.shutdown()
  944. self._wait_for_threads()
  945. def _wait_for_threads(self):
  946. # Wait for all threads to terminate. this is a call that is only used
  947. # in shutdown(), but it has its own method, so we can test shutdown
  948. # without involving thread operations (the test would override this
  949. # method)
  950. main_thread = threading.currentThread()
  951. for th in threading.enumerate():
  952. if th is main_thread:
  953. continue
  954. th.join()
  955. def command_handler(self, cmd, args):
  956. if cmd == "shutdown":
  957. logger.info(XFROUT_RECEIVED_SHUTDOWN_COMMAND)
  958. self.shutdown()
  959. answer = create_answer(0)
  960. elif cmd == "notify":
  961. zone_name = args.get('zone_name')
  962. zone_class = args.get('zone_class')
  963. if not zone_class:
  964. zone_class = str(RRClass.IN)
  965. if zone_name:
  966. logger.info(XFROUT_NOTIFY_COMMAND, zone_name, zone_class)
  967. if self.send_notify(zone_name, zone_class):
  968. answer = create_answer(0)
  969. else:
  970. zonestr = notify_out.format_zone_str(Name(zone_name),
  971. zone_class)
  972. answer = create_answer(1, "Unknown zone: " + zonestr)
  973. else:
  974. answer = create_answer(1, "Bad command parameter:" + str(args))
  975. # return statistics data to the stats daemon
  976. elif cmd == "getstats":
  977. # The log level is here set to debug in order to avoid
  978. # that a log becomes too verbose. Because the b10-stats
  979. # daemon is periodically asking to the b10-xfrout daemon.
  980. answer = create_answer(0, self._counters.get_statistics())
  981. logger.debug(DBG_XFROUT_TRACE, \
  982. XFROUT_RECEIVED_GETSTATS_COMMAND, \
  983. str(answer))
  984. else:
  985. answer = create_answer(1, "Unknown command:" + str(cmd))
  986. return answer
  987. def run(self):
  988. '''Get and process all commands sent from cfgmgr or other modules. '''
  989. logger.debug(DBG_PROCESS, XFROUT_STARTED)
  990. while not self._shutdown_event.is_set():
  991. self._cc.check_command(False)
  992. xfrout_server = None
  993. def signal_handler(signal, frame):
  994. if xfrout_server:
  995. xfrout_server.shutdown()
  996. sys.exit(0)
  997. def set_signal_handler():
  998. signal.signal(signal.SIGTERM, signal_handler)
  999. signal.signal(signal.SIGINT, signal_handler)
  1000. def set_cmd_options(parser):
  1001. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  1002. help="display more about what is going on")
  1003. def main():
  1004. try:
  1005. parser = OptionParser()
  1006. set_cmd_options(parser)
  1007. (options, args) = parser.parse_args()
  1008. VERBOSE_MODE = options.verbose
  1009. set_signal_handler()
  1010. xfrout_server = XfroutServer()
  1011. xfrout_server.run()
  1012. except KeyboardInterrupt:
  1013. logger.info(XFROUT_STOPPED_BY_KEYBOARD)
  1014. except SessionError as e:
  1015. logger.error(XFROUT_CC_SESSION_ERROR, str(e))
  1016. except ModuleCCSessionError as e:
  1017. logger.error(XFROUT_MODULECC_SESSION_ERROR, str(e))
  1018. except XfroutConfigError as e:
  1019. logger.error(XFROUT_CONFIG_ERROR, str(e))
  1020. except SessionTimeout as e:
  1021. logger.error(XFROUT_CC_SESSION_TIMEOUT_ERROR)
  1022. if xfrout_server:
  1023. xfrout_server.shutdown()
  1024. logger.info(XFROUT_EXITING)
  1025. if '__main__' == __name__:
  1026. isc.util.traceback_handler.traceback_handler(main)