xfrin.py.in 75 KB

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