xfrin.py.in 78 KB

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