xfrin.py.in 78 KB

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