xfrin.py.in 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  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. from isc.datasrc import DataSourceClient, ZoneFinder
  30. import isc.net.parse
  31. from isc.xfrin.diff import Diff
  32. from isc.log_messages.xfrin_messages import *
  33. isc.log.init("b10-xfrin")
  34. logger = isc.log.Logger("xfrin")
  35. try:
  36. from pydnspp import *
  37. except ImportError as e:
  38. # C++ loadable module may not be installed; even so the xfrin process
  39. # must keep running, so we warn about it and move forward.
  40. logger.error(XFRIN_IMPORT_DNS, str(e))
  41. isc.util.process.rename()
  42. # If B10_FROM_BUILD is set in the environment, we use data files
  43. # from a directory relative to that, otherwise we use the ones
  44. # installed on the system
  45. if "B10_FROM_BUILD" in os.environ:
  46. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/xfrin"
  47. AUTH_SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/auth"
  48. else:
  49. PREFIX = "@prefix@"
  50. DATAROOTDIR = "@datarootdir@"
  51. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  52. AUTH_SPECFILE_PATH = SPECFILE_PATH
  53. SPECFILE_LOCATION = SPECFILE_PATH + "/xfrin.spec"
  54. AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + "/auth.spec"
  55. XFROUT_MODULE_NAME = 'Xfrout'
  56. ZONE_MANAGER_MODULE_NAME = 'Zonemgr'
  57. REFRESH_FROM_ZONEMGR = 'refresh_from_zonemgr'
  58. ZONE_XFRIN_FAILED = 'zone_xfrin_failed'
  59. # Constants for debug levels, to be removed when we have #1074.
  60. DBG_XFRIN_TRACE = 3
  61. # These two default are currently hard-coded. For config this isn't
  62. # necessary, but we need these defaults for optional command arguments
  63. # (TODO: have similar support to get default values for command
  64. # arguments as we do for config options)
  65. DEFAULT_MASTER_PORT = 53
  66. DEFAULT_ZONE_CLASS = RRClass.IN()
  67. __version__ = 'BIND10'
  68. # define xfrin rcode
  69. XFRIN_OK = 0
  70. XFRIN_FAIL = 1
  71. class XfrinException(Exception):
  72. pass
  73. class XfrinProtocolError(Exception):
  74. '''An exception raised for errors encountered in xfrin protocol handling.
  75. '''
  76. pass
  77. class XfrinZoneInfoException(Exception):
  78. """This exception is raised if there is an error in the given
  79. configuration (part), or when a command does not have a required
  80. argument or has bad arguments, for instance when the zone's master
  81. address is not a valid IP address, when the zone does not
  82. have a name, or when multiple settings are given for the same
  83. zone."""
  84. pass
  85. def _check_zone_name(zone_name_str):
  86. """Checks if the given zone name is a valid domain name, and returns
  87. it as a Name object. Raises an XfrinException if it is not."""
  88. try:
  89. # In the _zones dict, part of the key is the zone name,
  90. # but due to a limitation in the Name class, we
  91. # cannot directly use it as a dict key, and we use to_text()
  92. #
  93. # Downcase the name here for that reason.
  94. return Name(zone_name_str, True)
  95. except (EmptyLabel, TooLongLabel, BadLabelType, BadEscape,
  96. TooLongName, IncompleteName) as ne:
  97. raise XfrinZoneInfoException("bad zone name: " + zone_name_str + " (" + str(ne) + ")")
  98. def _check_zone_class(zone_class_str):
  99. """If the given argument is a string: checks if the given class is
  100. a valid one, and returns an RRClass object if so.
  101. Raises XfrinZoneInfoException if not.
  102. If it is None, this function returns the default RRClass.IN()"""
  103. if zone_class_str is None:
  104. return DEFAULT_ZONE_CLASS
  105. try:
  106. return RRClass(zone_class_str)
  107. except InvalidRRClass as irce:
  108. raise XfrinZoneInfoException("bad zone class: " + zone_class_str + " (" + str(irce) + ")")
  109. def get_soa_serial(soa_rdata):
  110. '''Extract the serial field of an SOA RDATA and returns it as an intger.
  111. We don't have to be very efficient here, so we first dump the entire RDATA
  112. as a string and convert the first corresponding field. This should be
  113. sufficient in practice, but may not always work when the MNAME or RNAME
  114. contains an (escaped) space character in their labels. Ideally there
  115. should be a more direct and convenient way to get access to the SOA
  116. fields.
  117. '''
  118. return int(soa_rdata.to_text().split()[2])
  119. class XfrinState:
  120. '''
  121. The states of the incomding *XFR state machine.
  122. We (will) handle both IXFR and AXFR with a single integrated state
  123. machine because they cannot be distinguished immediately - an AXFR
  124. response to an IXFR request can only be detected when the first two (2)
  125. response RRs have already been received.
  126. The following diagram summarizes the state transition. After sending
  127. the query, xfrin starts the process with the InitialSOA state (all
  128. IXFR/AXFR response begins with an SOA). When it reaches IXFREnd
  129. or AXFREnd, the process successfully completes.
  130. (AXFR or
  131. (recv SOA) AXFR-style IXFR) (SOA, add)
  132. InitialSOA------->FirstData------------->AXFR--------->AXFREnd
  133. | | ^ (post xfr
  134. | | | checks, then
  135. | +--+ commit)
  136. | (non SOA, add)
  137. |
  138. | (non SOA, delete)
  139. (pure IXFR,| +-------+
  140. keep handling)| (Delete SOA) V |
  141. + ->IXFRDeleteSOA------>IXFRDelete--+
  142. ^ |
  143. (see SOA, not end, | (see SOA)|
  144. commit, keep handling) | |
  145. | V
  146. +---------IXFRAdd<----------+IXFRAddSOA
  147. (non SOA, add)| ^ | (Add SOA)
  148. ----------+ |
  149. |(see SOA w/ end serial, commit changes)
  150. V
  151. IXFREnd
  152. Note that changes are committed for every "difference sequence"
  153. (i.e. changes for one SOA update). This means when an IXFR response
  154. contains multiple difference sequences and something goes wrong
  155. after several commits, these changes have been published and visible
  156. to clients even if the IXFR session is subsequently aborted.
  157. It is not clear if this is valid in terms of the protocol specification.
  158. Section 4 of RFC 1995 states:
  159. An IXFR client, should only replace an older version with a newer
  160. version after all the differences have been successfully processed.
  161. If this "replacement" is for the changes of one difference sequence
  162. and "all the differences" mean the changes for that sequence, this
  163. implementation strictly follows what RFC states. If this is for
  164. the entire IXFR response (that may contain multiple sequences),
  165. we should implement it with one big transaction and one final commit
  166. at the very end.
  167. For now, we implement it with multiple smaller commits for two
  168. reasons. First, this is what BIND 9 does, and we generally port
  169. the implementation logic here. BIND 9 has been supporting IXFR
  170. for many years, so the fact that it still behaves this way
  171. probably means it at least doesn't cause a severe operational
  172. problem in practice. Second, especially because BIND 10 would
  173. often uses a database backend, a larger transaction could cause an
  174. undesirable effects, e.g. suspending normal lookups for a longer
  175. period depending on the characteristics of the database. Even if
  176. we find something wrong in a later sequeunce and abort the
  177. session, we can start another incremental update from what has
  178. been validated, or we can switch to AXFR to replace the zone
  179. completely.
  180. This implementation uses the state design pattern, where each state
  181. is represented as a subclass of the base XfrinState class. Each concrete
  182. subclass of XfrinState is assumed to define two methods: handle_rr() and
  183. finish_message(). These methods handle specific part of XFR protocols
  184. and (if necessary) perform the state transition.
  185. Conceptually, XfrinState and its subclasses are a "friend" of
  186. XfrinConnection and are assumed to be allowed to access its internal
  187. information (even though Python does not have a strict access control
  188. between different classes).
  189. The XfrinState and its subclasses are designed to be stateless, and
  190. can be used as singleton objects. For now, however, we always instantiate
  191. a new object for every state transition, partly because the introduction
  192. of singleton will make a code bit complicated, and partly because
  193. the overhead of object instantiotion wouldn't be significant for xfrin.
  194. '''
  195. def set_xfrstate(self, conn, new_state):
  196. '''Set the XfrConnection to a given new state.
  197. As a "friend" class, this method intentionally gets access to the
  198. connection's "private" method.
  199. '''
  200. conn._XfrinConnection__set_xfrstate(new_state)
  201. def handle_rr(self, conn):
  202. '''Handle one RR of an XFR response message.
  203. Depending on the state, the RR is generally added or deleted in the
  204. corresponding data source, or in some special cases indicates
  205. a specifi transition, such as starting a new IXFR difference
  206. sequence or completing the session.
  207. All subclass has their specific behaviors for this method, so
  208. there is no default definition. If the base class version
  209. is called, it's a bug of the caller, and it's notified via
  210. an XfrinException exception.
  211. This method returns a boolean value: True if the given RR was
  212. fully handled and the caller should go to the next RR; False
  213. if the caller needs to call this method with the (possibly) new
  214. state for the same RR again.
  215. '''
  216. raise XfrinException("Internal bug: " +
  217. "XfrinState.handle_rr() called directly")
  218. def finish_message(self, conn):
  219. '''Perform any final processing after handling all RRs of a response.
  220. This method then returns a boolean indicating whether to continue
  221. receiving the message. Unless it's in the end of the entire XFR
  222. session, we should continue, so this default method simply returns
  223. True.
  224. '''
  225. return True
  226. class XfrinInitialSOA(XfrinState):
  227. def handle_rr(self, conn, rr):
  228. if rr.get_type() != RRType.SOA():
  229. raise XfrinProtocolError('First RR in zone transfer must be SOA ('
  230. + rr.get_type().to_text() + ' received)')
  231. conn._end_serial = get_soa_serial(rr.get_rdata()[0])
  232. # FIXME: we need to check the serial is actually greater than ours.
  233. # To do so, however, we need to implement serial number arithmetic.
  234. # Although it wouldn't be a big task, we'll leave it for a separate
  235. # task for now. (Always performing xfr could be inefficient, but
  236. # shouldn't do any harm otherwise)
  237. self.set_xfrstate(conn, XfrinFirstData())
  238. return True
  239. class XfrinFirstData(XfrinState):
  240. def handle_rr(self, conn, rr):
  241. '''Handle the first RR after initial SOA in an XFR session.
  242. This state happens exactly once in an XFR session, where
  243. we decide whether it's incremental update ("real" IXFR) or
  244. non incremental update (AXFR or AXFR-style IXFR).
  245. If we initiated IXFR and the transfer begins with two SOAs
  246. (the serial of the second one being equal to our serial),
  247. it's incremental; otherwise it's non incremental.
  248. This method always return False (unlike many other handle_rr()
  249. methods) because this first RR must be examined again in the
  250. determined update context.
  251. Note that in the non incremental case the RR should normally be
  252. something other SOA, but it's still possible it's an SOA with a
  253. different serial than ours. The only possible interpretation at
  254. this point is that it's non incremental update that only consists
  255. of the SOA RR. It will result in broken zone (for example, it
  256. wouldn't even contain an apex NS) and should be rejected at post
  257. XFR processing, but in terms of the XFR session processing we
  258. accept it and move forward.
  259. Note further that, in the half-broken SOA-only transfer case,
  260. these two SOAs are supposed to be the same as stated in Section 2.2
  261. of RFC 5936. We don't check that condition here, either; we'll
  262. leave whether and how to deal with that situation to the end of
  263. the processing of non incremental update. See also a related
  264. discussion at the IETF dnsext wg:
  265. http://www.ietf.org/mail-archive/web/dnsext/current/msg07908.html
  266. '''
  267. if conn._request_type == RRType.IXFR() and \
  268. rr.get_type() == RRType.SOA() and \
  269. conn._request_serial == get_soa_serial(rr.get_rdata()[0]):
  270. logger.debug(DBG_XFRIN_TRACE, XFRIN_GOT_INCREMENTAL_RESP,
  271. conn.zone_str())
  272. self.set_xfrstate(conn, XfrinIXFRDeleteSOA())
  273. else:
  274. logger.debug(DBG_XFRIN_TRACE, XFRIN_GOT_NONINCREMENTAL_RESP,
  275. conn.zone_str())
  276. # We are now going to add RRs to the new zone. We need create
  277. # a Diff object. It will be used throughtout the XFR session.
  278. conn._diff = Diff(conn._datasrc_client, conn._zone_name, True)
  279. self.set_xfrstate(conn, XfrinAXFR())
  280. return False
  281. class XfrinIXFRDeleteSOA(XfrinState):
  282. def handle_rr(self, conn, rr):
  283. if rr.get_type() != RRType.SOA():
  284. # this shouldn't happen; should this occur it means an internal
  285. # bug.
  286. raise XfrinException(rr.get_type().to_text() +
  287. ' RR is given in IXFRDeleteSOA state')
  288. # This is the beginning state of one difference sequence (changes
  289. # for one SOA update). We need to create a new Diff object now.
  290. conn._diff = Diff(conn._datasrc_client, conn._zone_name)
  291. conn._diff.delete_data(rr)
  292. self.set_xfrstate(conn, XfrinIXFRDelete())
  293. return True
  294. class XfrinIXFRDelete(XfrinState):
  295. def handle_rr(self, conn, rr):
  296. if rr.get_type() == RRType.SOA():
  297. # This is the only place where current_serial is set
  298. conn._current_serial = get_soa_serial(rr.get_rdata()[0])
  299. self.set_xfrstate(conn, XfrinIXFRAddSOA())
  300. return False
  301. conn._diff.delete_data(rr)
  302. return True
  303. class XfrinIXFRAddSOA(XfrinState):
  304. def handle_rr(self, conn, rr):
  305. if rr.get_type() != RRType.SOA():
  306. # this shouldn't happen; should this occur it means an internal
  307. # bug.
  308. raise XfrinException(rr.get_type().to_text() +
  309. ' RR is given in IXFRAddSOA state')
  310. conn._diff.add_data(rr)
  311. self.set_xfrstate(conn, XfrinIXFRAdd())
  312. return True
  313. class XfrinIXFRAdd(XfrinState):
  314. def handle_rr(self, conn, rr):
  315. if rr.get_type() == RRType.SOA():
  316. soa_serial = get_soa_serial(rr.get_rdata()[0])
  317. if soa_serial == conn._end_serial:
  318. conn._diff.commit()
  319. self.set_xfrstate(conn, XfrinIXFREnd())
  320. return True
  321. elif soa_serial != conn._current_serial:
  322. raise XfrinProtocolError('IXFR out of sync: expected ' +
  323. 'serial ' +
  324. str(conn._current_serial) +
  325. ', got ' + str(soa_serial))
  326. else:
  327. conn._diff.commit()
  328. self.set_xfrstate(conn, XfrinIXFRDeleteSOA())
  329. return False
  330. conn._diff.add_data(rr)
  331. return True
  332. class XfrinIXFREnd(XfrinState):
  333. def handle_rr(self, conn, rr):
  334. raise XfrinProtocolError('Extra data after the end of IXFR diffs: ' +
  335. rr.to_text())
  336. def finish_message(self, conn):
  337. '''Final processing after processing an entire IXFR session.
  338. There will be more actions here, but for now we simply return False,
  339. indicating there will be no more message to receive.
  340. '''
  341. return False
  342. class XfrinAXFR(XfrinState):
  343. def handle_rr(self, conn, rr):
  344. """
  345. Handle the RR by putting it into the zone.
  346. """
  347. conn._diff.add_data(rr)
  348. if rr.get_type() == RRType.SOA():
  349. # SOA means end. Don't commit it yet - we need to perform
  350. # post-transfer checks
  351. soa_serial = get_soa_serial(rr.get_rdata()[0])
  352. if conn._end_serial != soa_serial:
  353. logger.warn(XFRIN_AXFR_INCONSISTENT_SOA, conn.zone_str(),
  354. conn._end_serial, soa_serial)
  355. self.set_xfrstate(conn, XfrinAXFREnd())
  356. # Yes, we've eaten this RR.
  357. return True
  358. class XfrinAXFREnd(XfrinState):
  359. def handle_rr(self, conn, rr):
  360. raise XfrinProtocolError('Extra data after the end of AXFR: ' +
  361. rr.to_text())
  362. def finish_message(self, conn):
  363. """
  364. Final processing after processing an entire AXFR session.
  365. In this process all the AXFR changes are committed to the
  366. data source.
  367. There might be more actions here, but for now we simply return False,
  368. indicating there will be no more message to receive.
  369. """
  370. conn._diff.commit()
  371. return False
  372. class XfrinConnection(asyncore.dispatcher):
  373. '''Do xfrin in this class. '''
  374. def __init__(self,
  375. sock_map, zone_name, rrclass, datasrc_client,
  376. shutdown_event, master_addrinfo, tsig_key=None,
  377. idle_timeout=60):
  378. '''Constructor of the XfirnConnection class.
  379. idle_timeout: max idle time for read data from socket.
  380. datasrc_client: the data source client object used for the XFR session.
  381. This will eventually replace db_file completely.
  382. '''
  383. asyncore.dispatcher.__init__(self, map=sock_map)
  384. # The XFR state. Conceptually this is purely private, so we emphasize
  385. # the fact by the double underscore. Other classes are assumed to
  386. # get access to this via get_xfrstate(), and only XfrinState classes
  387. # are assumed to be allowed to modify it via __set_xfrstate().
  388. self.__state = None
  389. # Requested transfer type (RRType.AXFR or RRType.IXFR). The actual
  390. # transfer type may differ due to IXFR->AXFR fallback:
  391. self._request_type = None
  392. # Zone parameters
  393. self._zone_name = zone_name
  394. self._rrclass = rrclass
  395. # Data source handler
  396. self._datasrc_client = datasrc_client
  397. self.create_socket(master_addrinfo[0], master_addrinfo[1])
  398. self._sock_map = sock_map
  399. self._soa_rr_count = 0
  400. self._idle_timeout = idle_timeout
  401. self.setblocking(1)
  402. self._shutdown_event = shutdown_event
  403. self._master_address = master_addrinfo[2]
  404. self._tsig_key = tsig_key
  405. self._tsig_ctx = None
  406. # tsig_ctx_creator is introduced to allow tests to use a mock class for
  407. # easier tests (in normal case we always use the default)
  408. self._tsig_ctx_creator = self.__create_tsig_ctx
  409. def __create_tsig_ctx(self, key):
  410. return TSIGContext(key)
  411. def __set_xfrstate(self, new_state):
  412. self.__state = new_state
  413. def get_xfrstate(self):
  414. return self.__state
  415. def zone_str(self):
  416. '''A convenient function for logging to include zone name and class'''
  417. return self._zone_name.to_text() + '/' + str(self._rrclass)
  418. def connect_to_master(self):
  419. '''Connect to master in TCP.'''
  420. try:
  421. self.connect(self._master_address)
  422. return True
  423. except socket.error as e:
  424. logger.error(XFRIN_CONNECT_MASTER, self._master_address, str(e))
  425. return False
  426. def _create_query(self, query_type):
  427. '''Create an XFR-related query message.
  428. query_type is either SOA, AXFR or IXFR. For type IXFR, it searches
  429. the associated data source for the current SOA record to include
  430. it in the query. If the corresponding zone or the SOA record
  431. cannot be found, it raises an XfrinException exception. Note that
  432. this may not necessarily a broken configuration; for the first attempt
  433. of transfer the secondary may not have any boot-strap zone
  434. information, in which case IXFR simply won't work. The xfrin
  435. should then fall back to AXFR. _request_serial is recorded for
  436. later use.
  437. '''
  438. msg = Message(Message.RENDER)
  439. query_id = random.randint(0, 0xFFFF)
  440. self._query_id = query_id
  441. msg.set_qid(query_id)
  442. msg.set_opcode(Opcode.QUERY())
  443. msg.set_rcode(Rcode.NOERROR())
  444. msg.add_question(Question(self._zone_name, self._rrclass, query_type))
  445. if query_type == RRType.IXFR():
  446. # get the zone finder. this must be SUCCESS (not even
  447. # PARTIALMATCH) because we are specifying the zone origin name.
  448. result, finder = self._datasrc_client.find_zone(self._zone_name)
  449. if result != DataSourceClient.SUCCESS:
  450. raise XfrinException('Zone not found in the given data ' +
  451. 'source: ' + self.zone_str())
  452. result, soa_rrset = finder.find(self._zone_name, RRType.SOA(),
  453. None, ZoneFinder.FIND_DEFAULT)
  454. if result != ZoneFinder.SUCCESS:
  455. raise XfrinException('SOA RR not found in zone: ' +
  456. self.zone_str())
  457. # Especially for database-based zones, a working zone may be in
  458. # a broken state where it has more than one SOA RR. We proactively
  459. # check the condition and abort the xfr attempt if we identify it.
  460. if soa_rrset.get_rdata_count() != 1:
  461. raise XfrinException('Invalid number of SOA RRs for ' +
  462. self.zone_str() + ': ' +
  463. str(soa_rrset.get_rdata_count()))
  464. msg.add_rrset(Message.SECTION_AUTHORITY, soa_rrset)
  465. self._request_serial = get_soa_serial(soa_rrset.get_rdata()[0])
  466. return msg
  467. def _send_data(self, data):
  468. size = len(data)
  469. total_count = 0
  470. while total_count < size:
  471. count = self.send(data[total_count:])
  472. total_count += count
  473. def _send_query(self, query_type):
  474. '''Send query message over TCP. '''
  475. msg = self._create_query(query_type)
  476. render = MessageRenderer()
  477. # XXX Currently, python wrapper doesn't accept 'None' parameter in this case,
  478. # we should remove the if statement and use a universal interface later.
  479. if self._tsig_key is not None:
  480. self._tsig_ctx = self._tsig_ctx_creator(self._tsig_key)
  481. msg.to_wire(render, self._tsig_ctx)
  482. else:
  483. msg.to_wire(render)
  484. header_len = struct.pack('H', socket.htons(render.get_length()))
  485. self._send_data(header_len)
  486. self._send_data(render.get_data())
  487. def _asyncore_loop(self):
  488. '''
  489. This method is a trivial wrapper for asyncore.loop(). It's extracted from
  490. _get_request_response so that we can test the rest of the code without
  491. involving actual communication with a remote server.'''
  492. asyncore.loop(self._idle_timeout, map=self._sock_map, count=1)
  493. def _get_request_response(self, size):
  494. recv_size = 0
  495. data = b''
  496. while recv_size < size:
  497. self._recv_time_out = True
  498. self._need_recv_size = size - recv_size
  499. self._asyncore_loop()
  500. if self._recv_time_out:
  501. raise XfrinException('receive data from socket time out.')
  502. recv_size += self._recvd_size
  503. data += self._recvd_data
  504. return data
  505. def _check_response_tsig(self, msg, response_data):
  506. tsig_record = msg.get_tsig_record()
  507. if self._tsig_ctx is not None:
  508. tsig_error = self._tsig_ctx.verify(tsig_record, response_data)
  509. if tsig_error != TSIGError.NOERROR:
  510. raise XfrinException('TSIG verify fail: %s' % str(tsig_error))
  511. elif tsig_record is not None:
  512. # If the response includes a TSIG while we didn't sign the query,
  513. # we treat it as an error. RFC doesn't say anything about this
  514. # case, but it clearly states the server must not sign a response
  515. # to an unsigned request. Although we could be flexible, no sane
  516. # implementation would return such a response, and since this is
  517. # part of security mechanism, it's probably better to be more
  518. # strict.
  519. raise XfrinException('Unexpected TSIG in response')
  520. def _check_soa_serial(self):
  521. ''' Compare the soa serial, if soa serial in master is less than
  522. the soa serial in local, Finish xfrin.
  523. False: soa serial in master is less or equal to the local one.
  524. True: soa serial in master is bigger
  525. '''
  526. self._send_query(RRType.SOA())
  527. data_len = self._get_request_response(2)
  528. msg_len = socket.htons(struct.unpack('H', data_len)[0])
  529. soa_response = self._get_request_response(msg_len)
  530. msg = Message(Message.PARSE)
  531. msg.from_wire(soa_response)
  532. # TSIG related checks, including an unexpected signed response
  533. self._check_response_tsig(msg, soa_response)
  534. # perform some minimal level validation. It's an open issue how
  535. # strict we should be (see the comment in _check_response_header())
  536. self._check_response_header(msg)
  537. # TODO, need select soa record from data source then compare the two
  538. # serial, current just return OK, since this function hasn't been used
  539. # now.
  540. return XFRIN_OK
  541. def do_xfrin(self, check_soa, request_type=RRType.AXFR()):
  542. '''Do an xfr session by sending xfr request and parsing responses.'''
  543. try:
  544. ret = XFRIN_OK
  545. self._request_type = request_type
  546. # Right now RRType.[IA]XFR().to_text() is 'TYPExxx', so we need
  547. # to hardcode here.
  548. request_str = 'IXFR' if request_type == RRType.IXFR() else 'AXFR'
  549. if check_soa:
  550. ret = self._check_soa_serial()
  551. if ret == XFRIN_OK:
  552. logger.info(XFRIN_XFR_TRANSFER_STARTED, request_str,
  553. self.zone_str())
  554. self._send_query(self._request_type)
  555. self.__state = XfrinInitialSOA()
  556. self._handle_xfrin_responses()
  557. logger.info(XFRIN_XFR_TRANSFER_SUCCESS, request_str,
  558. self.zone_str())
  559. except (XfrinException, XfrinProtocolError) as e:
  560. logger.error(XFRIN_XFR_TRANSFER_FAILURE, request_str,
  561. self.zone_str(), str(e))
  562. ret = XFRIN_FAIL
  563. except Exception as e:
  564. # Catching all possible exceptions like this is generally not a
  565. # good practice, but handling an xfr session could result in
  566. # so many types of exceptions, including ones from the DNS library
  567. # or from the data source library. Eventually we'd introduce a
  568. # hierarchy for exception classes from a base "ISC exception" and
  569. # catch it here, but until then we need broadest coverage so that
  570. # we won't miss anything.
  571. logger.error(XFRIN_XFR_OTHER_FAILURE, request_str,
  572. self.zone_str(), str(e))
  573. ret = XFRIN_FAIL
  574. finally:
  575. # Make sure any remaining transaction in the diff is closed
  576. # (if not yet - possible in case of xfr-level exception) as soon
  577. # as possible
  578. self._diff = None
  579. self.close()
  580. return ret
  581. def _check_response_header(self, msg):
  582. '''Perform minimal validation on responses'''
  583. # It's not clear how strict we should be about response validation.
  584. # BIND 9 ignores some cases where it would normally be considered a
  585. # bogus response. For example, it accepts a response even if its
  586. # opcode doesn't match that of the corresponding request.
  587. # According to an original developer of BIND 9 some of the missing
  588. # checks are deliberate to be kind to old implementations that would
  589. # cause interoperability trouble with stricter checks.
  590. msg_rcode = msg.get_rcode()
  591. if msg_rcode != Rcode.NOERROR():
  592. raise XfrinException('error response: %s' % msg_rcode.to_text())
  593. if not msg.get_header_flag(Message.HEADERFLAG_QR):
  594. raise XfrinException('response is not a response')
  595. if msg.get_qid() != self._query_id:
  596. raise XfrinException('bad query id')
  597. def _check_response_status(self, msg):
  598. '''Check validation of xfr response. '''
  599. self._check_response_header(msg)
  600. if msg.get_rr_count(Message.SECTION_QUESTION) > 1:
  601. raise XfrinException('query section count greater than 1')
  602. def _handle_answer_section(self, answer_section):
  603. '''Return a generator for the reponse in one tcp package to a zone transfer.'''
  604. for rrset in answer_section:
  605. rrset_name = rrset.get_name().to_text()
  606. rrset_ttl = int(rrset.get_ttl().to_text())
  607. rrset_class = rrset.get_class().to_text()
  608. rrset_type = rrset.get_type().to_text()
  609. for rdata in rrset.get_rdata():
  610. # Count the soa record count
  611. if rrset.get_type() == RRType.SOA():
  612. self._soa_rr_count += 1
  613. # XXX: the current DNS message parser can't preserve the
  614. # RR order or separete the beginning and ending SOA RRs.
  615. # As a short term workaround, we simply ignore the second
  616. # SOA, and ignore the erroneous case where the transfer
  617. # session doesn't end with an SOA.
  618. if (self._soa_rr_count == 2):
  619. # Avoid inserting soa record twice
  620. break
  621. rdata_text = rdata.to_text()
  622. yield (rrset_name, rrset_ttl, rrset_class, rrset_type,
  623. rdata_text)
  624. def _handle_xfrin_responses(self):
  625. read_next_msg = True
  626. while read_next_msg:
  627. data_len = self._get_request_response(2)
  628. msg_len = socket.htons(struct.unpack('H', data_len)[0])
  629. recvdata = self._get_request_response(msg_len)
  630. msg = Message(Message.PARSE)
  631. msg.from_wire(recvdata, Message.PRESERVE_ORDER)
  632. # TSIG related checks, including an unexpected signed response
  633. self._check_response_tsig(msg, recvdata)
  634. # Perform response status validation
  635. self._check_response_status(msg)
  636. for rr in msg.get_section(Message.SECTION_ANSWER):
  637. rr_handled = False
  638. while not rr_handled:
  639. rr_handled = self.__state.handle_rr(self, rr)
  640. read_next_msg = self.__state.finish_message(self)
  641. if self._shutdown_event.is_set():
  642. raise XfrinException('xfrin is forced to stop')
  643. def handle_read(self):
  644. '''Read query's response from socket. '''
  645. self._recvd_data = self.recv(self._need_recv_size)
  646. self._recvd_size = len(self._recvd_data)
  647. self._recv_time_out = False
  648. def writable(self):
  649. '''Ignore the writable socket. '''
  650. return False
  651. def log_info(self, msg, type='info'):
  652. # Overwrite the log function, log nothing
  653. pass
  654. def process_xfrin(server, xfrin_recorder, zone_name, rrclass, db_file,
  655. shutdown_event, master_addrinfo, check_soa, tsig_key,
  656. request_type):
  657. xfrin_recorder.increment(zone_name)
  658. # Create a data source client used in this XFR session. Right now we
  659. # still assume an sqlite3-based data source, and use both the old and new
  660. # data source APIs. We also need to use a mock client for tests.
  661. # For a temporary workaround to deal with these situations, we skip the
  662. # creation when the given file is none (the test case). Eventually
  663. # this code will be much cleaner.
  664. datasrc_client = None
  665. if db_file is not None:
  666. # temporary hardcoded sqlite initialization. Once we decide on
  667. # the config specification, we need to update this (TODO)
  668. # this may depend on #1207, or any followup ticket created for #1207
  669. datasrc_type = "sqlite3"
  670. datasrc_config = "{ \"database_file\": \"" + db_file + "\"}"
  671. datasrc_client = DataSourceClient(datasrc_type, datasrc_config)
  672. # Create a TCP connection for the XFR session and perform the operation.
  673. sock_map = {}
  674. conn = XfrinConnection(sock_map, zone_name, rrclass, datasrc_client,
  675. shutdown_event, master_addrinfo, tsig_key)
  676. ret = XFRIN_FAIL
  677. if conn.connect_to_master():
  678. ret = conn.do_xfrin(check_soa, request_type)
  679. # Publish the zone transfer result news, so zonemgr can reset the
  680. # zone timer, and xfrout can notify the zone's slaves if the result
  681. # is success.
  682. server.publish_xfrin_news(zone_name, rrclass, ret)
  683. xfrin_recorder.decrement(zone_name)
  684. class XfrinRecorder:
  685. def __init__(self):
  686. self._lock = threading.Lock()
  687. self._zones = []
  688. def increment(self, zone_name):
  689. self._lock.acquire()
  690. self._zones.append(zone_name)
  691. self._lock.release()
  692. def decrement(self, zone_name):
  693. self._lock.acquire()
  694. if zone_name in self._zones:
  695. self._zones.remove(zone_name)
  696. self._lock.release()
  697. def xfrin_in_progress(self, zone_name):
  698. self._lock.acquire()
  699. ret = zone_name in self._zones
  700. self._lock.release()
  701. return ret
  702. def count(self):
  703. self._lock.acquire()
  704. ret = len(self._zones)
  705. self._lock.release()
  706. return ret
  707. class ZoneInfo:
  708. def __init__(self, config_data, module_cc):
  709. """Creates a zone_info with the config data element as
  710. specified by the 'zones' list in xfrin.spec. Module_cc is
  711. needed to get the defaults from the specification"""
  712. self._module_cc = module_cc
  713. self.set_name(config_data.get('name'))
  714. self.set_master_addr(config_data.get('master_addr'))
  715. self.set_master_port(config_data.get('master_port'))
  716. self.set_zone_class(config_data.get('class'))
  717. self.set_tsig_key(config_data.get('tsig_key'))
  718. self.set_ixfr_disabled(config_data.get('ixfr_disabled'))
  719. def set_name(self, name_str):
  720. """Set the name for this zone given a name string.
  721. Raises XfrinZoneInfoException if name_str is None or if it
  722. cannot be parsed."""
  723. if name_str is None:
  724. raise XfrinZoneInfoException("Configuration zones list "
  725. "element does not contain "
  726. "'name' attribute")
  727. else:
  728. self.name = _check_zone_name(name_str)
  729. def set_master_addr(self, master_addr_str):
  730. """Set the master address for this zone given an IP address
  731. string. Raises XfrinZoneInfoException if master_addr_str is
  732. None or if it cannot be parsed."""
  733. if master_addr_str is None:
  734. raise XfrinZoneInfoException("master address missing from config data")
  735. else:
  736. try:
  737. self.master_addr = isc.net.parse.addr_parse(master_addr_str)
  738. except ValueError:
  739. logger.error(XFRIN_BAD_MASTER_ADDR_FORMAT, master_addr_str)
  740. errmsg = "bad format for zone's master: " + master_addr_str
  741. raise XfrinZoneInfoException(errmsg)
  742. def set_master_port(self, master_port_str):
  743. """Set the master port given a port number string. If
  744. master_port_str is None, the default from the specification
  745. for this module will be used. Raises XfrinZoneInfoException if
  746. the string contains an invalid port number"""
  747. if master_port_str is None:
  748. self.master_port = self._module_cc.get_default_value("zones/master_port")
  749. else:
  750. try:
  751. self.master_port = isc.net.parse.port_parse(master_port_str)
  752. except ValueError:
  753. logger.error(XFRIN_BAD_MASTER_PORT_FORMAT, master_port_str)
  754. errmsg = "bad format for zone's master port: " + master_port_str
  755. raise XfrinZoneInfoException(errmsg)
  756. def set_zone_class(self, zone_class_str):
  757. """Set the zone class given an RR class str (e.g. "IN"). If
  758. zone_class_str is None, it will default to what is specified
  759. in the specification file for this module. Raises
  760. XfrinZoneInfoException if the string cannot be parsed."""
  761. # TODO: remove _str
  762. self.class_str = zone_class_str or self._module_cc.get_default_value("zones/class")
  763. if zone_class_str == None:
  764. #TODO rrclass->zone_class
  765. self.rrclass = RRClass(self._module_cc.get_default_value("zones/class"))
  766. else:
  767. try:
  768. self.rrclass = RRClass(zone_class_str)
  769. except InvalidRRClass:
  770. logger.error(XFRIN_BAD_ZONE_CLASS, zone_class_str)
  771. errmsg = "invalid zone class: " + zone_class_str
  772. raise XfrinZoneInfoException(errmsg)
  773. def set_tsig_key(self, tsig_key_str):
  774. """Set the tsig_key for this zone, given a TSIG key string
  775. representation. If tsig_key_str is None, no TSIG key will
  776. be set. Raises XfrinZoneInfoException if tsig_key_str cannot
  777. be parsed."""
  778. if tsig_key_str is None:
  779. self.tsig_key = None
  780. else:
  781. try:
  782. self.tsig_key = TSIGKey(tsig_key_str)
  783. except InvalidParameter as ipe:
  784. logger.error(XFRIN_BAD_TSIG_KEY_STRING, tsig_key_str)
  785. errmsg = "bad TSIG key string: " + tsig_key_str
  786. raise XfrinZoneInfoException(errmsg)
  787. def set_ixfr_disabled(self, ixfr_disabled):
  788. """Set ixfr_disabled. If set to False (the default), it will use
  789. IXFR for incoming transfers. If set to True, it will use AXFR.
  790. At this moment there is no automatic fallback"""
  791. # don't care what type it is; if evaluates to true, set to True
  792. if ixfr_disabled:
  793. self.ixfr_disabled = True
  794. else:
  795. self.ixfr_disabled = False
  796. def get_master_addr_info(self):
  797. return (self.master_addr.family, socket.SOCK_STREAM,
  798. (str(self.master_addr), self.master_port))
  799. class Xfrin:
  800. def __init__(self):
  801. self._max_transfers_in = 10
  802. self._zones = {}
  803. self._cc_setup()
  804. self.recorder = XfrinRecorder()
  805. self._shutdown_event = threading.Event()
  806. def _cc_setup(self):
  807. '''This method is used only as part of initialization, but is
  808. implemented separately for convenience of unit tests; by letting
  809. the test code override this method we can test most of this class
  810. without requiring a command channel.'''
  811. # Create one session for sending command to other modules, because the
  812. # listening session will block the send operation.
  813. self._send_cc_session = isc.cc.Session()
  814. self._module_cc = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  815. self.config_handler,
  816. self.command_handler)
  817. self._module_cc.start()
  818. config_data = self._module_cc.get_full_config()
  819. self.config_handler(config_data)
  820. def _cc_check_command(self):
  821. '''This is a straightforward wrapper for cc.check_command,
  822. but provided as a separate method for the convenience
  823. of unit tests.'''
  824. self._module_cc.check_command(False)
  825. def _get_zone_info(self, name, rrclass):
  826. """Returns the ZoneInfo object containing the configured data
  827. for the given zone name. If the zone name did not have any
  828. data, returns None"""
  829. return self._zones.get((name.to_text(), rrclass.to_text()))
  830. def _add_zone_info(self, zone_info):
  831. """Add the zone info. Raises a XfrinZoneInfoException if a zone
  832. with the same name and class is already configured"""
  833. key = (zone_info.name.to_text(), zone_info.class_str)
  834. if key in self._zones:
  835. raise XfrinZoneInfoException("zone " + str(key) +
  836. " configured multiple times")
  837. self._zones[key] = zone_info
  838. def _clear_zone_info(self):
  839. self._zones = {}
  840. def config_handler(self, new_config):
  841. # backup all config data (should there be a problem in the new
  842. # data)
  843. old_max_transfers_in = self._max_transfers_in
  844. old_zones = self._zones
  845. self._max_transfers_in = new_config.get("transfers_in") or self._max_transfers_in
  846. if 'zones' in new_config:
  847. self._clear_zone_info()
  848. for zone_config in new_config.get('zones'):
  849. try:
  850. zone_info = ZoneInfo(zone_config, self._module_cc)
  851. self._add_zone_info(zone_info)
  852. except XfrinZoneInfoException as xce:
  853. self._zones = old_zones
  854. self._max_transfers_in = old_max_transfers_in
  855. return create_answer(1, str(xce))
  856. return create_answer(0)
  857. def shutdown(self):
  858. ''' shutdown the xfrin process. the thread which is doing xfrin should be
  859. terminated.
  860. '''
  861. self._shutdown_event.set()
  862. main_thread = threading.currentThread()
  863. for th in threading.enumerate():
  864. if th is main_thread:
  865. continue
  866. th.join()
  867. def command_handler(self, command, args):
  868. answer = create_answer(0)
  869. try:
  870. if command == 'shutdown':
  871. self._shutdown_event.set()
  872. elif command == 'notify' or command == REFRESH_FROM_ZONEMGR:
  873. # Xfrin receives the refresh/notify command from zone manager.
  874. # notify command maybe has the parameters which
  875. # specify the notifyfrom address and port, according the RFC1996, zone
  876. # transfer should starts first from the notifyfrom, but now, let 'TODO' it.
  877. # (using the value now, while we can only set one master address, would be
  878. # a security hole. Once we add the ability to have multiple master addresses,
  879. # we should check if it matches one of them, and then use it.)
  880. (zone_name, rrclass) = self._parse_zone_name_and_class(args)
  881. zone_info = self._get_zone_info(zone_name, rrclass)
  882. if zone_info is None:
  883. # TODO what to do? no info known about zone. defaults?
  884. errmsg = "Got notification to retransfer unknown zone " + zone_name.to_text()
  885. logger.error(XFRIN_RETRANSFER_UNKNOWN_ZONE, zone_name.to_text())
  886. answer = create_answer(1, errmsg)
  887. else:
  888. master_addr = zone_info.get_master_addr_info()
  889. ret = self.xfrin_start(zone_name,
  890. rrclass,
  891. self._get_db_file(),
  892. master_addr,
  893. zone_info.tsig_key, RRType.AXFR(),
  894. True)
  895. answer = create_answer(ret[0], ret[1])
  896. elif command == 'retransfer' or command == 'refresh':
  897. # Xfrin receives the retransfer/refresh from cmdctl(sent by bindctl).
  898. # If the command has specified master address, do transfer from the
  899. # master address, or else do transfer from the configured masters.
  900. (zone_name, rrclass) = self._parse_zone_name_and_class(args)
  901. master_addr = self._parse_master_and_port(args, zone_name,
  902. rrclass)
  903. zone_info = self._get_zone_info(zone_name, rrclass)
  904. tsig_key = None
  905. request_type = RRType.AXFR()
  906. if zone_info:
  907. tsig_key = zone_info.tsig_key
  908. if not zone_info.ixfr_disabled:
  909. request_type = RRType.IXFR()
  910. db_file = args.get('db_file') or self._get_db_file()
  911. ret = self.xfrin_start(zone_name,
  912. rrclass,
  913. db_file,
  914. master_addr,
  915. tsig_key, request_type,
  916. (False if command == 'retransfer' else True))
  917. answer = create_answer(ret[0], ret[1])
  918. else:
  919. answer = create_answer(1, 'unknown command: ' + command)
  920. except XfrinException as err:
  921. logger.error(XFRIN_COMMAND_ERROR, command, str(err))
  922. answer = create_answer(1, str(err))
  923. return answer
  924. def _parse_zone_name_and_class(self, args):
  925. zone_name_str = args.get('zone_name')
  926. if zone_name_str is None:
  927. raise XfrinException('zone name should be provided')
  928. return (_check_zone_name(zone_name_str), _check_zone_class(args.get('zone_class')))
  929. def _parse_master_and_port(self, args, zone_name, zone_class):
  930. """
  931. Return tuple (family, socktype, sockaddr) for address and port in given
  932. args dict.
  933. IPv4 and IPv6 are the only supported addresses now, so sockaddr will be
  934. (address, port). The socktype is socket.SOCK_STREAM for now.
  935. """
  936. # check if we have configured info about this zone, in case
  937. # port or master are not specified
  938. zone_info = self._get_zone_info(zone_name, zone_class)
  939. addr_str = args.get('master')
  940. if addr_str is None:
  941. if zone_info is not None:
  942. addr = zone_info.master_addr
  943. else:
  944. raise XfrinException("Master address not given or "
  945. "configured for " + zone_name.to_text())
  946. else:
  947. try:
  948. addr = isc.net.parse.addr_parse(addr_str)
  949. except ValueError as err:
  950. raise XfrinException("failed to resolve master address %s: %s" %
  951. (addr_str, str(err)))
  952. port_str = args.get('port')
  953. if port_str is None:
  954. if zone_info is not None:
  955. port = zone_info.master_port
  956. else:
  957. port = DEFAULT_MASTER_PORT
  958. else:
  959. try:
  960. port = isc.net.parse.port_parse(port_str)
  961. except ValueError as err:
  962. raise XfrinException("failed to parse port=%s: %s" %
  963. (port_str, str(err)))
  964. return (addr.family, socket.SOCK_STREAM, (str(addr), port))
  965. def _get_db_file(self):
  966. #TODO, the db file path should be got in auth server's configuration
  967. # if we need access to this configuration more often, we
  968. # should add it on start, and not remove it here
  969. # (or, if we have writable ds, we might not need this in
  970. # the first place)
  971. self._module_cc.add_remote_config(AUTH_SPECFILE_LOCATION)
  972. db_file, is_default = self._module_cc.get_remote_config_value("Auth", "database_file")
  973. if is_default and "B10_FROM_BUILD" in os.environ:
  974. # this too should be unnecessary, but currently the
  975. # 'from build' override isn't stored in the config
  976. # (and we don't have writable datasources yet)
  977. db_file = os.environ["B10_FROM_BUILD"] + os.sep + "bind10_zones.sqlite3"
  978. self._module_cc.remove_remote_config(AUTH_SPECFILE_LOCATION)
  979. return db_file
  980. def publish_xfrin_news(self, zone_name, zone_class, xfr_result):
  981. '''Send command to xfrout/zone manager module.
  982. If xfrin has finished successfully for one zone, tell the good
  983. news(command: zone_new_data_ready) to zone manager and xfrout.
  984. if xfrin failed, just tell the bad news to zone manager, so that
  985. it can reset the refresh timer for that zone. '''
  986. param = {'zone_name': zone_name.to_text(),
  987. 'zone_class': zone_class.to_text()}
  988. if xfr_result == XFRIN_OK:
  989. msg = create_command(notify_out.ZONE_NEW_DATA_READY_CMD, param)
  990. # catch the exception, in case msgq has been killed.
  991. try:
  992. seq = self._send_cc_session.group_sendmsg(msg,
  993. XFROUT_MODULE_NAME)
  994. try:
  995. answer, env = self._send_cc_session.group_recvmsg(False,
  996. seq)
  997. except isc.cc.session.SessionTimeout:
  998. pass # for now we just ignore the failure
  999. seq = self._send_cc_session.group_sendmsg(msg, ZONE_MANAGER_MODULE_NAME)
  1000. try:
  1001. answer, env = self._send_cc_session.group_recvmsg(False,
  1002. seq)
  1003. except isc.cc.session.SessionTimeout:
  1004. pass # for now we just ignore the failure
  1005. except socket.error as err:
  1006. logger.error(XFRIN_MSGQ_SEND_ERROR, XFROUT_MODULE_NAME, ZONE_MANAGER_MODULE_NAME)
  1007. else:
  1008. msg = create_command(ZONE_XFRIN_FAILED, param)
  1009. # catch the exception, in case msgq has been killed.
  1010. try:
  1011. seq = self._send_cc_session.group_sendmsg(msg, ZONE_MANAGER_MODULE_NAME)
  1012. try:
  1013. answer, env = self._send_cc_session.group_recvmsg(False,
  1014. seq)
  1015. except isc.cc.session.SessionTimeout:
  1016. pass # for now we just ignore the failure
  1017. except socket.error as err:
  1018. logger.error(XFRIN_MSGQ_SEND_ERROR_ZONE_MANAGER, ZONE_MANAGER_MODULE_NAME)
  1019. def startup(self):
  1020. while not self._shutdown_event.is_set():
  1021. self._cc_check_command()
  1022. def xfrin_start(self, zone_name, rrclass, db_file, master_addrinfo,
  1023. tsig_key, request_type, check_soa=True):
  1024. if "pydnspp" not in sys.modules:
  1025. return (1, "xfrin failed, can't load dns message python library: 'pydnspp'")
  1026. # check max_transfer_in, else return quota error
  1027. if self.recorder.count() >= self._max_transfers_in:
  1028. return (1, 'xfrin quota error')
  1029. if self.recorder.xfrin_in_progress(zone_name):
  1030. return (1, 'zone xfrin is in progress')
  1031. xfrin_thread = threading.Thread(target = process_xfrin,
  1032. args = (self,
  1033. self.recorder,
  1034. zone_name,
  1035. rrclass,
  1036. db_file,
  1037. self._shutdown_event,
  1038. master_addrinfo, check_soa,
  1039. tsig_key, request_type))
  1040. xfrin_thread.start()
  1041. return (0, 'zone xfrin is started')
  1042. xfrind = None
  1043. def signal_handler(signal, frame):
  1044. if xfrind:
  1045. xfrind.shutdown()
  1046. sys.exit(0)
  1047. def set_signal_handler():
  1048. signal.signal(signal.SIGTERM, signal_handler)
  1049. signal.signal(signal.SIGINT, signal_handler)
  1050. def set_cmd_options(parser):
  1051. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  1052. help="This option is obsolete and has no effect.")
  1053. def main(xfrin_class, use_signal=True):
  1054. """The main loop of the Xfrin daemon.
  1055. @param xfrin_class: A class of the Xfrin object. This is normally Xfrin,
  1056. but can be a subclass of it for customization.
  1057. @param use_signal: True if this process should catch signals. This is
  1058. normally True, but may be disabled when this function is called in a
  1059. testing context."""
  1060. global xfrind
  1061. try:
  1062. parser = OptionParser(version = __version__)
  1063. set_cmd_options(parser)
  1064. (options, args) = parser.parse_args()
  1065. if use_signal:
  1066. set_signal_handler()
  1067. xfrind = xfrin_class()
  1068. xfrind.startup()
  1069. except KeyboardInterrupt:
  1070. logger.info(XFRIN_STOPPED_BY_KEYBOARD)
  1071. except isc.cc.session.SessionError as e:
  1072. logger.error(XFRIN_CC_SESSION_ERROR, str(e))
  1073. except Exception as e:
  1074. logger.error(XFRIN_UNKNOWN_ERROR, str(e))
  1075. if xfrind:
  1076. xfrind.shutdown()
  1077. if __name__ == '__main__':
  1078. main(Xfrin)