xfrin.py.in 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707
  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. import time
  26. from functools import reduce
  27. from optparse import OptionParser, OptionValueError
  28. from isc.config.ccsession import *
  29. from isc.notify import notify_out
  30. import isc.util.process
  31. from isc.datasrc import DataSourceClient, ZoneFinder
  32. import isc.net.parse
  33. from isc.xfrin.diff import Diff
  34. from isc.log_messages.xfrin_messages import *
  35. isc.log.init("b10-xfrin")
  36. logger = isc.log.Logger("xfrin")
  37. # Pending system-wide debug level definitions, the ones we
  38. # use here are hardcoded for now
  39. DBG_PROCESS = logger.DBGLVL_TRACE_BASIC
  40. DBG_COMMANDS = logger.DBGLVL_TRACE_DETAIL
  41. try:
  42. from pydnspp import *
  43. except ImportError as e:
  44. # C++ loadable module may not be installed; even so the xfrin process
  45. # must keep running, so we warn about it and move forward.
  46. logger.error(XFRIN_IMPORT_DNS, str(e))
  47. isc.util.process.rename()
  48. # If B10_FROM_BUILD is set in the environment, we use data files
  49. # from a directory relative to that, otherwise we use the ones
  50. # installed on the system
  51. if "B10_FROM_BUILD" in os.environ:
  52. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/xfrin"
  53. AUTH_SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/auth"
  54. else:
  55. PREFIX = "@prefix@"
  56. DATAROOTDIR = "@datarootdir@"
  57. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  58. AUTH_SPECFILE_PATH = SPECFILE_PATH
  59. SPECFILE_LOCATION = SPECFILE_PATH + "/xfrin.spec"
  60. AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + "/auth.spec"
  61. AUTH_MODULE_NAME = 'Auth'
  62. XFROUT_MODULE_NAME = 'Xfrout'
  63. ZONE_MANAGER_MODULE_NAME = 'Zonemgr'
  64. REFRESH_FROM_ZONEMGR = 'refresh_from_zonemgr'
  65. ZONE_XFRIN_FAILED = 'zone_xfrin_failed'
  66. # Constants for debug levels.
  67. DBG_XFRIN_TRACE = logger.DBGLVL_TRACE_BASIC
  68. # These two default are currently hard-coded. For config this isn't
  69. # necessary, but we need these defaults for optional command arguments
  70. # (TODO: have similar support to get default values for command
  71. # arguments as we do for config options)
  72. DEFAULT_MASTER_PORT = 53
  73. DEFAULT_ZONE_CLASS = RRClass.IN()
  74. __version__ = 'BIND10'
  75. # Internal result codes of an xfr session
  76. XFRIN_OK = 0 # normal success
  77. XFRIN_FAIL = 1 # general failure (internal/external)
  78. class XfrinException(Exception):
  79. pass
  80. class XfrinProtocolError(Exception):
  81. '''An exception raised for errors encountered in xfrin protocol handling.
  82. '''
  83. pass
  84. class XfrinZoneUptodate(Exception):
  85. '''TBD
  86. '''
  87. pass
  88. class XfrinZoneInfoException(Exception):
  89. """This exception is raised if there is an error in the given
  90. configuration (part), or when a command does not have a required
  91. argument or has bad arguments, for instance when the zone's master
  92. address is not a valid IP address, when the zone does not
  93. have a name, or when multiple settings are given for the same
  94. zone."""
  95. pass
  96. def _check_zone_name(zone_name_str):
  97. """Checks if the given zone name is a valid domain name, and returns
  98. it as a Name object. Raises an XfrinException if it is not."""
  99. try:
  100. # In the _zones dict, part of the key is the zone name,
  101. # but due to a limitation in the Name class, we
  102. # cannot directly use it as a dict key, and we use to_text()
  103. #
  104. # Downcase the name here for that reason.
  105. return Name(zone_name_str, True)
  106. except (EmptyLabel, TooLongLabel, BadLabelType, BadEscape,
  107. TooLongName, IncompleteName) as ne:
  108. raise XfrinZoneInfoException("bad zone name: " + zone_name_str + " (" + str(ne) + ")")
  109. def _check_zone_class(zone_class_str):
  110. """If the given argument is a string: checks if the given class is
  111. a valid one, and returns an RRClass object if so.
  112. Raises XfrinZoneInfoException if not.
  113. If it is None, this function returns the default RRClass.IN()"""
  114. if zone_class_str is None:
  115. return DEFAULT_ZONE_CLASS
  116. try:
  117. return RRClass(zone_class_str)
  118. except InvalidRRClass as irce:
  119. raise XfrinZoneInfoException("bad zone class: " + zone_class_str + " (" + str(irce) + ")")
  120. def format_zone_str(zone_name, zone_class):
  121. """Helper function to format a zone name and class as a string of
  122. the form '<name>/<class>'.
  123. Parameters:
  124. zone_name (isc.dns.Name) name to format
  125. zone_class (isc.dns.RRClass) class to format
  126. """
  127. return zone_name.to_text(True) + '/' + str(zone_class)
  128. def format_addrinfo(addrinfo):
  129. """Helper function to format the addrinfo as a string of the form
  130. <addr>:<port> (for IPv4) or [<addr>]:port (for IPv6). For unix domain
  131. sockets, and unknown address families, it returns a basic string
  132. conversion of the third element of the passed tuple.
  133. Parameters:
  134. addrinfo: a 3-tuple consisting of address family, socket type, and,
  135. depending on the family, either a 2-tuple with the address
  136. and port, or a filename
  137. """
  138. try:
  139. if addrinfo[0] == socket.AF_INET:
  140. return str(addrinfo[2][0]) + ":" + str(addrinfo[2][1])
  141. elif addrinfo[0] == socket.AF_INET6:
  142. return "[" + str(addrinfo[2][0]) + "]:" + str(addrinfo[2][1])
  143. else:
  144. return str(addrinfo[2])
  145. except IndexError:
  146. raise TypeError("addrinfo argument to format_addrinfo() does not "
  147. "appear to be consisting of (family, socktype, (addr, port))")
  148. def get_soa_serial(soa_rdata):
  149. '''Extract the serial field of SOA RDATA and return it as a Serial object.
  150. We don't have to be very efficient here, so we first dump the entire RDATA
  151. as a string and convert the first corresponding field. This should be
  152. sufficient in practice, but may not always work when the MNAME or RNAME
  153. contains an (escaped) space character in their labels. Ideally there
  154. should be a more direct and convenient way to get access to the SOA
  155. fields.
  156. '''
  157. return Serial(int(soa_rdata.to_text().split()[2]))
  158. class XfrinState:
  159. '''
  160. The states of the incomding *XFR state machine.
  161. We (will) handle both IXFR and AXFR with a single integrated state
  162. machine because they cannot be distinguished immediately - an AXFR
  163. response to an IXFR request can only be detected when the first two (2)
  164. response RRs have already been received.
  165. The following diagram summarizes the state transition. After sending
  166. the query, xfrin starts the process with the InitialSOA state (all
  167. IXFR/AXFR response begins with an SOA). When it reaches IXFREnd
  168. or AXFREnd, the process successfully completes.
  169. (AXFR or
  170. (recv SOA) AXFR-style IXFR) (SOA, add)
  171. InitialSOA------->FirstData------------->AXFR--------->AXFREnd
  172. | | | ^ (post xfr
  173. |(IXFR && | | | checks, then
  174. | recv SOA | +--+ commit)
  175. | not new) | (non SOA, add)
  176. V |
  177. IXFRUptodate | (non SOA, delete)
  178. (pure IXFR,| +-------+
  179. keep handling)| (Delete SOA) V |
  180. + ->IXFRDeleteSOA------>IXFRDelete--+
  181. ^ |
  182. (see SOA, not end, | (see SOA)|
  183. commit, keep handling) | |
  184. | V
  185. +---------IXFRAdd<----------+IXFRAddSOA
  186. (non SOA, add)| ^ | (Add SOA)
  187. ----------+ |
  188. |(see SOA w/ end serial, commit changes)
  189. V
  190. IXFREnd
  191. Note that changes are committed for every "difference sequence"
  192. (i.e. changes for one SOA update). This means when an IXFR response
  193. contains multiple difference sequences and something goes wrong
  194. after several commits, these changes have been published and visible
  195. to clients even if the IXFR session is subsequently aborted.
  196. It is not clear if this is valid in terms of the protocol specification.
  197. Section 4 of RFC 1995 states:
  198. An IXFR client, should only replace an older version with a newer
  199. version after all the differences have been successfully processed.
  200. If this "replacement" is for the changes of one difference sequence
  201. and "all the differences" mean the changes for that sequence, this
  202. implementation strictly follows what RFC states. If this is for
  203. the entire IXFR response (that may contain multiple sequences),
  204. we should implement it with one big transaction and one final commit
  205. at the very end.
  206. For now, we implement it with multiple smaller commits for two
  207. reasons. First, this is what BIND 9 does, and we generally port
  208. the implementation logic here. BIND 9 has been supporting IXFR
  209. for many years, so the fact that it still behaves this way
  210. probably means it at least doesn't cause a severe operational
  211. problem in practice. Second, especially because BIND 10 would
  212. often uses a database backend, a larger transaction could cause an
  213. undesirable effects, e.g. suspending normal lookups for a longer
  214. period depending on the characteristics of the database. Even if
  215. we find something wrong in a later sequeunce and abort the
  216. session, we can start another incremental update from what has
  217. been validated, or we can switch to AXFR to replace the zone
  218. completely.
  219. This implementation uses the state design pattern, where each state
  220. is represented as a subclass of the base XfrinState class. Each concrete
  221. subclass of XfrinState is assumed to define two methods: handle_rr() and
  222. finish_message(). These methods handle specific part of XFR protocols
  223. and (if necessary) perform the state transition.
  224. Conceptually, XfrinState and its subclasses are a "friend" of
  225. XfrinConnection and are assumed to be allowed to access its internal
  226. information (even though Python does not have a strict access control
  227. between different classes).
  228. The XfrinState and its subclasses are designed to be stateless, and
  229. can be used as singleton objects. For now, however, we always instantiate
  230. a new object for every state transition, partly because the introduction
  231. of singleton will make a code bit complicated, and partly because
  232. the overhead of object instantiotion wouldn't be significant for xfrin.
  233. '''
  234. def set_xfrstate(self, conn, new_state):
  235. '''Set the XfrConnection to a given new state.
  236. As a "friend" class, this method intentionally gets access to the
  237. connection's "private" method.
  238. '''
  239. conn._XfrinConnection__set_xfrstate(new_state)
  240. def handle_rr(self, conn):
  241. '''Handle one RR of an XFR response message.
  242. Depending on the state, the RR is generally added or deleted in the
  243. corresponding data source, or in some special cases indicates
  244. a specifi transition, such as starting a new IXFR difference
  245. sequence or completing the session.
  246. All subclass has their specific behaviors for this method, so
  247. there is no default definition. If the base class version
  248. is called, it's a bug of the caller, and it's notified via
  249. an XfrinException exception.
  250. This method returns a boolean value: True if the given RR was
  251. fully handled and the caller should go to the next RR; False
  252. if the caller needs to call this method with the (possibly) new
  253. state for the same RR again.
  254. '''
  255. raise XfrinException("Internal bug: " +
  256. "XfrinState.handle_rr() called directly")
  257. def finish_message(self, conn):
  258. '''Perform any final processing after handling all RRs of a response.
  259. This method then returns a boolean indicating whether to continue
  260. receiving the message. Unless it's in the end of the entire XFR
  261. session, we should continue, so this default method simply returns
  262. True.
  263. '''
  264. return True
  265. class XfrinInitialSOA(XfrinState):
  266. def handle_rr(self, conn, rr):
  267. if rr.get_type() != RRType.SOA():
  268. raise XfrinProtocolError('First RR in zone transfer must be SOA ('
  269. + rr.get_type().to_text() + ' received)')
  270. conn._end_serial = get_soa_serial(rr.get_rdata()[0])
  271. if conn._request_type == RRType.IXFR() and \
  272. conn._end_serial <= conn._request_serial:
  273. logger.info(XFRIN_IXFR_UPTODATE, conn.zone_str(),
  274. conn._request_serial, conn._end_serial)
  275. self.set_xfrstate(conn, XfrinIXFRUptodate())
  276. else:
  277. self.set_xfrstate(conn, XfrinFirstData())
  278. return True
  279. class XfrinFirstData(XfrinState):
  280. def handle_rr(self, conn, rr):
  281. '''Handle the first RR after initial SOA in an XFR session.
  282. This state happens exactly once in an XFR session, where
  283. we decide whether it's incremental update ("real" IXFR) or
  284. non incremental update (AXFR or AXFR-style IXFR).
  285. If we initiated IXFR and the transfer begins with two SOAs
  286. (the serial of the second one being equal to our serial),
  287. it's incremental; otherwise it's non incremental.
  288. This method always return False (unlike many other handle_rr()
  289. methods) because this first RR must be examined again in the
  290. determined update context.
  291. Note that in the non incremental case the RR should normally be
  292. something other SOA, but it's still possible it's an SOA with a
  293. different serial than ours. The only possible interpretation at
  294. this point is that it's non incremental update that only consists
  295. of the SOA RR. It will result in broken zone (for example, it
  296. wouldn't even contain an apex NS) and should be rejected at post
  297. XFR processing, but in terms of the XFR session processing we
  298. accept it and move forward.
  299. Note further that, in the half-broken SOA-only transfer case,
  300. these two SOAs are supposed to be the same as stated in Section 2.2
  301. of RFC 5936. We don't check that condition here, either; we'll
  302. leave whether and how to deal with that situation to the end of
  303. the processing of non incremental update. See also a related
  304. discussion at the IETF dnsext wg:
  305. http://www.ietf.org/mail-archive/web/dnsext/current/msg07908.html
  306. '''
  307. if conn._request_type == RRType.IXFR() and \
  308. rr.get_type() == RRType.SOA() and \
  309. conn._request_serial == get_soa_serial(rr.get_rdata()[0]):
  310. logger.debug(DBG_XFRIN_TRACE, XFRIN_GOT_INCREMENTAL_RESP,
  311. conn.zone_str())
  312. self.set_xfrstate(conn, XfrinIXFRDeleteSOA())
  313. else:
  314. logger.debug(DBG_XFRIN_TRACE, XFRIN_GOT_NONINCREMENTAL_RESP,
  315. conn.zone_str())
  316. # We are now going to add RRs to the new zone. We need create
  317. # a Diff object. It will be used throughtout the XFR session.
  318. conn._diff = Diff(conn._datasrc_client, conn._zone_name, True)
  319. self.set_xfrstate(conn, XfrinAXFR())
  320. return False
  321. class XfrinIXFRDeleteSOA(XfrinState):
  322. def handle_rr(self, conn, rr):
  323. if rr.get_type() != RRType.SOA():
  324. # this shouldn't happen; should this occur it means an internal
  325. # bug.
  326. raise XfrinException(rr.get_type().to_text() +
  327. ' RR is given in IXFRDeleteSOA state')
  328. # This is the beginning state of one difference sequence (changes
  329. # for one SOA update). We need to create a new Diff object now.
  330. # Note also that we (unconditionally) enable journaling here. The
  331. # Diff constructor may internally disable it, however, if the
  332. # underlying data source doesn't support journaling.
  333. conn._diff = Diff(conn._datasrc_client, conn._zone_name, False, True)
  334. conn._diff.delete_data(rr)
  335. self.set_xfrstate(conn, XfrinIXFRDelete())
  336. conn.get_transfer_stats().ixfr_deletion_count += 1
  337. return True
  338. class XfrinIXFRDelete(XfrinState):
  339. def handle_rr(self, conn, rr):
  340. if rr.get_type() == RRType.SOA():
  341. # This is the only place where current_serial is set
  342. conn._current_serial = get_soa_serial(rr.get_rdata()[0])
  343. self.set_xfrstate(conn, XfrinIXFRAddSOA())
  344. return False
  345. conn._diff.delete_data(rr)
  346. conn.get_transfer_stats().ixfr_deletion_count += 1
  347. return True
  348. class XfrinIXFRAddSOA(XfrinState):
  349. def handle_rr(self, conn, rr):
  350. if rr.get_type() != RRType.SOA():
  351. # this shouldn't happen; should this occur it means an internal
  352. # bug.
  353. raise XfrinException(rr.get_type().to_text() +
  354. ' RR is given in IXFRAddSOA state')
  355. conn._diff.add_data(rr)
  356. self.set_xfrstate(conn, XfrinIXFRAdd())
  357. conn.get_transfer_stats().ixfr_addition_count += 1
  358. return True
  359. class XfrinIXFRAdd(XfrinState):
  360. def handle_rr(self, conn, rr):
  361. if rr.get_type() == RRType.SOA():
  362. # This SOA marks the end of a difference sequence
  363. conn.get_transfer_stats().ixfr_changeset_count += 1
  364. soa_serial = get_soa_serial(rr.get_rdata()[0])
  365. if soa_serial == conn._end_serial:
  366. conn._diff.commit()
  367. self.set_xfrstate(conn, XfrinIXFREnd())
  368. return True
  369. elif soa_serial != conn._current_serial:
  370. raise XfrinProtocolError('IXFR out of sync: expected ' +
  371. 'serial ' +
  372. str(conn._current_serial) +
  373. ', got ' + str(soa_serial))
  374. else:
  375. conn._diff.commit()
  376. self.set_xfrstate(conn, XfrinIXFRDeleteSOA())
  377. return False
  378. conn._diff.add_data(rr)
  379. conn.get_transfer_stats().ixfr_addition_count += 1
  380. return True
  381. class XfrinIXFREnd(XfrinState):
  382. def handle_rr(self, conn, rr):
  383. raise XfrinProtocolError('Extra data after the end of IXFR diffs: ' +
  384. rr.to_text())
  385. def finish_message(self, conn):
  386. '''Final processing after processing an entire IXFR session.
  387. There will be more actions here, but for now we simply return False,
  388. indicating there will be no more message to receive.
  389. '''
  390. return False
  391. class XfrinIXFRUptodate(XfrinState):
  392. def handle_rr(self, conn, rr):
  393. raise XfrinProtocolError('Extra data after single IXFR response ' +
  394. rr.to_text())
  395. def finish_message(self, conn):
  396. raise XfrinZoneUptodate
  397. class XfrinAXFR(XfrinState):
  398. def handle_rr(self, conn, rr):
  399. """
  400. Handle the RR by putting it into the zone.
  401. """
  402. conn._diff.add_data(rr)
  403. if rr.get_type() == RRType.SOA():
  404. # SOA means end. Don't commit it yet - we need to perform
  405. # post-transfer checks
  406. soa_serial = get_soa_serial(rr.get_rdata()[0])
  407. if conn._end_serial != soa_serial:
  408. logger.warn(XFRIN_AXFR_INCONSISTENT_SOA, conn.zone_str(),
  409. conn._end_serial, soa_serial)
  410. self.set_xfrstate(conn, XfrinAXFREnd())
  411. conn.get_transfer_stats().axfr_rr_count += 1
  412. # Yes, we've eaten this RR.
  413. return True
  414. class XfrinAXFREnd(XfrinState):
  415. def handle_rr(self, conn, rr):
  416. raise XfrinProtocolError('Extra data after the end of AXFR: ' +
  417. rr.to_text())
  418. def finish_message(self, conn):
  419. """
  420. Final processing after processing an entire AXFR session.
  421. In this process all the AXFR changes are committed to the
  422. data source.
  423. There might be more actions here, but for now we simply return False,
  424. indicating there will be no more message to receive.
  425. """
  426. conn._diff.commit()
  427. return False
  428. class XfrinTransferStats:
  429. """
  430. This class keeps a record of transfer data for logging purposes.
  431. It records number of messages, rrs, and bytes transfered, as well
  432. as the start and end time. The start time is set upon instantiation of
  433. this class. The end time is set the first time finalize(),
  434. get_running_time(), or get_bytes_per_second() is called. The end time is
  435. set only once; subsequent calls to any of these methods does not modify
  436. it further.
  437. All _count instance variables can be directly set as needed by the
  438. class collecting these results.
  439. """
  440. def __init__(self):
  441. self.message_count = 0
  442. self.axfr_rr_count = 0
  443. self.byte_count = 0
  444. self.ixfr_changeset_count = 0;
  445. self.ixfr_deletion_count = 0;
  446. self.ixfr_addition_count = 0;
  447. self._start_time = time.time()
  448. self._end_time = None
  449. def finalize(self):
  450. """Sets the end time to time.time() if not done already."""
  451. if self._end_time is None:
  452. self._end_time = time.time()
  453. def get_running_time(self):
  454. """Calls finalize(), then returns the difference between creation
  455. and finalization time"""
  456. self.finalize()
  457. return self._end_time - self._start_time
  458. def get_bytes_per_second(self):
  459. """Returns the number of bytes per second, based on the result of
  460. get_running_time() and the value of bytes_count."""
  461. runtime = self.get_running_time()
  462. if runtime > 0.0:
  463. return float(self.byte_count) / runtime
  464. else:
  465. # This should never happen, but if some clock is so
  466. # off or reset in the meantime, we do need to return
  467. # *something* (and not raise an error)
  468. if self.byte_count == 0:
  469. return 0.0
  470. else:
  471. return float("inf")
  472. class XfrinConnection(asyncore.dispatcher):
  473. '''Do xfrin in this class. '''
  474. def __init__(self,
  475. sock_map, zone_name, rrclass, datasrc_client,
  476. shutdown_event, master_addrinfo, db_file, tsig_key=None,
  477. idle_timeout=60):
  478. '''Constructor of the XfirnConnection class.
  479. db_file: SQLite3 DB file. Unforutnately we still need this for
  480. temporary workaround in _get_zone_soa(). This should be
  481. removed when we eliminate the need for the workaround.
  482. idle_timeout: max idle time for read data from socket.
  483. datasrc_client: the data source client object used for the XFR session.
  484. This will eventually replace db_file completely.
  485. '''
  486. asyncore.dispatcher.__init__(self, map=sock_map)
  487. # The XFR state. Conceptually this is purely private, so we emphasize
  488. # the fact by the double underscore. Other classes are assumed to
  489. # get access to this via get_xfrstate(), and only XfrinState classes
  490. # are assumed to be allowed to modify it via __set_xfrstate().
  491. self.__state = None
  492. # Requested transfer type (RRType.AXFR or RRType.IXFR). The actual
  493. # transfer type may differ due to IXFR->AXFR fallback:
  494. self._request_type = None
  495. # Zone parameters
  496. self._zone_name = zone_name
  497. self._rrclass = rrclass
  498. # Data source handler
  499. self._db_file = db_file
  500. self._datasrc_client = datasrc_client
  501. self._zone_soa = self._get_zone_soa()
  502. self._sock_map = sock_map
  503. self._soa_rr_count = 0
  504. self._idle_timeout = idle_timeout
  505. self._shutdown_event = shutdown_event
  506. self._master_addrinfo = master_addrinfo
  507. self._tsig_key = tsig_key
  508. self._tsig_ctx = None
  509. # tsig_ctx_creator is introduced to allow tests to use a mock class for
  510. # easier tests (in normal case we always use the default)
  511. self._tsig_ctx_creator = lambda key : TSIGContext(key)
  512. # keep a record of this specific transfer to log on success
  513. # (time, rr/s, etc)
  514. self._transfer_stats = XfrinTransferStats()
  515. def init_socket(self):
  516. '''Initialize the underlyig socket.
  517. This is essentially a part of __init__() and is expected to be
  518. called immediately after the constructor. It's separated from
  519. the constructor because otherwise we might not be able to close
  520. it if the constructor raises an exception after opening the socket.
  521. '''
  522. self.create_socket(self._master_addrinfo[0], self._master_addrinfo[1])
  523. self.setblocking(1)
  524. def _get_zone_soa(self):
  525. '''Retrieve the current SOA RR of the zone to be transferred.
  526. It will be used for various purposes in subsequent xfr protocol
  527. processing. It is validly possible that the zone is currently
  528. empty and therefore doesn't have an SOA, so this method doesn't
  529. consider it an error and returns None in such a case. It may or
  530. may not result in failure in the actual processing depending on
  531. how the SOA is used.
  532. When the zone has an SOA RR, this method makes sure that it's
  533. valid, i.e., it has exactly one RDATA; if it is not the case
  534. this method returns None.
  535. If the underlying data source doesn't even know the zone, this method
  536. tries to provide backward compatible behavior where xfrin is
  537. responsible for creating zone in the corresponding DB table.
  538. For a longer term we should deprecate this behavior by introducing
  539. more generic zone management framework, but at the moment we try
  540. to not surprise existing users. (Note also that the part of
  541. providing the compatible behavior uses the old data source API.
  542. We'll deprecate this API in a near future, too).
  543. '''
  544. # get the zone finder. this must be SUCCESS (not even
  545. # PARTIALMATCH) because we are specifying the zone origin name.
  546. result, finder = self._datasrc_client.find_zone(self._zone_name)
  547. if result != DataSourceClient.SUCCESS:
  548. # The data source doesn't know the zone. For now, we provide
  549. # backward compatibility and creates a new one ourselves.
  550. isc.datasrc.sqlite3_ds.load(self._db_file,
  551. self._zone_name.to_text(),
  552. lambda : [])
  553. logger.warn(XFRIN_ZONE_CREATED, self.zone_str())
  554. # try again
  555. result, finder = self._datasrc_client.find_zone(self._zone_name)
  556. if result != DataSourceClient.SUCCESS:
  557. return None
  558. result, soa_rrset, _ = finder.find(self._zone_name, RRType.SOA())
  559. if result != ZoneFinder.SUCCESS:
  560. logger.info(XFRIN_ZONE_NO_SOA, self.zone_str())
  561. return None
  562. if soa_rrset.get_rdata_count() != 1:
  563. logger.warn(XFRIN_ZONE_MULTIPLE_SOA, self.zone_str(),
  564. soa_rrset.get_rdata_count())
  565. return None
  566. return soa_rrset
  567. def __set_xfrstate(self, new_state):
  568. self.__state = new_state
  569. def get_xfrstate(self):
  570. return self.__state
  571. def get_transfer_stats(self):
  572. """Returns the transfer stats object, used to measure transfer time,
  573. and number of messages/records/bytes transfered."""
  574. return self._transfer_stats
  575. def zone_str(self):
  576. '''A convenience function for logging to include zone name and class'''
  577. return format_zone_str(self._zone_name, self._rrclass)
  578. def connect_to_master(self):
  579. '''Connect to master in TCP.'''
  580. try:
  581. self.connect(self._master_addrinfo[2])
  582. return True
  583. except socket.error as e:
  584. logger.error(XFRIN_CONNECT_MASTER, self._master_addrinfo[2],
  585. str(e))
  586. return False
  587. def _create_query(self, query_type):
  588. '''Create an XFR-related query message.
  589. query_type is either SOA, AXFR or IXFR. An IXFR query needs the
  590. zone's current SOA record. If it's not known, it raises an
  591. XfrinException exception. Note that this may not necessarily a
  592. broken configuration; for the first attempt of transfer the secondary
  593. may not have any boot-strap zone information, in which case IXFR
  594. simply won't work. The xfrin should then fall back to AXFR.
  595. _request_serial is recorded for later use.
  596. '''
  597. msg = Message(Message.RENDER)
  598. query_id = random.randint(0, 0xFFFF)
  599. self._query_id = query_id
  600. msg.set_qid(query_id)
  601. msg.set_opcode(Opcode.QUERY())
  602. msg.set_rcode(Rcode.NOERROR())
  603. msg.add_question(Question(self._zone_name, self._rrclass, query_type))
  604. # Remember our serial, if known
  605. self._request_serial = get_soa_serial(self._zone_soa.get_rdata()[0]) \
  606. if self._zone_soa is not None else None
  607. # Set the authority section with our SOA for IXFR
  608. if query_type == RRType.IXFR():
  609. if self._zone_soa is None:
  610. # (incremental) IXFR doesn't work without known SOA
  611. raise XfrinException('Failed to create IXFR query due to no ' +
  612. 'SOA for ' + self.zone_str())
  613. msg.add_rrset(Message.SECTION_AUTHORITY, self._zone_soa)
  614. return msg
  615. def _send_data(self, data):
  616. size = len(data)
  617. total_count = 0
  618. while total_count < size:
  619. count = self.send(data[total_count:])
  620. total_count += count
  621. def _send_query(self, query_type):
  622. '''Send query message over TCP. '''
  623. msg = self._create_query(query_type)
  624. render = MessageRenderer()
  625. # XXX Currently, python wrapper doesn't accept 'None' parameter in this case,
  626. # we should remove the if statement and use a universal interface later.
  627. if self._tsig_key is not None:
  628. self._tsig_ctx = self._tsig_ctx_creator(self._tsig_key)
  629. msg.to_wire(render, self._tsig_ctx)
  630. else:
  631. msg.to_wire(render)
  632. header_len = struct.pack('H', socket.htons(render.get_length()))
  633. self._send_data(header_len)
  634. self._send_data(render.get_data())
  635. def _asyncore_loop(self):
  636. '''
  637. This method is a trivial wrapper for asyncore.loop(). It's extracted from
  638. _get_request_response so that we can test the rest of the code without
  639. involving actual communication with a remote server.'''
  640. asyncore.loop(self._idle_timeout, map=self._sock_map, count=1)
  641. def _get_request_response(self, size):
  642. recv_size = 0
  643. data = b''
  644. while recv_size < size:
  645. self._recv_time_out = True
  646. self._need_recv_size = size - recv_size
  647. self._asyncore_loop()
  648. if self._recv_time_out:
  649. raise XfrinException('receive data from socket time out.')
  650. recv_size += self._recvd_size
  651. data += self._recvd_data
  652. return data
  653. def _check_response_tsig(self, msg, response_data):
  654. tsig_record = msg.get_tsig_record()
  655. if self._tsig_ctx is not None:
  656. tsig_error = self._tsig_ctx.verify(tsig_record, response_data)
  657. if tsig_error != TSIGError.NOERROR:
  658. raise XfrinProtocolError('TSIG verify fail: %s' %
  659. str(tsig_error))
  660. elif tsig_record is not None:
  661. # If the response includes a TSIG while we didn't sign the query,
  662. # we treat it as an error. RFC doesn't say anything about this
  663. # case, but it clearly states the server must not sign a response
  664. # to an unsigned request. Although we could be flexible, no sane
  665. # implementation would return such a response, and since this is
  666. # part of security mechanism, it's probably better to be more
  667. # strict.
  668. raise XfrinProtocolError('Unexpected TSIG in response')
  669. def __parse_soa_response(self, msg, response_data):
  670. '''Parse a response to SOA query and extract the SOA from answer.
  671. This is a subroutine of _check_soa_serial(). This method also
  672. validates message, and rejects bogus responses with XfrinProtocolError.
  673. If everything is okay, it returns the SOA RR from the answer section
  674. of the response.
  675. '''
  676. # Check TSIG integrity and validate the header. Unlike AXFR/IXFR,
  677. # we should be more strict for SOA queries and check the AA flag, too.
  678. self._check_response_tsig(msg, response_data)
  679. self._check_response_header(msg)
  680. if not msg.get_header_flag(Message.HEADERFLAG_AA):
  681. raise XfrinProtocolError('non-authoritative answer to SOA query')
  682. # Validate the question section
  683. n_question = msg.get_rr_count(Message.SECTION_QUESTION)
  684. if n_question != 1:
  685. raise XfrinProtocolError('Invalid response to SOA query: ' +
  686. '(' + str(n_question) + ' questions, 1 ' +
  687. 'expected)')
  688. resp_question = msg.get_question()[0]
  689. if resp_question.get_name() != self._zone_name or \
  690. resp_question.get_class() != self._rrclass or \
  691. resp_question.get_type() != RRType.SOA():
  692. raise XfrinProtocolError('Invalid response to SOA query: '
  693. 'question mismatch: ' +
  694. str(resp_question))
  695. # Look into the answer section for SOA
  696. soa = None
  697. for rr in msg.get_section(Message.SECTION_ANSWER):
  698. if rr.get_type() == RRType.SOA():
  699. if soa is not None:
  700. raise XfrinProtocolError('SOA response had multiple SOAs')
  701. soa = rr
  702. # There should not be a CNAME record at top of zone.
  703. if rr.get_type() == RRType.CNAME():
  704. raise XfrinProtocolError('SOA query resulted in CNAME')
  705. # If SOA is not found, try to figure out the reason then report it.
  706. if soa is None:
  707. # See if we have any SOA records in the authority section.
  708. for rr in msg.get_section(Message.SECTION_AUTHORITY):
  709. if rr.get_type() == RRType.NS():
  710. raise XfrinProtocolError('SOA query resulted in referral')
  711. if rr.get_type() == RRType.SOA():
  712. raise XfrinProtocolError('SOA query resulted in NODATA')
  713. raise XfrinProtocolError('No SOA record found in response to ' +
  714. 'SOA query')
  715. # Check if the SOA is really what we asked for
  716. if soa.get_name() != self._zone_name or \
  717. soa.get_class() != self._rrclass:
  718. raise XfrinProtocolError("SOA response doesn't match query: " +
  719. str(soa))
  720. # All okay, return it
  721. return soa
  722. def _check_soa_serial(self):
  723. '''Send SOA query and compare the local and remote serials.
  724. If we know our local serial and the remote serial isn't newer
  725. than ours, we abort the session with XfrinZoneUptodate.
  726. On success it returns XFRIN_OK for testing. The caller won't use it.
  727. '''
  728. self._send_query(RRType.SOA())
  729. data_len = self._get_request_response(2)
  730. msg_len = socket.htons(struct.unpack('H', data_len)[0])
  731. soa_response = self._get_request_response(msg_len)
  732. msg = Message(Message.PARSE)
  733. msg.from_wire(soa_response, Message.PRESERVE_ORDER)
  734. # Validate/parse the rest of the response, and extract the SOA
  735. # from the answer section
  736. soa = self.__parse_soa_response(msg, soa_response)
  737. # Compare the two serials. If ours is 'new', abort with ZoneUptodate.
  738. primary_serial = get_soa_serial(soa.get_rdata()[0])
  739. if self._request_serial is not None and \
  740. self._request_serial >= primary_serial:
  741. if self._request_serial != primary_serial:
  742. logger.info(XFRIN_ZONE_SERIAL_AHEAD, primary_serial,
  743. self.zone_str(),
  744. format_addrinfo(self._master_addrinfo),
  745. self._request_serial)
  746. raise XfrinZoneUptodate
  747. return XFRIN_OK
  748. def do_xfrin(self, check_soa, request_type=RRType.AXFR()):
  749. '''Do an xfr session by sending xfr request and parsing responses.'''
  750. try:
  751. ret = XFRIN_OK
  752. self._request_type = request_type
  753. # Right now RRType.[IA]XFR().to_text() is 'TYPExxx', so we need
  754. # to hardcode here.
  755. req_str = 'IXFR' if request_type == RRType.IXFR() else 'AXFR'
  756. if check_soa:
  757. self._check_soa_serial()
  758. logger.info(XFRIN_XFR_TRANSFER_STARTED, req_str, self.zone_str())
  759. self._send_query(self._request_type)
  760. self.__state = XfrinInitialSOA()
  761. self._handle_xfrin_responses()
  762. # Depending what data was found, we log different status reports
  763. # (In case of an AXFR-style IXFR, print the 'AXFR' message)
  764. if self._transfer_stats.axfr_rr_count == 0:
  765. logger.info(XFRIN_IXFR_TRANSFER_SUCCESS,
  766. self.zone_str(),
  767. self._transfer_stats.message_count,
  768. self._transfer_stats.ixfr_changeset_count,
  769. self._transfer_stats.ixfr_deletion_count,
  770. self._transfer_stats.ixfr_addition_count,
  771. self._transfer_stats.byte_count,
  772. "%.3f" % self._transfer_stats.get_running_time(),
  773. "%.f" % self._transfer_stats.get_bytes_per_second()
  774. )
  775. else:
  776. logger.info(XFRIN_TRANSFER_SUCCESS,
  777. req_str,
  778. self.zone_str(),
  779. self._transfer_stats.message_count,
  780. self._transfer_stats.axfr_rr_count,
  781. self._transfer_stats.byte_count,
  782. "%.3f" % self._transfer_stats.get_running_time(),
  783. "%.f" % self._transfer_stats.get_bytes_per_second()
  784. )
  785. except XfrinZoneUptodate:
  786. # Eventually we'll probably have to treat this case as a trigger
  787. # of trying another primary server, etc, but for now we treat it
  788. # as "success".
  789. pass
  790. except XfrinProtocolError as e:
  791. logger.info(XFRIN_XFR_TRANSFER_PROTOCOL_ERROR, req_str,
  792. self.zone_str(),
  793. format_addrinfo(self._master_addrinfo), str(e))
  794. ret = XFRIN_FAIL
  795. except XfrinException as e:
  796. logger.error(XFRIN_XFR_TRANSFER_FAILURE, req_str,
  797. self.zone_str(),
  798. format_addrinfo(self._master_addrinfo), str(e))
  799. ret = XFRIN_FAIL
  800. except Exception as e:
  801. # Catching all possible exceptions like this is generally not a
  802. # good practice, but handling an xfr session could result in
  803. # so many types of exceptions, including ones from the DNS library
  804. # or from the data source library. Eventually we'd introduce a
  805. # hierarchy for exception classes from a base "ISC exception" and
  806. # catch it here, but until then we need broadest coverage so that
  807. # we won't miss anything.
  808. logger.error(XFRIN_XFR_OTHER_FAILURE, req_str,
  809. self.zone_str(), str(e))
  810. ret = XFRIN_FAIL
  811. finally:
  812. # Make sure any remaining transaction in the diff is closed
  813. # (if not yet - possible in case of xfr-level exception) as soon
  814. # as possible
  815. self._diff = None
  816. return ret
  817. def _check_response_header(self, msg):
  818. '''Perform minimal validation on responses'''
  819. # It's not clear how strict we should be about response validation.
  820. # BIND 9 ignores some cases where it would normally be considered a
  821. # bogus response. For example, it accepts a response even if its
  822. # opcode doesn't match that of the corresponding request.
  823. # According to an original developer of BIND 9 some of the missing
  824. # checks are deliberate to be kind to old implementations that would
  825. # cause interoperability trouble with stricter checks.
  826. msg_rcode = msg.get_rcode()
  827. if msg_rcode != Rcode.NOERROR():
  828. raise XfrinProtocolError('error response: %s' %
  829. msg_rcode.to_text())
  830. if not msg.get_header_flag(Message.HEADERFLAG_QR):
  831. raise XfrinProtocolError('response is not a response')
  832. if msg.get_qid() != self._query_id:
  833. raise XfrinProtocolError('bad query id')
  834. def _check_response_status(self, msg):
  835. '''Check validation of xfr response. '''
  836. self._check_response_header(msg)
  837. if msg.get_rr_count(Message.SECTION_QUESTION) > 1:
  838. raise XfrinProtocolError('query section count greater than 1')
  839. def _handle_xfrin_responses(self):
  840. read_next_msg = True
  841. while read_next_msg:
  842. data_len = self._get_request_response(2)
  843. msg_len = socket.htons(struct.unpack('H', data_len)[0])
  844. self._transfer_stats.byte_count += msg_len + 2
  845. recvdata = self._get_request_response(msg_len)
  846. msg = Message(Message.PARSE)
  847. msg.from_wire(recvdata, Message.PRESERVE_ORDER)
  848. self._transfer_stats.message_count += 1
  849. # TSIG related checks, including an unexpected signed response
  850. self._check_response_tsig(msg, recvdata)
  851. # Perform response status validation
  852. self._check_response_status(msg)
  853. for rr in msg.get_section(Message.SECTION_ANSWER):
  854. rr_handled = False
  855. while not rr_handled:
  856. rr_handled = self.__state.handle_rr(self, rr)
  857. read_next_msg = self.__state.finish_message(self)
  858. if self._shutdown_event.is_set():
  859. raise XfrinException('xfrin is forced to stop')
  860. def handle_read(self):
  861. '''Read query's response from socket. '''
  862. self._recvd_data = self.recv(self._need_recv_size)
  863. self._recvd_size = len(self._recvd_data)
  864. self._recv_time_out = False
  865. def writable(self):
  866. '''Ignore the writable socket. '''
  867. return False
  868. def __process_xfrin(server, zone_name, rrclass, db_file,
  869. shutdown_event, master_addrinfo, check_soa, tsig_key,
  870. request_type, conn_class):
  871. conn = None
  872. exception = None
  873. ret = XFRIN_FAIL
  874. try:
  875. # Create a data source client used in this XFR session. Right now we
  876. # still assume an sqlite3-based data source, and use both the old and new
  877. # data source APIs. We also need to use a mock client for tests.
  878. # For a temporary workaround to deal with these situations, we skip the
  879. # creation when the given file is none (the test case). Eventually
  880. # this code will be much cleaner.
  881. datasrc_client = None
  882. if db_file is not None:
  883. # temporary hardcoded sqlite initialization. Once we decide on
  884. # the config specification, we need to update this (TODO)
  885. # this may depend on #1207, or any followup ticket created for #1207
  886. datasrc_type = "sqlite3"
  887. datasrc_config = "{ \"database_file\": \"" + db_file + "\"}"
  888. datasrc_client = DataSourceClient(datasrc_type, datasrc_config)
  889. # Create a TCP connection for the XFR session and perform the operation.
  890. sock_map = {}
  891. # In case we were asked to do IXFR and that one fails, we try again with
  892. # AXFR. But only if we could actually connect to the server.
  893. #
  894. # So we start with retry as True, which is set to false on each attempt.
  895. # In the case of connected but failed IXFR, we set it to true once again.
  896. retry = True
  897. while retry:
  898. retry = False
  899. conn = conn_class(sock_map, zone_name, rrclass, datasrc_client,
  900. shutdown_event, master_addrinfo, db_file,
  901. tsig_key)
  902. conn.init_socket()
  903. ret = XFRIN_FAIL
  904. if conn.connect_to_master():
  905. ret = conn.do_xfrin(check_soa, request_type)
  906. if ret == XFRIN_FAIL and request_type == RRType.IXFR():
  907. # IXFR failed for some reason. It might mean the server can't
  908. # handle it, or we don't have the zone or we are out of sync or
  909. # whatever else. So we retry with with AXFR, as it may succeed
  910. # in many such cases.
  911. retry = True
  912. request_type = RRType.AXFR()
  913. logger.warn(XFRIN_XFR_TRANSFER_FALLBACK, conn.zone_str())
  914. conn.close()
  915. conn = None
  916. except Exception as ex:
  917. # If exception happens, just remember it here so that we can re-raise
  918. # after cleaning up things. We don't log it here because we want
  919. # eliminate smallest possibility of having an exception in logging
  920. # itself.
  921. exception = ex
  922. # asyncore.dispatcher requires explicit close() unless its lifetime
  923. # from born to destruction is closed within asyncore.loop, which is not
  924. # the case for us. We always close() here, whether or not do_xfrin
  925. # succeeds, and even when we see an unexpected exception.
  926. if conn is not None:
  927. conn.close()
  928. # Publish the zone transfer result news, so zonemgr can reset the
  929. # zone timer, and xfrout can notify the zone's slaves if the result
  930. # is success.
  931. server.publish_xfrin_news(zone_name, rrclass, ret)
  932. if exception is not None:
  933. raise exception
  934. def process_xfrin(server, xfrin_recorder, zone_name, rrclass, db_file,
  935. shutdown_event, master_addrinfo, check_soa, tsig_key,
  936. request_type, conn_class=XfrinConnection):
  937. # Even if it should be rare, the main process of xfrin session can
  938. # raise an exception. In order to make sure the lock in xfrin_recorder
  939. # is released in any cases, we delegate the main part to the helper
  940. # function in the try block, catch any exceptions, then release the lock.
  941. xfrin_recorder.increment(zone_name)
  942. exception = None
  943. try:
  944. __process_xfrin(server, zone_name, rrclass, db_file,
  945. shutdown_event, master_addrinfo, check_soa, tsig_key,
  946. request_type, conn_class)
  947. except Exception as ex:
  948. # don't log it until we complete decrement().
  949. exception = ex
  950. xfrin_recorder.decrement(zone_name)
  951. if exception is not None:
  952. typestr = "AXFR" if request_type == RRType.AXFR() else "IXFR"
  953. logger.error(XFRIN_XFR_PROCESS_FAILURE, typestr, zone_name.to_text(),
  954. str(rrclass), str(exception))
  955. class XfrinRecorder:
  956. def __init__(self):
  957. self._lock = threading.Lock()
  958. self._zones = []
  959. def increment(self, zone_name):
  960. self._lock.acquire()
  961. self._zones.append(zone_name)
  962. self._lock.release()
  963. def decrement(self, zone_name):
  964. self._lock.acquire()
  965. if zone_name in self._zones:
  966. self._zones.remove(zone_name)
  967. self._lock.release()
  968. def xfrin_in_progress(self, zone_name):
  969. self._lock.acquire()
  970. ret = zone_name in self._zones
  971. self._lock.release()
  972. return ret
  973. def count(self):
  974. self._lock.acquire()
  975. ret = len(self._zones)
  976. self._lock.release()
  977. return ret
  978. class ZoneInfo:
  979. def __init__(self, config_data, module_cc):
  980. """Creates a zone_info with the config data element as
  981. specified by the 'zones' list in xfrin.spec. Module_cc is
  982. needed to get the defaults from the specification"""
  983. self._module_cc = module_cc
  984. self.set_name(config_data.get('name'))
  985. self.set_master_addr(config_data.get('master_addr'))
  986. self.set_master_port(config_data.get('master_port'))
  987. self.set_zone_class(config_data.get('class'))
  988. self.set_tsig_key(config_data.get('tsig_key'))
  989. self.set_use_ixfr(config_data.get('use_ixfr'))
  990. def set_name(self, name_str):
  991. """Set the name for this zone given a name string.
  992. Raises XfrinZoneInfoException if name_str is None or if it
  993. cannot be parsed."""
  994. if name_str is None:
  995. raise XfrinZoneInfoException("Configuration zones list "
  996. "element does not contain "
  997. "'name' attribute")
  998. else:
  999. self.name = _check_zone_name(name_str)
  1000. def set_master_addr(self, master_addr_str):
  1001. """Set the master address for this zone given an IP address
  1002. string. Raises XfrinZoneInfoException if master_addr_str is
  1003. None or if it cannot be parsed."""
  1004. if master_addr_str is None:
  1005. raise XfrinZoneInfoException("master address missing from config data")
  1006. else:
  1007. try:
  1008. self.master_addr = isc.net.parse.addr_parse(master_addr_str)
  1009. except ValueError:
  1010. logger.error(XFRIN_BAD_MASTER_ADDR_FORMAT, master_addr_str)
  1011. errmsg = "bad format for zone's master: " + master_addr_str
  1012. raise XfrinZoneInfoException(errmsg)
  1013. def set_master_port(self, master_port_str):
  1014. """Set the master port given a port number string. If
  1015. master_port_str is None, the default from the specification
  1016. for this module will be used. Raises XfrinZoneInfoException if
  1017. the string contains an invalid port number"""
  1018. if master_port_str is None:
  1019. self.master_port = self._module_cc.get_default_value("zones/master_port")
  1020. else:
  1021. try:
  1022. self.master_port = isc.net.parse.port_parse(master_port_str)
  1023. except ValueError:
  1024. logger.error(XFRIN_BAD_MASTER_PORT_FORMAT, master_port_str)
  1025. errmsg = "bad format for zone's master port: " + master_port_str
  1026. raise XfrinZoneInfoException(errmsg)
  1027. def set_zone_class(self, zone_class_str):
  1028. """Set the zone class given an RR class str (e.g. "IN"). If
  1029. zone_class_str is None, it will default to what is specified
  1030. in the specification file for this module. Raises
  1031. XfrinZoneInfoException if the string cannot be parsed."""
  1032. # TODO: remove _str
  1033. self.class_str = zone_class_str or self._module_cc.get_default_value("zones/class")
  1034. if zone_class_str == None:
  1035. #TODO rrclass->zone_class
  1036. self.rrclass = RRClass(self._module_cc.get_default_value("zones/class"))
  1037. else:
  1038. try:
  1039. self.rrclass = RRClass(zone_class_str)
  1040. except InvalidRRClass:
  1041. logger.error(XFRIN_BAD_ZONE_CLASS, zone_class_str)
  1042. errmsg = "invalid zone class: " + zone_class_str
  1043. raise XfrinZoneInfoException(errmsg)
  1044. def set_tsig_key(self, tsig_key_str):
  1045. """Set the tsig_key for this zone, given a TSIG key string
  1046. representation. If tsig_key_str is None, no TSIG key will
  1047. be set. Raises XfrinZoneInfoException if tsig_key_str cannot
  1048. be parsed."""
  1049. if tsig_key_str is None:
  1050. self.tsig_key = None
  1051. else:
  1052. try:
  1053. self.tsig_key = TSIGKey(tsig_key_str)
  1054. except InvalidParameter as ipe:
  1055. logger.error(XFRIN_BAD_TSIG_KEY_STRING, tsig_key_str)
  1056. errmsg = "bad TSIG key string: " + tsig_key_str
  1057. raise XfrinZoneInfoException(errmsg)
  1058. def set_use_ixfr(self, use_ixfr):
  1059. """Set use_ixfr. If set to True, it will use
  1060. IXFR for incoming transfers. If set to False, it will use AXFR.
  1061. At this moment there is no automatic fallback"""
  1062. # TODO: http://bind10.isc.org/ticket/1279
  1063. if use_ixfr is None:
  1064. self.use_ixfr = \
  1065. self._module_cc.get_default_value("zones/use_ixfr")
  1066. else:
  1067. self.use_ixfr = use_ixfr
  1068. def get_master_addr_info(self):
  1069. return (self.master_addr.family, socket.SOCK_STREAM,
  1070. (str(self.master_addr), self.master_port))
  1071. def _do_auth_loadzone(server, zone_name, zone_class):
  1072. # On a successful zone transfer, if the zone is served by
  1073. # b10-auth in the in-memory data source using sqlite3 as a
  1074. # backend, send the "loadzone" command for the zone to auth.
  1075. datasources, is_default =\
  1076. server._module_cc.get_remote_config_value(AUTH_MODULE_NAME, "datasources")
  1077. if is_default:
  1078. return
  1079. for d in datasources:
  1080. if "type" not in d:
  1081. continue
  1082. try:
  1083. if "class" in d:
  1084. dclass = RRClass(d["class"])
  1085. else:
  1086. dclass = RRClass("IN")
  1087. except InvalidRRClass as err:
  1088. logger.info(XFRIN_AUTH_CONFIG_RRCLASS_ERROR, str(err))
  1089. continue
  1090. if d["type"].lower() == "memory" and dclass == zone_class:
  1091. for zone in d["zones"]:
  1092. if "filetype" not in zone:
  1093. continue
  1094. if "origin" not in zone:
  1095. continue
  1096. if "filetype" not in zone:
  1097. continue
  1098. try:
  1099. name = Name(zone["origin"])
  1100. except (EmptyLabel, TooLongLabel, BadLabelType, BadEscape, TooLongName, IncompleteName):
  1101. logger.info(XFRIN_AUTH_CONFIG_NAME_PARSER_ERROR, str(err))
  1102. continue
  1103. if zone["filetype"].lower() == "sqlite3" and name == zone_name:
  1104. param = {"origin": zone_name.to_text(),
  1105. "class": zone_class.to_text(),
  1106. "datasrc": d["type"]}
  1107. logger.debug(DBG_XFRIN_TRACE, XFRIN_AUTH_LOADZONE,
  1108. param["origin"], param["class"], param["datasrc"])
  1109. msg = create_command("loadzone", param)
  1110. seq = server._send_cc_session.group_sendmsg(msg, AUTH_MODULE_NAME)
  1111. answer, env = server._send_cc_session.group_recvmsg(False, seq)
  1112. class Xfrin:
  1113. def __init__(self):
  1114. self._max_transfers_in = 10
  1115. self._zones = {}
  1116. # This is a set of (zone/class) tuples (both as strings),
  1117. # representing the in-memory zones maintaned by Xfrin. It
  1118. # is used to trigger Auth/in-memory so that it reloads
  1119. # zones when they have been transfered in
  1120. self._memory_zones = set()
  1121. self._cc_setup()
  1122. self.recorder = XfrinRecorder()
  1123. self._shutdown_event = threading.Event()
  1124. def _cc_setup(self):
  1125. '''This method is used only as part of initialization, but is
  1126. implemented separately for convenience of unit tests; by letting
  1127. the test code override this method we can test most of this class
  1128. without requiring a command channel.'''
  1129. # Create one session for sending command to other modules, because the
  1130. # listening session will block the send operation.
  1131. self._send_cc_session = isc.cc.Session()
  1132. self._module_cc = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  1133. self.config_handler,
  1134. self.command_handler)
  1135. self._module_cc.start()
  1136. config_data = self._module_cc.get_full_config()
  1137. self.config_handler(config_data)
  1138. self._module_cc.add_remote_config(AUTH_SPECFILE_LOCATION,
  1139. self._auth_config_handler)
  1140. def _cc_check_command(self):
  1141. '''This is a straightforward wrapper for cc.check_command,
  1142. but provided as a separate method for the convenience
  1143. of unit tests.'''
  1144. self._module_cc.check_command(False)
  1145. def _get_zone_info(self, name, rrclass):
  1146. """Returns the ZoneInfo object containing the configured data
  1147. for the given zone name. If the zone name did not have any
  1148. data, returns None"""
  1149. return self._zones.get((name.to_text(), rrclass.to_text()))
  1150. def _add_zone_info(self, zone_info):
  1151. """Add the zone info. Raises a XfrinZoneInfoException if a zone
  1152. with the same name and class is already configured"""
  1153. key = (zone_info.name.to_text(), zone_info.class_str)
  1154. if key in self._zones:
  1155. raise XfrinZoneInfoException("zone " + str(key) +
  1156. " configured multiple times")
  1157. self._zones[key] = zone_info
  1158. def _clear_zone_info(self):
  1159. self._zones = {}
  1160. def config_handler(self, new_config):
  1161. # backup all config data (should there be a problem in the new
  1162. # data)
  1163. old_max_transfers_in = self._max_transfers_in
  1164. old_zones = self._zones
  1165. self._max_transfers_in = new_config.get("transfers_in") or self._max_transfers_in
  1166. if 'zones' in new_config:
  1167. self._clear_zone_info()
  1168. for zone_config in new_config.get('zones'):
  1169. try:
  1170. zone_info = ZoneInfo(zone_config, self._module_cc)
  1171. self._add_zone_info(zone_info)
  1172. except XfrinZoneInfoException as xce:
  1173. self._zones = old_zones
  1174. self._max_transfers_in = old_max_transfers_in
  1175. return create_answer(1, str(xce))
  1176. return create_answer(0)
  1177. def _auth_config_handler(self, new_config, config_data):
  1178. # Config handler for changes in Auth configuration
  1179. self._set_db_file()
  1180. self._set_memory_zones(new_config, config_data)
  1181. def _clear_memory_zones(self):
  1182. """Clears the memory_zones set; called before processing the
  1183. changed list of memory datasource zones that have file type
  1184. sqlite3"""
  1185. self._memory_zones.clear()
  1186. def _is_memory_zone(self, zone_name_str, zone_class_str):
  1187. """Returns true if the given zone/class combination is configured
  1188. in the in-memory datasource of the Auth process with file type
  1189. 'sqlite3'.
  1190. Note: this method is not thread-safe. We are considering
  1191. changing the threaded model here, but if we do not, take
  1192. care in accessing and updating the memory zone set (or add
  1193. locks)
  1194. """
  1195. # Normalize them first, if either conversion fails, return false
  1196. # (they won't be in the set anyway)
  1197. try:
  1198. zone_name_str = Name(zone_name_str).to_text().lower()
  1199. zone_class_str = RRClass(zone_class_str).to_text()
  1200. except Exception:
  1201. return False
  1202. return (zone_name_str, zone_class_str) in self._memory_zones
  1203. def _set_memory_zones(self, new_config, config_data):
  1204. """Part of the _auth_config_handler function, keeps an internal set
  1205. of zones in the datasources config subset that have 'sqlite3' as
  1206. their file type.
  1207. Note: this method is not thread-safe. We are considering
  1208. changing the threaded model here, but if we do not, take
  1209. care in accessing and updating the memory zone set (or add
  1210. locks)
  1211. """
  1212. # walk through the data and collect the memory zones
  1213. # If this causes any exception, assume we were passed bad data
  1214. # and keep the original set
  1215. new_memory_zones = set()
  1216. try:
  1217. if "datasources" in new_config:
  1218. for datasource in new_config["datasources"]:
  1219. if "class" in datasource:
  1220. ds_class = RRClass(datasource["class"])
  1221. else:
  1222. # Get the default
  1223. ds_class = RRClass(config_data.get_default_value(
  1224. "datasources/class"))
  1225. if datasource["type"] == "memory":
  1226. for zone in datasource["zones"]:
  1227. if "filetype" in zone and \
  1228. zone["filetype"] == "sqlite3":
  1229. zone_name = Name(zone["origin"])
  1230. zone_name_str = zone_name.to_text().lower()
  1231. new_memory_zones.add((zone_name_str,
  1232. ds_class.to_text()))
  1233. # Ok, we can use the data, update our list
  1234. self._memory_zones = new_memory_zones
  1235. except Exception:
  1236. # Something is wrong with the data. If this data even reached us,
  1237. # we cannot do more than assume the real module has logged and
  1238. # reported an error. Keep the old set.
  1239. return
  1240. def shutdown(self):
  1241. ''' shutdown the xfrin process. the thread which is doing xfrin should be
  1242. terminated.
  1243. '''
  1244. self._module_cc.remove_remote_config(AUTH_SPECFILE_LOCATION)
  1245. self._module_cc.send_stopping()
  1246. self._shutdown_event.set()
  1247. main_thread = threading.currentThread()
  1248. for th in threading.enumerate():
  1249. if th is main_thread:
  1250. continue
  1251. th.join()
  1252. def command_handler(self, command, args):
  1253. answer = create_answer(0)
  1254. try:
  1255. if command == 'shutdown':
  1256. self._shutdown_event.set()
  1257. elif command == 'notify' or command == REFRESH_FROM_ZONEMGR:
  1258. # Xfrin receives the refresh/notify command from zone manager.
  1259. # notify command maybe has the parameters which
  1260. # specify the notifyfrom address and port, according the RFC1996, zone
  1261. # transfer should starts first from the notifyfrom, but now, let 'TODO' it.
  1262. # (using the value now, while we can only set one master address, would be
  1263. # a security hole. Once we add the ability to have multiple master addresses,
  1264. # we should check if it matches one of them, and then use it.)
  1265. (zone_name, rrclass) = self._parse_zone_name_and_class(args)
  1266. zone_str = format_zone_str(zone_name, rrclass)
  1267. zone_info = self._get_zone_info(zone_name, rrclass)
  1268. notify_addr = self._parse_master_and_port(args, zone_name,
  1269. rrclass)
  1270. if zone_info is None:
  1271. # TODO what to do? no info known about zone. defaults?
  1272. errmsg = "Got notification to retransfer unknown zone " + zone_str
  1273. logger.info(XFRIN_RETRANSFER_UNKNOWN_ZONE, zone_str)
  1274. answer = create_answer(1, errmsg)
  1275. else:
  1276. request_type = RRType.AXFR()
  1277. if zone_info.use_ixfr:
  1278. request_type = RRType.IXFR()
  1279. master_addr = zone_info.get_master_addr_info()
  1280. if notify_addr[0] == master_addr[0] and\
  1281. notify_addr[2] == master_addr[2]:
  1282. ret = self.xfrin_start(zone_name,
  1283. rrclass,
  1284. self._get_db_file(),
  1285. master_addr,
  1286. zone_info.tsig_key, request_type,
  1287. True)
  1288. answer = create_answer(ret[0], ret[1])
  1289. else:
  1290. notify_addr_str = format_addrinfo(notify_addr)
  1291. master_addr_str = format_addrinfo(master_addr)
  1292. errmsg = "Got notification for " + zone_str\
  1293. + "from unknown address: " + notify_addr_str;
  1294. logger.info(XFRIN_NOTIFY_UNKNOWN_MASTER, zone_str,
  1295. notify_addr_str, master_addr_str)
  1296. answer = create_answer(1, errmsg)
  1297. elif command == 'retransfer' or command == 'refresh':
  1298. # Xfrin receives the retransfer/refresh from cmdctl(sent by bindctl).
  1299. # If the command has specified master address, do transfer from the
  1300. # master address, or else do transfer from the configured masters.
  1301. (zone_name, rrclass) = self._parse_zone_name_and_class(args)
  1302. master_addr = self._parse_master_and_port(args, zone_name,
  1303. rrclass)
  1304. zone_info = self._get_zone_info(zone_name, rrclass)
  1305. tsig_key = None
  1306. request_type = RRType.AXFR()
  1307. if zone_info:
  1308. tsig_key = zone_info.tsig_key
  1309. if zone_info.use_ixfr:
  1310. request_type = RRType.IXFR()
  1311. db_file = args.get('db_file') or self._get_db_file()
  1312. ret = self.xfrin_start(zone_name,
  1313. rrclass,
  1314. db_file,
  1315. master_addr,
  1316. tsig_key, request_type,
  1317. (False if command == 'retransfer' else True))
  1318. answer = create_answer(ret[0], ret[1])
  1319. else:
  1320. answer = create_answer(1, 'unknown command: ' + command)
  1321. except XfrinException as err:
  1322. logger.error(XFRIN_COMMAND_ERROR, command, str(err))
  1323. answer = create_answer(1, str(err))
  1324. return answer
  1325. def _parse_zone_name_and_class(self, args):
  1326. zone_name_str = args.get('zone_name')
  1327. if zone_name_str is None:
  1328. raise XfrinException('zone name should be provided')
  1329. return (_check_zone_name(zone_name_str), _check_zone_class(args.get('zone_class')))
  1330. def _parse_master_and_port(self, args, zone_name, zone_class):
  1331. """
  1332. Return tuple (family, socktype, sockaddr) for address and port in given
  1333. args dict.
  1334. IPv4 and IPv6 are the only supported addresses now, so sockaddr will be
  1335. (address, port). The socktype is socket.SOCK_STREAM for now.
  1336. """
  1337. # check if we have configured info about this zone, in case
  1338. # port or master are not specified
  1339. zone_info = self._get_zone_info(zone_name, zone_class)
  1340. addr_str = args.get('master')
  1341. if addr_str is None:
  1342. if zone_info is not None:
  1343. addr = zone_info.master_addr
  1344. else:
  1345. raise XfrinException("Master address not given or "
  1346. "configured for " + zone_name.to_text())
  1347. else:
  1348. try:
  1349. addr = isc.net.parse.addr_parse(addr_str)
  1350. except ValueError as err:
  1351. raise XfrinException("failed to resolve master address %s: %s" %
  1352. (addr_str, str(err)))
  1353. port_str = args.get('port')
  1354. if port_str is None:
  1355. if zone_info is not None:
  1356. port = zone_info.master_port
  1357. else:
  1358. port = DEFAULT_MASTER_PORT
  1359. else:
  1360. try:
  1361. port = isc.net.parse.port_parse(port_str)
  1362. except ValueError as err:
  1363. raise XfrinException("failed to parse port=%s: %s" %
  1364. (port_str, str(err)))
  1365. return (addr.family, socket.SOCK_STREAM, (str(addr), port))
  1366. def _get_db_file(self):
  1367. return self._db_file
  1368. def _set_db_file(self):
  1369. db_file, is_default =\
  1370. self._module_cc.get_remote_config_value(AUTH_MODULE_NAME, "database_file")
  1371. if is_default and "B10_FROM_BUILD" in os.environ:
  1372. # override the local database setting if it is default and we
  1373. # are running from the source tree
  1374. # This should be hidden inside the data source library and/or
  1375. # done as a configuration, and this special case should be gone).
  1376. db_file = os.environ["B10_FROM_BUILD"] + os.sep +\
  1377. "bind10_zones.sqlite3"
  1378. self._db_file = db_file
  1379. def publish_xfrin_news(self, zone_name, zone_class, xfr_result):
  1380. '''Send command to xfrout/zone manager module.
  1381. If xfrin has finished successfully for one zone, tell the good
  1382. news(command: zone_new_data_ready) to zone manager and xfrout.
  1383. if xfrin failed, just tell the bad news to zone manager, so that
  1384. it can reset the refresh timer for that zone. '''
  1385. param = {'zone_name': zone_name.to_text(),
  1386. 'zone_class': zone_class.to_text()}
  1387. if xfr_result == XFRIN_OK:
  1388. _do_auth_loadzone(self, zone_name, zone_class)
  1389. msg = create_command(notify_out.ZONE_NEW_DATA_READY_CMD, param)
  1390. # catch the exception, in case msgq has been killed.
  1391. try:
  1392. seq = self._send_cc_session.group_sendmsg(msg,
  1393. XFROUT_MODULE_NAME)
  1394. try:
  1395. answer, env = self._send_cc_session.group_recvmsg(False,
  1396. seq)
  1397. except isc.cc.session.SessionTimeout:
  1398. pass # for now we just ignore the failure
  1399. seq = self._send_cc_session.group_sendmsg(msg, ZONE_MANAGER_MODULE_NAME)
  1400. try:
  1401. answer, env = self._send_cc_session.group_recvmsg(False,
  1402. seq)
  1403. except isc.cc.session.SessionTimeout:
  1404. pass # for now we just ignore the failure
  1405. except socket.error as err:
  1406. logger.error(XFRIN_MSGQ_SEND_ERROR, XFROUT_MODULE_NAME, ZONE_MANAGER_MODULE_NAME)
  1407. else:
  1408. msg = create_command(ZONE_XFRIN_FAILED, param)
  1409. # catch the exception, in case msgq has been killed.
  1410. try:
  1411. seq = self._send_cc_session.group_sendmsg(msg, ZONE_MANAGER_MODULE_NAME)
  1412. try:
  1413. answer, env = self._send_cc_session.group_recvmsg(False,
  1414. seq)
  1415. except isc.cc.session.SessionTimeout:
  1416. pass # for now we just ignore the failure
  1417. except socket.error as err:
  1418. logger.error(XFRIN_MSGQ_SEND_ERROR_ZONE_MANAGER, ZONE_MANAGER_MODULE_NAME)
  1419. def startup(self):
  1420. logger.debug(DBG_PROCESS, XFRIN_STARTED)
  1421. while not self._shutdown_event.is_set():
  1422. self._cc_check_command()
  1423. def xfrin_start(self, zone_name, rrclass, db_file, master_addrinfo,
  1424. tsig_key, request_type, check_soa=True):
  1425. if "pydnspp" not in sys.modules:
  1426. return (1, "xfrin failed, can't load dns message python library: 'pydnspp'")
  1427. # check max_transfer_in, else return quota error
  1428. if self.recorder.count() >= self._max_transfers_in:
  1429. return (1, 'xfrin quota error')
  1430. if self.recorder.xfrin_in_progress(zone_name):
  1431. return (1, 'zone xfrin is in progress')
  1432. xfrin_thread = threading.Thread(target = process_xfrin,
  1433. args = (self,
  1434. self.recorder,
  1435. zone_name,
  1436. rrclass,
  1437. db_file,
  1438. self._shutdown_event,
  1439. master_addrinfo, check_soa,
  1440. tsig_key, request_type))
  1441. xfrin_thread.start()
  1442. return (0, 'zone xfrin is started')
  1443. xfrind = None
  1444. def signal_handler(signal, frame):
  1445. if xfrind:
  1446. xfrind.shutdown()
  1447. sys.exit(0)
  1448. def set_signal_handler():
  1449. signal.signal(signal.SIGTERM, signal_handler)
  1450. signal.signal(signal.SIGINT, signal_handler)
  1451. def set_cmd_options(parser):
  1452. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  1453. help="This option is obsolete and has no effect.")
  1454. def main(xfrin_class, use_signal=True):
  1455. """The main loop of the Xfrin daemon.
  1456. @param xfrin_class: A class of the Xfrin object. This is normally Xfrin,
  1457. but can be a subclass of it for customization.
  1458. @param use_signal: True if this process should catch signals. This is
  1459. normally True, but may be disabled when this function is called in a
  1460. testing context."""
  1461. global xfrind
  1462. try:
  1463. parser = OptionParser(version = __version__)
  1464. set_cmd_options(parser)
  1465. (options, args) = parser.parse_args()
  1466. if use_signal:
  1467. set_signal_handler()
  1468. xfrind = xfrin_class()
  1469. xfrind.startup()
  1470. except KeyboardInterrupt:
  1471. logger.info(XFRIN_STOPPED_BY_KEYBOARD)
  1472. except isc.cc.session.SessionError as e:
  1473. logger.error(XFRIN_CC_SESSION_ERROR, str(e))
  1474. except Exception as e:
  1475. logger.error(XFRIN_UNKNOWN_ERROR, str(e))
  1476. if xfrind:
  1477. xfrind.shutdown()
  1478. if __name__ == '__main__':
  1479. main(Xfrin)