xfrin.py.in 83 KB

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