xfrin.py.in 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. #!@PYTHON@
  2. # Copyright (C) 2009-2011 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 os
  18. import signal
  19. import isc
  20. import asyncore
  21. import struct
  22. import threading
  23. import socket
  24. import random
  25. from optparse import OptionParser, OptionValueError
  26. from isc.config.ccsession import *
  27. from isc.notify import notify_out
  28. import isc.util.process
  29. import isc.net.parse
  30. try:
  31. from pydnspp import *
  32. except ImportError as e:
  33. # C++ loadable module may not be installed; even so the xfrin process
  34. # must keep running, so we warn about it and move forward.
  35. sys.stderr.write('[b10-xfrin] failed to import DNS module: %s\n' % str(e))
  36. isc.util.process.rename()
  37. # If B10_FROM_BUILD is set in the environment, we use data files
  38. # from a directory relative to that, otherwise we use the ones
  39. # installed on the system
  40. if "B10_FROM_BUILD" in os.environ:
  41. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/xfrin"
  42. AUTH_SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/auth"
  43. else:
  44. PREFIX = "@prefix@"
  45. DATAROOTDIR = "@datarootdir@"
  46. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  47. AUTH_SPECFILE_PATH = SPECFILE_PATH
  48. SPECFILE_LOCATION = SPECFILE_PATH + "/xfrin.spec"
  49. AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + "/auth.spec"
  50. XFROUT_MODULE_NAME = 'Xfrout'
  51. ZONE_MANAGER_MODULE_NAME = 'Zonemgr'
  52. REFRESH_FROM_ZONEMGR = 'refresh_from_zonemgr'
  53. ZONE_XFRIN_FAILED = 'zone_xfrin_failed'
  54. # These two default are currently hard-coded. For config this isn't
  55. # necessary, but we need these defaults for optional command arguments
  56. # (TODO: have similar support to get default values for command
  57. # arguments as we do for config options)
  58. DEFAULT_MASTER_PORT = 53
  59. DEFAULT_ZONE_CLASS = RRClass.IN()
  60. __version__ = 'BIND10'
  61. # define xfrin rcode
  62. XFRIN_OK = 0
  63. XFRIN_FAIL = 1
  64. def log_error(msg):
  65. sys.stderr.write("[b10-xfrin] %s\n" % str(msg))
  66. class XfrinException(Exception):
  67. pass
  68. class XfrinZoneInfoException(Exception):
  69. """This exception is raised if there is an error in the given
  70. configuration (part), or when a command does not have a required
  71. argument or has bad arguments, for instance when the zone's master
  72. address is not a valid IP address, when the zone does not
  73. have a name, or when multiple settings are given for the same
  74. zone."""
  75. pass
  76. def _check_zone_name(zone_name_str):
  77. """Checks if the given zone name is a valid domain name, and returns
  78. it as a Name object. Raises an XfrinException if it is not."""
  79. try:
  80. # In the _zones dict, part of the key is the zone name,
  81. # but due to a limitation in the Name class, we
  82. # cannot directly use it as a dict key, and we use to_text()
  83. #
  84. # Downcase the name here for that reason.
  85. return Name(zone_name_str, True)
  86. except (EmptyLabel, TooLongLabel, BadLabelType, BadEscape,
  87. TooLongName, IncompleteName) as ne:
  88. raise XfrinZoneInfoException("bad zone name: " + zone_name_str + " (" + str(ne) + ")")
  89. def _check_zone_class(zone_class_str):
  90. """If the given argument is a string: checks if the given class is
  91. a valid one, and returns an RRClass object if so.
  92. Raises XfrinZoneInfoException if not.
  93. If it is None, this function returns the default RRClass.IN()"""
  94. if zone_class_str is None:
  95. return DEFAULT_ZONE_CLASS
  96. try:
  97. return RRClass(zone_class_str)
  98. except InvalidRRClass as irce:
  99. raise XfrinZoneInfoException("bad zone class: " + zone_class_str + " (" + str(irce) + ")")
  100. class XfrinConnection(asyncore.dispatcher):
  101. '''Do xfrin in this class. '''
  102. def __init__(self,
  103. sock_map, zone_name, rrclass, db_file, shutdown_event,
  104. master_addrinfo, tsig_key = None, verbose = False,
  105. idle_timeout = 60):
  106. ''' idle_timeout: max idle time for read data from socket.
  107. db_file: specify the data source file.
  108. check_soa: when it's true, check soa first before sending xfr query
  109. '''
  110. asyncore.dispatcher.__init__(self, map=sock_map)
  111. self.create_socket(master_addrinfo[0], master_addrinfo[1])
  112. self._zone_name = zone_name
  113. self._sock_map = sock_map
  114. self._rrclass = rrclass
  115. self._db_file = db_file
  116. self._soa_rr_count = 0
  117. self._idle_timeout = idle_timeout
  118. self.setblocking(1)
  119. self._shutdown_event = shutdown_event
  120. self._verbose = verbose
  121. self._master_address = master_addrinfo[2]
  122. self._tsig_key = tsig_key
  123. self._tsig_ctx = None
  124. # tsig_ctx_creator is introduced to allow tests to use a mock class for
  125. # easier tests (in normal case we always use the default)
  126. self._tsig_ctx_creator = self.__create_tsig_ctx
  127. def __create_tsig_ctx(self, key):
  128. return TSIGContext(key)
  129. def connect_to_master(self):
  130. '''Connect to master in TCP.'''
  131. try:
  132. self.connect(self._master_address)
  133. return True
  134. except socket.error as e:
  135. self.log_msg('Failed to connect:(%s), %s' % (self._master_address,
  136. str(e)))
  137. return False
  138. def _create_query(self, query_type):
  139. '''Create dns query message. '''
  140. msg = Message(Message.RENDER)
  141. query_id = random.randint(0, 0xFFFF)
  142. self._query_id = query_id
  143. msg.set_qid(query_id)
  144. msg.set_opcode(Opcode.QUERY())
  145. msg.set_rcode(Rcode.NOERROR())
  146. query_question = Question(Name(self._zone_name), self._rrclass, query_type)
  147. msg.add_question(query_question)
  148. return msg
  149. def _send_data(self, data):
  150. size = len(data)
  151. total_count = 0
  152. while total_count < size:
  153. count = self.send(data[total_count:])
  154. total_count += count
  155. def _send_query(self, query_type):
  156. '''Send query message over TCP. '''
  157. msg = self._create_query(query_type)
  158. render = MessageRenderer()
  159. # XXX Currently, python wrapper doesn't accept 'None' parameter in this case,
  160. # we should remove the if statement and use a universal interface later.
  161. if self._tsig_key is not None:
  162. self._tsig_ctx = self._tsig_ctx_creator(self._tsig_key)
  163. msg.to_wire(render, self._tsig_ctx)
  164. else:
  165. msg.to_wire(render)
  166. header_len = struct.pack('H', socket.htons(render.get_length()))
  167. self._send_data(header_len)
  168. self._send_data(render.get_data())
  169. def _asyncore_loop(self):
  170. '''
  171. This method is a trivial wrapper for asyncore.loop(). It's extracted from
  172. _get_request_response so that we can test the rest of the code without
  173. involving actual communication with a remote server.'''
  174. asyncore.loop(self._idle_timeout, map=self._sock_map, count=1)
  175. def _get_request_response(self, size):
  176. recv_size = 0
  177. data = b''
  178. while recv_size < size:
  179. self._recv_time_out = True
  180. self._need_recv_size = size - recv_size
  181. self._asyncore_loop()
  182. if self._recv_time_out:
  183. raise XfrinException('receive data from socket time out.')
  184. recv_size += self._recvd_size
  185. data += self._recvd_data
  186. return data
  187. def _check_response_tsig(self, msg, response_data):
  188. tsig_record = msg.get_tsig_record()
  189. if self._tsig_ctx is not None:
  190. tsig_error = self._tsig_ctx.verify(tsig_record, response_data)
  191. if tsig_error != TSIGError.NOERROR:
  192. raise XfrinException('TSIG verify fail: %s' % str(tsig_error))
  193. elif tsig_record is not None:
  194. # If the response includes a TSIG while we didn't sign the query,
  195. # we treat it as an error. RFC doesn't say anything about this
  196. # case, but it clearly states the server must not sign a response
  197. # to an unsigned request. Although we could be flexible, no sane
  198. # implementation would return such a response, and since this is
  199. # part of security mechanism, it's probably better to be more
  200. # strict.
  201. raise XfrinException('Unexpected TSIG in response')
  202. def _check_soa_serial(self):
  203. ''' Compare the soa serial, if soa serial in master is less than
  204. the soa serial in local, Finish xfrin.
  205. False: soa serial in master is less or equal to the local one.
  206. True: soa serial in master is bigger
  207. '''
  208. self._send_query(RRType.SOA())
  209. data_len = self._get_request_response(2)
  210. msg_len = socket.htons(struct.unpack('H', data_len)[0])
  211. soa_response = self._get_request_response(msg_len)
  212. msg = Message(Message.PARSE)
  213. msg.from_wire(soa_response)
  214. # perform some minimal level validation. It's an open issue how
  215. # strict we should be (see the comment in _check_response_header())
  216. self._check_response_header(msg)
  217. # TSIG related checks, including an unexpected signed response
  218. self._check_response_tsig(msg, soa_response)
  219. # TODO, need select soa record from data source then compare the two
  220. # serial, current just return OK, since this function hasn't been used
  221. # now.
  222. return XFRIN_OK
  223. def do_xfrin(self, check_soa, ixfr_first = False):
  224. '''Do xfr by sending xfr request and parsing response. '''
  225. try:
  226. ret = XFRIN_OK
  227. if check_soa:
  228. logstr = 'SOA check for \'%s\' ' % self._zone_name
  229. ret = self._check_soa_serial()
  230. logstr = 'transfer of \'%s\': AXFR ' % self._zone_name
  231. if ret == XFRIN_OK:
  232. self.log_msg(logstr + 'started')
  233. self._send_query(RRType.AXFR())
  234. isc.datasrc.sqlite3_ds.load(self._db_file, self._zone_name,
  235. self._handle_xfrin_response)
  236. self.log_msg(logstr + 'succeeded')
  237. except XfrinException as e:
  238. self.log_msg(e)
  239. self.log_msg(logstr + 'failed')
  240. ret = XFRIN_FAIL
  241. #TODO, recover data source.
  242. except isc.datasrc.sqlite3_ds.Sqlite3DSError as e:
  243. self.log_msg(e)
  244. self.log_msg(logstr + 'failed')
  245. ret = XFRIN_FAIL
  246. except UserWarning as e:
  247. # XXX: this is an exception from our C++ library via the
  248. # Boost.Python binding. It would be better to have more more
  249. # specific exceptions, but at this moment this is the finest
  250. # granularity.
  251. self.log_msg(e)
  252. self.log_msg(logstr + 'failed')
  253. ret = XFRIN_FAIL
  254. finally:
  255. self.close()
  256. return ret
  257. def _check_response_header(self, msg):
  258. '''Perform minimal validation on responses'''
  259. # It's not clear how strict we should be about response validation.
  260. # BIND 9 ignores some cases where it would normally be considered a
  261. # bogus response. For example, it accepts a response even if its
  262. # opcode doesn't match that of the corresponding request.
  263. # According to an original developer of BIND 9 some of the missing
  264. # checks are deliberate to be kind to old implementations that would
  265. # cause interoperability trouble with stricter checks.
  266. msg_rcode = msg.get_rcode()
  267. if msg_rcode != Rcode.NOERROR():
  268. raise XfrinException('error response: %s' % msg_rcode.to_text())
  269. if not msg.get_header_flag(Message.HEADERFLAG_QR):
  270. raise XfrinException('response is not a response ')
  271. if msg.get_qid() != self._query_id:
  272. raise XfrinException('bad query id')
  273. def _check_response_status(self, msg):
  274. '''Check validation of xfr response. '''
  275. self._check_response_header(msg)
  276. if msg.get_rr_count(Message.SECTION_ANSWER) == 0:
  277. raise XfrinException('answer section is empty')
  278. if msg.get_rr_count(Message.SECTION_QUESTION) > 1:
  279. raise XfrinException('query section count greater than 1')
  280. def _handle_answer_section(self, answer_section):
  281. '''Return a generator for the reponse in one tcp package to a zone transfer.'''
  282. for rrset in answer_section:
  283. rrset_name = rrset.get_name().to_text()
  284. rrset_ttl = int(rrset.get_ttl().to_text())
  285. rrset_class = rrset.get_class().to_text()
  286. rrset_type = rrset.get_type().to_text()
  287. for rdata in rrset.get_rdata():
  288. # Count the soa record count
  289. if rrset.get_type() == RRType.SOA():
  290. self._soa_rr_count += 1
  291. # XXX: the current DNS message parser can't preserve the
  292. # RR order or separete the beginning and ending SOA RRs.
  293. # As a short term workaround, we simply ignore the second
  294. # SOA, and ignore the erroneous case where the transfer
  295. # session doesn't end with an SOA.
  296. if (self._soa_rr_count == 2):
  297. # Avoid inserting soa record twice
  298. break
  299. rdata_text = rdata.to_text()
  300. yield (rrset_name, rrset_ttl, rrset_class, rrset_type,
  301. rdata_text)
  302. def _handle_xfrin_response(self):
  303. '''Return a generator for the response to a zone transfer. '''
  304. while True:
  305. data_len = self._get_request_response(2)
  306. msg_len = socket.htons(struct.unpack('H', data_len)[0])
  307. recvdata = self._get_request_response(msg_len)
  308. msg = Message(Message.PARSE)
  309. msg.from_wire(recvdata)
  310. self._check_response_status(msg)
  311. # TSIG related checks, including an unexpected signed response
  312. self._check_response_tsig(msg, recvdata)
  313. answer_section = msg.get_section(Message.SECTION_ANSWER)
  314. for rr in self._handle_answer_section(answer_section):
  315. yield rr
  316. if self._soa_rr_count == 2:
  317. break
  318. if self._shutdown_event.is_set():
  319. raise XfrinException('xfrin is forced to stop')
  320. def handle_read(self):
  321. '''Read query's response from socket. '''
  322. self._recvd_data = self.recv(self._need_recv_size)
  323. self._recvd_size = len(self._recvd_data)
  324. self._recv_time_out = False
  325. def writable(self):
  326. '''Ignore the writable socket. '''
  327. return False
  328. def log_info(self, msg, type='info'):
  329. # Overwrite the log function, log nothing
  330. pass
  331. def log_msg(self, msg):
  332. if self._verbose:
  333. sys.stdout.write('[b10-xfrin] %s\n' % str(msg))
  334. def process_xfrin(server, xfrin_recorder, zone_name, rrclass, db_file,
  335. shutdown_event, master_addrinfo, check_soa, verbose,
  336. tsig_key):
  337. xfrin_recorder.increment(zone_name)
  338. sock_map = {}
  339. conn = XfrinConnection(sock_map, zone_name, rrclass, db_file,
  340. shutdown_event, master_addrinfo,
  341. tsig_key, verbose)
  342. ret = XFRIN_FAIL
  343. if conn.connect_to_master():
  344. ret = conn.do_xfrin(check_soa)
  345. # Publish the zone transfer result news, so zonemgr can reset the
  346. # zone timer, and xfrout can notify the zone's slaves if the result
  347. # is success.
  348. server.publish_xfrin_news(zone_name, rrclass, ret)
  349. xfrin_recorder.decrement(zone_name)
  350. class XfrinRecorder:
  351. def __init__(self):
  352. self._lock = threading.Lock()
  353. self._zones = []
  354. def increment(self, zone_name):
  355. self._lock.acquire()
  356. self._zones.append(zone_name)
  357. self._lock.release()
  358. def decrement(self, zone_name):
  359. self._lock.acquire()
  360. if zone_name in self._zones:
  361. self._zones.remove(zone_name)
  362. self._lock.release()
  363. def xfrin_in_progress(self, zone_name):
  364. self._lock.acquire()
  365. ret = zone_name in self._zones
  366. self._lock.release()
  367. return ret
  368. def count(self):
  369. self._lock.acquire()
  370. ret = len(self._zones)
  371. self._lock.release()
  372. return ret
  373. class ZoneInfo:
  374. def __init__(self, config_data, module_cc):
  375. """Creates a zone_info with the config data element as
  376. specified by the 'zones' list in xfrin.spec. Module_cc is
  377. needed to get the defaults from the specification"""
  378. self._module_cc = module_cc
  379. self.set_name(config_data.get('name'))
  380. self.set_master_addr(config_data.get('master_addr'))
  381. self.set_master_port(config_data.get('master_port'))
  382. self.set_zone_class(config_data.get('class'))
  383. self.set_tsig_key(config_data.get('tsig_key'))
  384. def set_name(self, name_str):
  385. """Set the name for this zone given a name string.
  386. Raises XfrinZoneInfoException if name_str is None or if it
  387. cannot be parsed."""
  388. if name_str is None:
  389. raise XfrinZoneInfoException("Configuration zones list "
  390. "element does not contain "
  391. "'name' attribute")
  392. else:
  393. self.name = _check_zone_name(name_str)
  394. def set_master_addr(self, master_addr_str):
  395. """Set the master address for this zone given an IP address
  396. string. Raises XfrinZoneInfoException if master_addr_str is
  397. None or if it cannot be parsed."""
  398. if master_addr_str is None:
  399. raise XfrinZoneInfoException("master address missing from config data")
  400. else:
  401. try:
  402. self.master_addr = isc.net.parse.addr_parse(master_addr_str)
  403. except ValueError:
  404. errmsg = "bad format for zone's master: " + master_addr_str
  405. log_error(errmsg)
  406. raise XfrinZoneInfoException(errmsg)
  407. def set_master_port(self, master_port_str):
  408. """Set the master port given a port number string. If
  409. master_port_str is None, the default from the specification
  410. for this module will be used. Raises XfrinZoneInfoException if
  411. the string contains an invalid port number"""
  412. if master_port_str is None:
  413. self.master_port = self._module_cc.get_default_value("zones/master_port")
  414. else:
  415. try:
  416. self.master_port = isc.net.parse.port_parse(master_port_str)
  417. except ValueError:
  418. errmsg = "bad format for zone's master port: " + master_port_str
  419. log_error(errmsg)
  420. raise XfrinZoneInfoException(errmsg)
  421. def set_zone_class(self, zone_class_str):
  422. """Set the zone class given an RR class str (e.g. "IN"). If
  423. zone_class_str is None, it will default to what is specified
  424. in the specification file for this module. Raises
  425. XfrinZoneInfoException if the string cannot be parsed."""
  426. # TODO: remove _str
  427. self.class_str = zone_class_str or self._module_cc.get_default_value("zones/class")
  428. if zone_class_str == None:
  429. #TODO rrclass->zone_class
  430. self.rrclass = RRClass(self._module_cc.get_default_value("zones/class"))
  431. else:
  432. try:
  433. self.rrclass = RRClass(zone_class_str)
  434. except InvalidRRClass:
  435. errmsg = "invalid zone class: " + zone_class_str
  436. log_error(errmsg)
  437. raise XfrinZoneInfoException(errmsg)
  438. def set_tsig_key(self, tsig_key_str):
  439. """Set the tsig_key for this zone, given a TSIG key string
  440. representation. If tsig_key_str is None, no TSIG key will
  441. be set. Raises XfrinZoneInfoException if tsig_key_str cannot
  442. be parsed."""
  443. if tsig_key_str is None:
  444. self.tsig_key = None
  445. else:
  446. try:
  447. self.tsig_key = TSIGKey(tsig_key_str)
  448. except InvalidParameter as ipe:
  449. errmsg = "bad TSIG key string: " + tsig_key_str
  450. log_error(errmsg)
  451. raise XfrinZoneInfoException(errmsg)
  452. def get_master_addr_info(self):
  453. return (self.master_addr.family, socket.SOCK_STREAM,
  454. (str(self.master_addr), self.master_port))
  455. class Xfrin:
  456. def __init__(self, verbose = False):
  457. self._max_transfers_in = 10
  458. self._zones = {}
  459. self._cc_setup()
  460. self.recorder = XfrinRecorder()
  461. self._shutdown_event = threading.Event()
  462. self._verbose = verbose
  463. def _cc_setup(self):
  464. '''This method is used only as part of initialization, but is
  465. implemented separately for convenience of unit tests; by letting
  466. the test code override this method we can test most of this class
  467. without requiring a command channel.'''
  468. # Create one session for sending command to other modules, because the
  469. # listening session will block the send operation.
  470. self._send_cc_session = isc.cc.Session()
  471. self._module_cc = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  472. self.config_handler,
  473. self.command_handler)
  474. self._module_cc.start()
  475. config_data = self._module_cc.get_full_config()
  476. self.config_handler(config_data)
  477. def _cc_check_command(self):
  478. '''This is a straightforward wrapper for cc.check_command,
  479. but provided as a separate method for the convenience
  480. of unit tests.'''
  481. self._module_cc.check_command(False)
  482. def _get_zone_info(self, name, rrclass):
  483. """Returns the ZoneInfo object containing the configured data
  484. for the given zone name. If the zone name did not have any
  485. data, returns None"""
  486. return self._zones.get((name.to_text(), rrclass.to_text()))
  487. def _add_zone_info(self, zone_info):
  488. """Add the zone info. Raises a XfrinZoneInfoException if a zone
  489. with the same name and class is already configured"""
  490. key = (zone_info.name.to_text(), zone_info.class_str)
  491. if key in self._zones:
  492. raise XfrinZoneInfoException("zone " + str(key) +
  493. " configured multiple times")
  494. self._zones[key] = zone_info
  495. def _clear_zone_info(self):
  496. self._zones = {}
  497. def config_handler(self, new_config):
  498. # backup all config data (should there be a problem in the new
  499. # data)
  500. old_max_transfers_in = self._max_transfers_in
  501. old_zones = self._zones
  502. self._max_transfers_in = new_config.get("transfers_in") or self._max_transfers_in
  503. if 'zones' in new_config:
  504. self._clear_zone_info()
  505. for zone_config in new_config.get('zones'):
  506. try:
  507. zone_info = ZoneInfo(zone_config, self._module_cc)
  508. self._add_zone_info(zone_info)
  509. except XfrinZoneInfoException as xce:
  510. self._zones = old_zones
  511. self._max_transfers_in = old_max_transfers_in
  512. return create_answer(1, str(xce))
  513. return create_answer(0)
  514. def shutdown(self):
  515. ''' shutdown the xfrin process. the thread which is doing xfrin should be
  516. terminated.
  517. '''
  518. self._shutdown_event.set()
  519. main_thread = threading.currentThread()
  520. for th in threading.enumerate():
  521. if th is main_thread:
  522. continue
  523. th.join()
  524. def command_handler(self, command, args):
  525. answer = create_answer(0)
  526. try:
  527. if command == 'shutdown':
  528. self._shutdown_event.set()
  529. elif command == 'notify' or command == REFRESH_FROM_ZONEMGR:
  530. # Xfrin receives the refresh/notify command from zone manager.
  531. # notify command maybe has the parameters which
  532. # specify the notifyfrom address and port, according the RFC1996, zone
  533. # transfer should starts first from the notifyfrom, but now, let 'TODO' it.
  534. # (using the value now, while we can only set one master address, would be
  535. # a security hole. Once we add the ability to have multiple master addresses,
  536. # we should check if it matches one of them, and then use it.)
  537. (zone_name, rrclass) = self._parse_zone_name_and_class(args)
  538. zone_info = self._get_zone_info(zone_name, rrclass)
  539. if zone_info is None:
  540. # TODO what to do? no info known about zone. defaults?
  541. errmsg = "Got notification to retransfer unknown zone " + zone_name.to_text()
  542. log_error(errmsg)
  543. answer = create_answer(1, errmsg)
  544. else:
  545. master_addr = zone_info.get_master_addr_info()
  546. ret = self.xfrin_start(zone_name,
  547. rrclass,
  548. self._get_db_file(),
  549. master_addr,
  550. zone_info.tsig_key,
  551. True)
  552. answer = create_answer(ret[0], ret[1])
  553. elif command == 'retransfer' or command == 'refresh':
  554. # Xfrin receives the retransfer/refresh from cmdctl(sent by bindctl).
  555. # If the command has specified master address, do transfer from the
  556. # master address, or else do transfer from the configured masters.
  557. (zone_name, rrclass) = self._parse_zone_name_and_class(args)
  558. master_addr = self._parse_master_and_port(args, zone_name,
  559. rrclass)
  560. zone_info = self._get_zone_info(zone_name, rrclass)
  561. tsig_key = None
  562. if zone_info:
  563. tsig_key = zone_info.tsig_key
  564. db_file = args.get('db_file') or self._get_db_file()
  565. ret = self.xfrin_start(zone_name,
  566. rrclass,
  567. db_file,
  568. master_addr,
  569. tsig_key,
  570. (False if command == 'retransfer' else True))
  571. answer = create_answer(ret[0], ret[1])
  572. else:
  573. answer = create_answer(1, 'unknown command: ' + command)
  574. except XfrinException as err:
  575. log_error('error happened for command: %s, %s' % (command, str(err)) )
  576. answer = create_answer(1, str(err))
  577. return answer
  578. def _parse_zone_name_and_class(self, args):
  579. zone_name_str = args.get('zone_name')
  580. if zone_name_str is None:
  581. raise XfrinException('zone name should be provided')
  582. return (_check_zone_name(zone_name_str), _check_zone_class(args.get('zone_class')))
  583. def _parse_master_and_port(self, args, zone_name, zone_class):
  584. """
  585. Return tuple (family, socktype, sockaddr) for address and port in given
  586. args dict.
  587. IPv4 and IPv6 are the only supported addresses now, so sockaddr will be
  588. (address, port). The socktype is socket.SOCK_STREAM for now.
  589. """
  590. # check if we have configured info about this zone, in case
  591. # port or master are not specified
  592. zone_info = self._get_zone_info(zone_name, zone_class)
  593. addr_str = args.get('master')
  594. if addr_str is None:
  595. if zone_info is not None:
  596. addr = zone_info.master_addr
  597. else:
  598. raise XfrinException("Master address not given or "
  599. "configured for " + zone_name.to_text())
  600. else:
  601. try:
  602. addr = isc.net.parse.addr_parse(addr_str)
  603. except ValueError as err:
  604. raise XfrinException("failed to resolve master address %s: %s" %
  605. (addr_str, str(err)))
  606. port_str = args.get('port')
  607. if port_str is None:
  608. if zone_info is not None:
  609. port = zone_info.master_port
  610. else:
  611. port = DEFAULT_MASTER_PORT
  612. else:
  613. try:
  614. port = isc.net.parse.port_parse(port_str)
  615. except ValueError as err:
  616. raise XfrinException("failed to parse port=%s: %s" %
  617. (port_str, str(err)))
  618. return (addr.family, socket.SOCK_STREAM, (str(addr), port))
  619. def _get_db_file(self):
  620. #TODO, the db file path should be got in auth server's configuration
  621. # if we need access to this configuration more often, we
  622. # should add it on start, and not remove it here
  623. # (or, if we have writable ds, we might not need this in
  624. # the first place)
  625. self._module_cc.add_remote_config(AUTH_SPECFILE_LOCATION)
  626. db_file, is_default = self._module_cc.get_remote_config_value("Auth", "database_file")
  627. if is_default and "B10_FROM_BUILD" in os.environ:
  628. # this too should be unnecessary, but currently the
  629. # 'from build' override isn't stored in the config
  630. # (and we don't have writable datasources yet)
  631. db_file = os.environ["B10_FROM_BUILD"] + os.sep + "bind10_zones.sqlite3"
  632. self._module_cc.remove_remote_config(AUTH_SPECFILE_LOCATION)
  633. return db_file
  634. def publish_xfrin_news(self, zone_name, zone_class, xfr_result):
  635. '''Send command to xfrout/zone manager module.
  636. If xfrin has finished successfully for one zone, tell the good
  637. news(command: zone_new_data_ready) to zone manager and xfrout.
  638. if xfrin failed, just tell the bad news to zone manager, so that
  639. it can reset the refresh timer for that zone. '''
  640. param = {'zone_name': zone_name, 'zone_class': zone_class.to_text()}
  641. if xfr_result == XFRIN_OK:
  642. msg = create_command(notify_out.ZONE_NEW_DATA_READY_CMD, param)
  643. # catch the exception, in case msgq has been killed.
  644. try:
  645. seq = self._send_cc_session.group_sendmsg(msg,
  646. XFROUT_MODULE_NAME)
  647. try:
  648. answer, env = self._send_cc_session.group_recvmsg(False,
  649. seq)
  650. except isc.cc.session.SessionTimeout:
  651. pass # for now we just ignore the failure
  652. seq = self._send_cc_session.group_sendmsg(msg, ZONE_MANAGER_MODULE_NAME)
  653. try:
  654. answer, env = self._send_cc_session.group_recvmsg(False,
  655. seq)
  656. except isc.cc.session.SessionTimeout:
  657. pass # for now we just ignore the failure
  658. except socket.error as err:
  659. log_error("Fail to send message to %s and %s, msgq may has been killed"
  660. % (XFROUT_MODULE_NAME, ZONE_MANAGER_MODULE_NAME))
  661. else:
  662. msg = create_command(ZONE_XFRIN_FAILED, param)
  663. # catch the exception, in case msgq has been killed.
  664. try:
  665. seq = self._send_cc_session.group_sendmsg(msg, ZONE_MANAGER_MODULE_NAME)
  666. try:
  667. answer, env = self._send_cc_session.group_recvmsg(False,
  668. seq)
  669. except isc.cc.session.SessionTimeout:
  670. pass # for now we just ignore the failure
  671. except socket.error as err:
  672. log_error("Fail to send message to %s, msgq may has been killed"
  673. % ZONE_MANAGER_MODULE_NAME)
  674. def startup(self):
  675. while not self._shutdown_event.is_set():
  676. self._cc_check_command()
  677. def xfrin_start(self, zone_name, rrclass, db_file, master_addrinfo, tsig_key,
  678. check_soa = True):
  679. if "pydnspp" not in sys.modules:
  680. return (1, "xfrin failed, can't load dns message python library: 'pydnspp'")
  681. # check max_transfer_in, else return quota error
  682. if self.recorder.count() >= self._max_transfers_in:
  683. return (1, 'xfrin quota error')
  684. if self.recorder.xfrin_in_progress(zone_name):
  685. return (1, 'zone xfrin is in progress')
  686. xfrin_thread = threading.Thread(target = process_xfrin,
  687. args = (self,
  688. self.recorder,
  689. zone_name.to_text(),
  690. rrclass,
  691. db_file,
  692. self._shutdown_event,
  693. master_addrinfo, check_soa,
  694. self._verbose,
  695. tsig_key))
  696. xfrin_thread.start()
  697. return (0, 'zone xfrin is started')
  698. xfrind = None
  699. def signal_handler(signal, frame):
  700. if xfrind:
  701. xfrind.shutdown()
  702. sys.exit(0)
  703. def set_signal_handler():
  704. signal.signal(signal.SIGTERM, signal_handler)
  705. signal.signal(signal.SIGINT, signal_handler)
  706. def set_cmd_options(parser):
  707. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  708. help="display more about what is going on")
  709. def main(xfrin_class, use_signal = True):
  710. """The main loop of the Xfrin daemon.
  711. @param xfrin_class: A class of the Xfrin object. This is normally Xfrin,
  712. but can be a subclass of it for customization.
  713. @param use_signal: True if this process should catch signals. This is
  714. normally True, but may be disabled when this function is called in a
  715. testing context."""
  716. global xfrind
  717. try:
  718. parser = OptionParser(version = __version__)
  719. set_cmd_options(parser)
  720. (options, args) = parser.parse_args()
  721. if use_signal:
  722. set_signal_handler()
  723. xfrind = xfrin_class(verbose = options.verbose)
  724. xfrind.startup()
  725. except KeyboardInterrupt:
  726. log_error("exit b10-xfrin")
  727. except isc.cc.session.SessionError as e:
  728. log_error(str(e))
  729. log_error('Error happened! is the command channel daemon running?')
  730. except Exception as e:
  731. log_error(str(e))
  732. if xfrind:
  733. xfrind.shutdown()
  734. if __name__ == '__main__':
  735. main(Xfrin)