xfrout.py.in 48 KB

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