xfrin_test.py 139 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197
  1. # Copyright (C) 2009-2011 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. import unittest
  16. import re
  17. import shutil
  18. import socket
  19. import sys
  20. import io
  21. from isc.testutils.tsigctx_mock import MockTSIGContext
  22. from isc.testutils.ccsession_mock import MockModuleCCSession
  23. from isc.testutils.rrset_utils import *
  24. from xfrin import *
  25. import xfrin
  26. from isc.xfrin.diff import Diff
  27. import isc.log
  28. from isc.server_common.tsig_keyring import init_keyring, get_keyring
  29. # If we use any python library that is basically a wrapper for
  30. # a library we use as well (like sqlite3 in our datasources),
  31. # we must make sure we import ours first; If we have special
  32. # rpath or libtool rules to pick the correct version, python might
  33. # choose the wrong one first, if those rules aren't hit first.
  34. # This would result in missing symbols later.
  35. import sqlite3
  36. #
  37. # Commonly used (mostly constant) test parameters
  38. #
  39. TEST_ZONE_NAME_STR = "example.com."
  40. TEST_ZONE_NAME = Name(TEST_ZONE_NAME_STR)
  41. TEST_RRCLASS = RRClass.IN()
  42. TEST_RRCLASS_STR = 'IN'
  43. TEST_DB_FILE = 'db_file'
  44. TEST_MASTER_IPV4_ADDRESS = '127.0.0.1'
  45. TEST_MASTER_IPV4_ADDRINFO = (socket.AF_INET, socket.SOCK_STREAM,
  46. (TEST_MASTER_IPV4_ADDRESS, 53))
  47. TEST_MASTER_IPV6_ADDRESS = '::1'
  48. TEST_MASTER_IPV6_ADDRINFO = (socket.AF_INET6, socket.SOCK_STREAM,
  49. (TEST_MASTER_IPV6_ADDRESS, 53))
  50. TESTDATA_SRCDIR = os.getenv("TESTDATASRCDIR")
  51. TESTDATA_OBJDIR = os.getenv("TESTDATAOBJDIR")
  52. # XXX: This should be a non priviledge port that is unlikely to be used.
  53. # If some other process uses this port test will fail.
  54. TEST_MASTER_PORT = '53535'
  55. TSIG_KEY = TSIGKey("example.com:SFuWd/q99SzF8Yzd1QbB9g==")
  56. # SOA intended to be used for the new SOA as a result of transfer.
  57. soa_rdata = Rdata(RRType.SOA(), TEST_RRCLASS,
  58. 'master.example.com. admin.example.com. ' +
  59. '1234 3600 1800 2419200 7200')
  60. soa_rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.SOA(), RRTTL(3600))
  61. soa_rrset.add_rdata(soa_rdata)
  62. # SOA intended to be used for the current SOA at the secondary side.
  63. # Note that its serial is smaller than that of soa_rdata.
  64. begin_soa_rdata = Rdata(RRType.SOA(), TEST_RRCLASS,
  65. 'master.example.com. admin.example.com. ' +
  66. '1230 3600 1800 2419200 7200')
  67. begin_soa_rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.SOA(), RRTTL(3600))
  68. begin_soa_rrset.add_rdata(begin_soa_rdata)
  69. example_axfr_question = Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.AXFR())
  70. example_soa_question = Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.SOA())
  71. default_questions = [example_axfr_question]
  72. default_answers = [soa_rrset]
  73. def get_fake_time_time():
  74. '''Returns a temporary replacement function for time.time(), which
  75. always returns 0.1 more than the previous call. This is to make
  76. sure these tests do not fail on systems where the time.time()
  77. function has a high minimal accuracy.
  78. This fake time.time() is usually set in place of the real one
  79. where we need testing of get_running_time(). It is done is
  80. as low a scope as possible, so as not to mess up unit test
  81. framework time related tests. It must be set before
  82. XfrinTransferState (or any class that initializes that) is
  83. initialized.
  84. And every time it is set up, in must be reset later (again, so
  85. as not to mess up the framework's concept of time).
  86. '''
  87. fake_time = 0.0
  88. def fake_time_time():
  89. nonlocal fake_time
  90. fake_time += 0.1
  91. return fake_time
  92. return fake_time_time
  93. def check_diffs(assert_fn, expected, actual):
  94. '''A helper function checking the differences made in the XFR session.
  95. This is expected called from some subclass of unittest.TestCase and
  96. assert_fn is generally expected to be 'self.assertEqual' of that class.
  97. '''
  98. assert_fn(len(expected), len(actual))
  99. for (diffs_exp, diffs_actual) in zip(expected, actual):
  100. assert_fn(len(diffs_exp), len(diffs_actual))
  101. for (diff_exp, diff_actual) in zip(diffs_exp, diffs_actual):
  102. # operation should match
  103. assert_fn(diff_exp[0], diff_actual[0])
  104. # The diff as RRset should be equal (for simplicity we assume
  105. # all RRsets contain exactly one RDATA)
  106. assert_fn(diff_exp[1].get_name(), diff_actual[1].get_name())
  107. assert_fn(diff_exp[1].get_type(), diff_actual[1].get_type())
  108. assert_fn(diff_exp[1].get_class(), diff_actual[1].get_class())
  109. assert_fn(diff_exp[1].get_rdata_count(),
  110. diff_actual[1].get_rdata_count())
  111. assert_fn(1, diff_exp[1].get_rdata_count())
  112. assert_fn(diff_exp[1].get_rdata()[0],
  113. diff_actual[1].get_rdata()[0])
  114. class XfrinTestException(Exception):
  115. pass
  116. class XfrinTestTimeoutException(Exception):
  117. pass
  118. class MockCC(MockModuleCCSession):
  119. def get_default_value(self, identifier):
  120. # The returned values should be identical to the spec file
  121. # XXX: these should be retrieved from the spec file
  122. # (see MyCCSession of xfrout_test.py.in)
  123. if identifier == "zones/master_port":
  124. return TEST_MASTER_PORT
  125. if identifier == "zones/class":
  126. return TEST_RRCLASS_STR
  127. if identifier == "zones/use_ixfr":
  128. return False
  129. def add_remote_config_by_name(self, name, callback):
  130. pass
  131. def get_remote_config_value(self, module, identifier):
  132. if module == 'tsig_keys' and identifier == 'keys':
  133. return (['example.com.key.:EvAAsfU2h7uofnmqaTCrhHunGsc='], True)
  134. else:
  135. raise Exception('MockCC requested for unknown config value ' +
  136. + module + "/" + identifier)
  137. def remove_remote_config(self, module_name):
  138. pass
  139. class MockRRsetCollection:
  140. '''
  141. A mock RRset collection. We don't use it really (we mock the method that
  142. it is passed to too), so it's empty.
  143. '''
  144. pass
  145. class MockDataSourceClient():
  146. '''A simple mock data source client.
  147. This class provides a minimal set of wrappers related the data source
  148. API that would be used by Diff objects. For our testing purposes they
  149. only keep track of the history of the changes.
  150. '''
  151. def __init__(self):
  152. self.force_fail = False # if True, raise an exception on commit
  153. self.committed_diffs = []
  154. self.diffs = []
  155. def get_class(self):
  156. '''Mock version of get_class().
  157. We simply return the commonly used constant RR class. If and when
  158. we use this mock for a different RR class we need to adjust it
  159. accordingly.
  160. '''
  161. return TEST_RRCLASS
  162. def find_zone(self, zone_name):
  163. '''Mock version of find_zone().
  164. It returns itself (subsequently acting as a mock ZoneFinder) for
  165. some test zone names. For some others it returns either NOTFOUND
  166. or PARTIALMATCH.
  167. '''
  168. if zone_name == TEST_ZONE_NAME or \
  169. zone_name == Name('no-soa.example') or \
  170. zone_name == Name('dup-soa.example'):
  171. return (isc.datasrc.DataSourceClient.SUCCESS, self)
  172. elif zone_name == Name('no-such-zone.example'):
  173. return (DataSourceClient.NOTFOUND, None)
  174. elif zone_name == Name('partial-match-zone.example'):
  175. return (DataSourceClient.PARTIALMATCH, self)
  176. raise ValueError('Unexpected input to mock client: bug in test case?')
  177. def find(self, name, rrtype, options=ZoneFinder.FIND_DEFAULT):
  178. '''Mock ZoneFinder.find().
  179. It returns the predefined SOA RRset to queries for SOA of the common
  180. test zone name. It also emulates some unusual cases for special
  181. zone names.
  182. '''
  183. if name == TEST_ZONE_NAME and rrtype == RRType.SOA():
  184. return (ZoneFinder.SUCCESS, begin_soa_rrset, 0)
  185. if name == Name('no-soa.example'):
  186. return (ZoneFinder.NXDOMAIN, None, 0)
  187. if name == Name('dup-soa.example'):
  188. dup_soa_rrset = RRset(name, TEST_RRCLASS, RRType.SOA(), RRTTL(0))
  189. dup_soa_rrset.add_rdata(begin_soa_rdata)
  190. dup_soa_rrset.add_rdata(soa_rdata)
  191. return (ZoneFinder.SUCCESS, dup_soa_rrset, 0)
  192. raise ValueError('Unexpected input to mock finder: bug in test case?')
  193. def get_updater(self, zone_name, replace, journaling=False):
  194. self._journaling_enabled = journaling
  195. return self
  196. def get_rrset_collection(self):
  197. '''
  198. Pretend to be a zone updater and provide a (dummy) rrset collection.
  199. '''
  200. return MockRRsetCollection()
  201. def add_rrset(self, rrset):
  202. self.diffs.append(('add', rrset))
  203. def delete_rrset(self, rrset):
  204. self.diffs.append(('delete', rrset))
  205. def commit(self):
  206. if self.force_fail:
  207. raise isc.datasrc.Error('Updater.commit() failed')
  208. self.committed_diffs.append(self.diffs)
  209. self.diffs = []
  210. class MockXfrin(Xfrin):
  211. # This is a class attribute of a callable object that specifies a non
  212. # default behavior triggered in _cc_check_command(). Specific test methods
  213. # are expected to explicitly set this attribute before creating a
  214. # MockXfrin object (when it needs a non default behavior).
  215. # See the TestMain class.
  216. check_command_hook = None
  217. def _cc_setup(self):
  218. self._tsig_key = None
  219. self._module_cc = MockCC()
  220. init_keyring(self._module_cc)
  221. pass
  222. def _get_db_file(self):
  223. pass
  224. def _cc_check_command(self):
  225. self._shutdown_event.set()
  226. if MockXfrin.check_command_hook:
  227. MockXfrin.check_command_hook()
  228. def xfrin_start(self, zone_name, rrclass, db_file, master_addrinfo,
  229. tsig_key, request_type, check_soa=True):
  230. # store some of the arguments for verification, then call this
  231. # method in the superclass
  232. self.xfrin_started_master_addr = master_addrinfo[2][0]
  233. self.xfrin_started_master_port = master_addrinfo[2][1]
  234. self.xfrin_started_request_type = request_type
  235. return Xfrin.xfrin_start(self, zone_name, rrclass, None,
  236. master_addrinfo, tsig_key,
  237. request_type, check_soa)
  238. class MockXfrinConnection(XfrinConnection):
  239. def __init__(self, sock_map, zone_name, rrclass, datasrc_client,
  240. shutdown_event, master_addr, tsig_key=None):
  241. super().__init__(sock_map, zone_name, rrclass, MockDataSourceClient(),
  242. shutdown_event, master_addr, TEST_DB_FILE)
  243. self.query_data = b''
  244. self.reply_data = b''
  245. self.force_time_out = False
  246. self.force_close = False
  247. self.qlen = None
  248. self.qid = None
  249. self.response_generator = None
  250. def _asyncore_loop(self):
  251. if self.force_close:
  252. self.handle_close()
  253. elif not self.force_time_out:
  254. self.handle_read()
  255. def connect_to_master(self):
  256. return True
  257. def recv(self, size):
  258. data = self.reply_data[:size]
  259. self.reply_data = self.reply_data[size:]
  260. if len(data) == 0:
  261. raise XfrinTestTimeoutException('Emulated timeout')
  262. if len(data) < size:
  263. raise XfrinTestException('cannot get reply data (' + str(size) +
  264. ' bytes)')
  265. return data
  266. def send(self, data):
  267. if self.qlen != None and len(self.query_data) >= self.qlen:
  268. # This is a new query. reset the internal state.
  269. self.qlen = None
  270. self.qid = None
  271. self.query_data = b''
  272. self.query_data += data
  273. # when the outgoing data is sufficiently large to contain the length
  274. # and the QID fields (4 octets or more), extract these fields.
  275. # The length will be reset the internal query data to support multiple
  276. # queries in a single test.
  277. # The QID will be used to construct a matching response.
  278. if len(self.query_data) >= 4 and self.qid == None:
  279. self.qlen = socket.htons(struct.unpack('H',
  280. self.query_data[0:2])[0])
  281. self.qid = socket.htons(struct.unpack('H', self.query_data[2:4])[0])
  282. # if the response generator method is specified, invoke it now.
  283. if self.response_generator != None:
  284. self.response_generator()
  285. return len(data)
  286. def create_response_data(self, response=True, auth=True, bad_qid=False,
  287. rcode=Rcode.NOERROR(),
  288. questions=default_questions,
  289. answers=default_answers,
  290. authorities=[],
  291. tsig_ctx=None):
  292. resp = Message(Message.RENDER)
  293. qid = self.qid
  294. if bad_qid:
  295. qid += 1
  296. resp.set_qid(qid)
  297. resp.set_opcode(Opcode.QUERY())
  298. resp.set_rcode(rcode)
  299. if response:
  300. resp.set_header_flag(Message.HEADERFLAG_QR)
  301. if auth:
  302. resp.set_header_flag(Message.HEADERFLAG_AA)
  303. [resp.add_question(q) for q in questions]
  304. [resp.add_rrset(Message.SECTION_ANSWER, a) for a in answers]
  305. [resp.add_rrset(Message.SECTION_AUTHORITY, a) for a in authorities]
  306. renderer = MessageRenderer()
  307. if tsig_ctx is not None:
  308. resp.to_wire(renderer, tsig_ctx)
  309. else:
  310. resp.to_wire(renderer)
  311. reply_data = struct.pack('H', socket.htons(renderer.get_length()))
  312. reply_data += renderer.get_data()
  313. return reply_data
  314. class TestXfrinState(unittest.TestCase):
  315. def setUp(self):
  316. self.sock_map = {}
  317. self.conn = MockXfrinConnection(self.sock_map, TEST_ZONE_NAME,
  318. TEST_RRCLASS, None, threading.Event(),
  319. TEST_MASTER_IPV4_ADDRINFO)
  320. self.conn.init_socket()
  321. self.begin_soa = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.SOA(),
  322. RRTTL(3600))
  323. self.begin_soa.add_rdata(Rdata(RRType.SOA(), TEST_RRCLASS,
  324. 'm. r. 1230 0 0 0 0'))
  325. self.ns_rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.NS(),
  326. RRTTL(3600))
  327. self.ns_rrset.add_rdata(Rdata(RRType.NS(), TEST_RRCLASS,
  328. 'ns.example.com.'))
  329. self.a_rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.A(),
  330. RRTTL(3600))
  331. self.a_rrset.add_rdata(Rdata(RRType.A(), TEST_RRCLASS, '192.0.2.1'))
  332. self.conn._datasrc_client = MockDataSourceClient()
  333. self.conn._diff = Diff(self.conn._datasrc_client, TEST_ZONE_NAME)
  334. class TestXfrinStateBase(TestXfrinState):
  335. def setUp(self):
  336. super().setUp()
  337. def test_handle_rr_on_base(self):
  338. # The base version of handle_rr() isn't supposed to be called
  339. # directly (the argument doesn't matter in this test)
  340. self.assertRaises(XfrinException, XfrinState().handle_rr, None)
  341. class TestXfrinInitialSOA(TestXfrinState):
  342. def setUp(self):
  343. super().setUp()
  344. self.state = XfrinInitialSOA()
  345. def test_handle_rr(self):
  346. # normal case
  347. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  348. self.assertEqual(type(XfrinFirstData()),
  349. type(self.conn.get_xfrstate()))
  350. self.assertEqual(1234, self.conn._end_serial.get_value())
  351. def test_handle_not_soa(self):
  352. # The given RR is not of SOA
  353. self.assertRaises(XfrinProtocolError, self.state.handle_rr, self.conn,
  354. self.ns_rrset)
  355. def test_handle_ixfr_uptodate(self):
  356. self.conn._request_type = RRType.IXFR()
  357. self.conn._request_serial = isc.dns.Serial(1234) # same as soa_rrset
  358. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  359. self.assertEqual(type(XfrinIXFRUptodate()),
  360. type(self.conn.get_xfrstate()))
  361. def test_handle_ixfr_uptodate2(self):
  362. self.conn._request_type = RRType.IXFR()
  363. self.conn._request_serial = isc.dns.Serial(1235) # > soa_rrset
  364. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  365. self.assertEqual(type(XfrinIXFRUptodate()),
  366. type(self.conn.get_xfrstate()))
  367. def test_handle_ixfr_uptodate3(self):
  368. # Similar to the previous case, but checking serial number arithmetic
  369. # comparison
  370. self.conn._request_type = RRType.IXFR()
  371. self.conn._request_serial = isc.dns.Serial(0xffffffff)
  372. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  373. self.assertEqual(type(XfrinFirstData()),
  374. type(self.conn.get_xfrstate()))
  375. def test_handle_axfr_uptodate(self):
  376. # "request serial" should matter only for IXFR
  377. self.conn._request_type = RRType.AXFR()
  378. self.conn._request_serial = isc.dns.Serial(1234) # same as soa_rrset
  379. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  380. self.assertEqual(type(XfrinFirstData()),
  381. type(self.conn.get_xfrstate()))
  382. def test_finish_message(self):
  383. self.assertTrue(self.state.finish_message(self.conn))
  384. class TestXfrinFirstData(TestXfrinState):
  385. def setUp(self):
  386. super().setUp()
  387. self.state = XfrinFirstData()
  388. self.conn._request_type = RRType.IXFR()
  389. # arbitrary chosen serial < 1234:
  390. self.conn._request_serial = isc.dns.Serial(1230)
  391. self.conn._diff = None # should be replaced in the AXFR case
  392. def test_handle_ixfr_begin_soa(self):
  393. self.conn._request_type = RRType.IXFR()
  394. self.assertFalse(self.state.handle_rr(self.conn, self.begin_soa))
  395. self.assertEqual(type(XfrinIXFRDeleteSOA()),
  396. type(self.conn.get_xfrstate()))
  397. def test_handle_axfr(self):
  398. # If the original type is AXFR, other conditions aren't considered,
  399. # and AXFR processing will continue
  400. self.conn._request_type = RRType.AXFR()
  401. self.assertFalse(self.state.handle_rr(self.conn, self.begin_soa))
  402. self.assertEqual(type(XfrinAXFR()), type(self.conn.get_xfrstate()))
  403. def test_handle_ixfr_to_axfr(self):
  404. # Detecting AXFR-compatible IXFR response by seeing a non SOA RR after
  405. # the initial SOA. Should switch to AXFR.
  406. self.assertFalse(self.state.handle_rr(self.conn, self.ns_rrset))
  407. self.assertEqual(type(XfrinAXFR()), type(self.conn.get_xfrstate()))
  408. # The Diff for AXFR should be created at this point
  409. self.assertNotEqual(None, self.conn._diff)
  410. def test_handle_ixfr_to_axfr_by_different_soa(self):
  411. # An unusual case: Response contains two consecutive SOA but the
  412. # serial of the second does not match the requested one. See
  413. # the documentation for XfrinFirstData.handle_rr().
  414. self.assertFalse(self.state.handle_rr(self.conn, soa_rrset))
  415. self.assertEqual(type(XfrinAXFR()), type(self.conn.get_xfrstate()))
  416. self.assertNotEqual(None, self.conn._diff)
  417. def test_finish_message(self):
  418. self.assertTrue(self.state.finish_message(self.conn))
  419. class TestXfrinIXFRDeleteSOA(TestXfrinState):
  420. def setUp(self):
  421. super().setUp()
  422. self.state = XfrinIXFRDeleteSOA()
  423. # In this state a new Diff object is expected to be created. To
  424. # confirm it, we nullify it beforehand.
  425. self.conn._diff = None
  426. def test_handle_rr(self):
  427. self.assertTrue(self.state.handle_rr(self.conn, self.begin_soa))
  428. self.assertEqual(type(XfrinIXFRDelete()),
  429. type(self.conn.get_xfrstate()))
  430. self.assertEqual([('delete', self.begin_soa)],
  431. self.conn._diff.get_buffer())
  432. def test_handle_non_soa(self):
  433. self.assertRaises(XfrinException, self.state.handle_rr, self.conn,
  434. self.ns_rrset)
  435. def test_finish_message(self):
  436. self.assertTrue(self.state.finish_message(self.conn))
  437. class TestXfrinIXFRDelete(TestXfrinState):
  438. def setUp(self):
  439. super().setUp()
  440. # We need record the state in 'conn' to check the case where the
  441. # state doesn't change.
  442. XfrinIXFRDelete().set_xfrstate(self.conn, XfrinIXFRDelete())
  443. self.state = self.conn.get_xfrstate()
  444. def test_handle_delete_rr(self):
  445. # Non SOA RRs are simply (goting to be) deleted in this state
  446. self.assertTrue(self.state.handle_rr(self.conn, self.ns_rrset))
  447. self.assertEqual([('delete', self.ns_rrset)],
  448. self.conn._diff.get_buffer())
  449. # The state shouldn't change
  450. self.assertEqual(type(XfrinIXFRDelete()),
  451. type(self.conn.get_xfrstate()))
  452. def test_handle_soa(self):
  453. # SOA in this state means the beginning of added RRs. This SOA
  454. # should also be added in the next state, so handle_rr() should return
  455. # false.
  456. self.assertFalse(self.state.handle_rr(self.conn, soa_rrset))
  457. self.assertEqual([], self.conn._diff.get_buffer())
  458. self.assertEqual(1234, self.conn._current_serial.get_value())
  459. self.assertEqual(type(XfrinIXFRAddSOA()),
  460. type(self.conn.get_xfrstate()))
  461. def test_finish_message(self):
  462. self.assertTrue(self.state.finish_message(self.conn))
  463. class TestXfrinIXFRAddSOA(TestXfrinState):
  464. def setUp(self):
  465. super().setUp()
  466. self.state = XfrinIXFRAddSOA()
  467. def test_handle_rr(self):
  468. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  469. self.assertEqual(type(XfrinIXFRAdd()), type(self.conn.get_xfrstate()))
  470. self.assertEqual([('add', soa_rrset)],
  471. self.conn._diff.get_buffer())
  472. def test_handle_non_soa(self):
  473. self.assertRaises(XfrinException, self.state.handle_rr, self.conn,
  474. self.ns_rrset)
  475. def test_finish_message(self):
  476. self.assertTrue(self.state.finish_message(self.conn))
  477. class TestXfrinIXFRAdd(TestXfrinState):
  478. def setUp(self):
  479. super().setUp()
  480. # We need record the state in 'conn' to check the case where the
  481. # state doesn't change.
  482. XfrinIXFRAdd().set_xfrstate(self.conn, XfrinIXFRAdd())
  483. self.conn._current_serial = isc.dns.Serial(1230)
  484. self.state = self.conn.get_xfrstate()
  485. def test_handle_add_rr(self):
  486. # Non SOA RRs are simply (goting to be) added in this state
  487. self.assertTrue(self.state.handle_rr(self.conn, self.ns_rrset))
  488. self.assertEqual([('add', self.ns_rrset)],
  489. self.conn._diff.get_buffer())
  490. # The state shouldn't change
  491. self.assertEqual(type(XfrinIXFRAdd()), type(self.conn.get_xfrstate()))
  492. def test_handle_end_soa(self):
  493. self.conn._end_serial = isc.dns.Serial(1234)
  494. self.conn._diff.add_data(self.ns_rrset) # put some dummy change
  495. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  496. self.assertEqual(type(XfrinIXFREnd()), type(self.conn.get_xfrstate()))
  497. # handle_rr should have caused commit, and the buffer should now be
  498. # empty.
  499. self.assertEqual([], self.conn._diff.get_buffer())
  500. def test_handle_new_delete(self):
  501. self.conn._end_serial = isc.dns.Serial(1234)
  502. # SOA RR whose serial is the current one means we are going to a new
  503. # difference, starting with removing that SOA.
  504. self.conn._diff.add_data(self.ns_rrset) # put some dummy change
  505. self.assertFalse(self.state.handle_rr(self.conn, self.begin_soa))
  506. self.assertEqual([], self.conn._diff.get_buffer())
  507. self.assertEqual(type(XfrinIXFRDeleteSOA()),
  508. type(self.conn.get_xfrstate()))
  509. def test_handle_new_delete_missing_sig(self):
  510. self.conn._end_serial = isc.dns.Serial(1234)
  511. # SOA RR whose serial is the current one means we are going to a new
  512. # difference, starting with removing that SOA.
  513. self.conn._diff.add_data(self.ns_rrset) # put some dummy change
  514. self.conn._tsig_ctx = MockTSIGContext(TSIG_KEY)
  515. self.conn._tsig_ctx.last_had_signature = lambda: False
  516. # First, push a starting SOA inside. This should be OK, nothing checked
  517. # yet.
  518. self.state.handle_rr(self.conn, self.begin_soa)
  519. end_soa_rdata = Rdata(RRType.SOA(), TEST_RRCLASS,
  520. 'm. r. 1234 0 0 0 0')
  521. end_soa_rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.SOA(),
  522. RRTTL(3600))
  523. end_soa_rrset.add_rdata(end_soa_rdata)
  524. # This would try to finish up. But the TSIG pretends not everything is
  525. # signed, rejecting it.
  526. self.assertRaises(xfrin.XfrinProtocolError, self.state.handle_rr,
  527. self.conn, end_soa_rrset)
  528. # No diffs were commited
  529. self.assertEqual([], self.conn._datasrc_client.committed_diffs)
  530. def test_handle_out_of_sync(self):
  531. # getting SOA with an inconsistent serial. This is an error.
  532. self.conn._end_serial = isc.dns.Serial(1235)
  533. self.assertRaises(XfrinProtocolError, self.state.handle_rr,
  534. self.conn, soa_rrset)
  535. def test_finish_message(self):
  536. self.assertTrue(self.state.finish_message(self.conn))
  537. class TestXfrinIXFREnd(TestXfrinState):
  538. def setUp(self):
  539. super().setUp()
  540. self.state = XfrinIXFREnd()
  541. def test_handle_rr(self):
  542. self.assertRaises(XfrinProtocolError, self.state.handle_rr, self.conn,
  543. self.ns_rrset)
  544. def test_finish_message(self):
  545. self.assertFalse(self.state.finish_message(self.conn))
  546. class TestXfrinIXFREndUpToDate(TestXfrinState):
  547. def setUp(self):
  548. super().setUp()
  549. self.state = XfrinIXFRUptodate()
  550. def test_handle_rr(self):
  551. self.assertRaises(XfrinProtocolError, self.state.handle_rr, self.conn,
  552. self.ns_rrset)
  553. def test_finish_message(self):
  554. self.assertRaises(XfrinZoneUptodate, self.state.finish_message,
  555. self.conn)
  556. class TestXfrinAXFR(TestXfrinState):
  557. def setUp(self):
  558. super().setUp()
  559. self.state = XfrinAXFR()
  560. self.conn._end_serial = isc.dns.Serial(1234)
  561. def test_handle_rr(self):
  562. """
  563. Test we can put data inside.
  564. """
  565. # Put some data inside
  566. self.assertTrue(self.state.handle_rr(self.conn, self.a_rrset))
  567. # This test uses internal Diff structure to check the behaviour of
  568. # XfrinAXFR. Maybe there could be a cleaner way, but it would be more
  569. # complicated.
  570. self.assertEqual([('add', self.a_rrset)], self.conn._diff.get_buffer())
  571. # This SOA terminates the transfer
  572. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  573. # It should have changed the state
  574. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  575. # At this point, the data haven't been committed yet
  576. self.assertEqual([('add', self.a_rrset), ('add', soa_rrset)],
  577. self.conn._diff.get_buffer())
  578. def test_handle_rr_mismatch_soa(self):
  579. """ SOA with inconsistent serial - unexpected, but we accept it.
  580. """
  581. self.assertTrue(self.state.handle_rr(self.conn, begin_soa_rrset))
  582. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  583. def test_finish_message(self):
  584. """
  585. Check normal end of message.
  586. """
  587. # When a message ends, nothing happens usually
  588. self.assertTrue(self.state.finish_message(self.conn))
  589. class TestXfrinAXFREnd(TestXfrinState):
  590. def setUp(self):
  591. super().setUp()
  592. self.state = XfrinAXFREnd()
  593. def test_handle_rr(self):
  594. self.assertRaises(XfrinProtocolError, self.state.handle_rr, self.conn,
  595. self.ns_rrset)
  596. def test_finish_message(self):
  597. self.conn._diff.add_data(self.a_rrset)
  598. self.conn._diff.add_data(soa_rrset)
  599. self.assertFalse(self.state.finish_message(self.conn))
  600. # The data should have been committed
  601. self.assertEqual([], self.conn._diff.get_buffer())
  602. check_diffs(self.assertEqual, [[('add', self.a_rrset),
  603. ('add', soa_rrset)]],
  604. self.conn._datasrc_client.committed_diffs)
  605. self.assertRaises(ValueError, self.conn._diff.commit)
  606. class TestXfrinConnection(unittest.TestCase):
  607. '''Convenient parent class for XFR-protocol tests.
  608. This class provides common setups and helper methods for protocol related
  609. tests on AXFR and IXFR.
  610. '''
  611. def setUp(self):
  612. if os.path.exists(TEST_DB_FILE):
  613. os.remove(TEST_DB_FILE)
  614. self.sock_map = {}
  615. self.conn = MockXfrinConnection(self.sock_map, TEST_ZONE_NAME,
  616. TEST_RRCLASS, None, threading.Event(),
  617. TEST_MASTER_IPV4_ADDRINFO)
  618. self.conn.init_socket()
  619. self.soa_response_params = {
  620. 'questions': [example_soa_question],
  621. 'bad_qid': False,
  622. 'response': True,
  623. 'auth': True,
  624. 'rcode': Rcode.NOERROR(),
  625. 'answers': default_answers,
  626. 'authorities': [],
  627. 'tsig': False,
  628. 'axfr_after_soa': self._create_normal_response_data
  629. }
  630. self.axfr_response_params = {
  631. 'question_1st': default_questions,
  632. 'question_2nd': default_questions,
  633. 'answer_1st': [soa_rrset, self._create_ns()],
  634. 'answer_2nd': default_answers,
  635. 'tsig_1st': None,
  636. 'tsig_2nd': None
  637. }
  638. self.__orig_check_zone = xfrin.check_zone
  639. xfrin.check_zone = self.__check_zone
  640. self._check_zone_result = True
  641. self._check_zone_params = None
  642. def tearDown(self):
  643. self.conn.close()
  644. if os.path.exists(TEST_DB_FILE):
  645. os.remove(TEST_DB_FILE)
  646. xfrin.check_zone = self.__orig_check_zone
  647. def __check_zone(self, name, rrclass, rrsets, callbacks):
  648. '''
  649. A mock function used instead of dns.check_zone.
  650. '''
  651. self._check_zone_params = (name, rrclass, rrsets, callbacks)
  652. # Call both callbacks to see they do nothing. This checks
  653. # the transfer depends on the result only.
  654. callbacks[0]("Test error")
  655. callbacks[1]("Test warning")
  656. return self._check_zone_result
  657. def _create_normal_response_data(self):
  658. # This helper method creates a simple sequence of DNS messages that
  659. # forms a valid AXFR transaction. It consists of two messages: the
  660. # first one containing SOA, NS, the second containing the trailing SOA.
  661. question_1st = self.axfr_response_params['question_1st']
  662. question_2nd = self.axfr_response_params['question_2nd']
  663. answer_1st = self.axfr_response_params['answer_1st']
  664. answer_2nd = self.axfr_response_params['answer_2nd']
  665. tsig_1st = self.axfr_response_params['tsig_1st']
  666. tsig_2nd = self.axfr_response_params['tsig_2nd']
  667. self.conn.reply_data = self.conn.create_response_data(
  668. questions=question_1st, answers=answer_1st,
  669. tsig_ctx=tsig_1st)
  670. self.conn.reply_data += \
  671. self.conn.create_response_data(questions=question_2nd,
  672. answers=answer_2nd,
  673. tsig_ctx=tsig_2nd)
  674. def _create_soa_response_data(self):
  675. # This helper method creates a DNS message that is supposed to be
  676. # used a valid response to SOA queries prior to XFR.
  677. # If tsig is True, it tries to verify the query with a locally
  678. # created TSIG context (which may or may not succeed) so that the
  679. # response will include a TSIG.
  680. # If axfr_after_soa is True, it resets the response_generator so that
  681. # a valid XFR messages will follow.
  682. verify_ctx = None
  683. if self.soa_response_params['tsig']:
  684. # xfrin (currently) always uses TCP. strip off the length field.
  685. query_data = self.conn.query_data[2:]
  686. query_message = Message(Message.PARSE)
  687. query_message.from_wire(query_data)
  688. verify_ctx = TSIGContext(TSIG_KEY)
  689. verify_ctx.verify(query_message.get_tsig_record(), query_data)
  690. self.conn.reply_data = self.conn.create_response_data(
  691. bad_qid=self.soa_response_params['bad_qid'],
  692. response=self.soa_response_params['response'],
  693. auth=self.soa_response_params['auth'],
  694. rcode=self.soa_response_params['rcode'],
  695. questions=self.soa_response_params['questions'],
  696. answers=self.soa_response_params['answers'],
  697. authorities=self.soa_response_params['authorities'],
  698. tsig_ctx=verify_ctx)
  699. if self.soa_response_params['axfr_after_soa'] != None:
  700. self.conn.response_generator = \
  701. self.soa_response_params['axfr_after_soa']
  702. def _create_broken_response_data(self):
  703. # This helper method creates a bogus "DNS message" that only contains
  704. # 4 octets of data. The DNS message parser will raise an exception.
  705. bogus_data = b'xxxx'
  706. self.conn.reply_data = struct.pack('H', socket.htons(len(bogus_data)))
  707. self.conn.reply_data += bogus_data
  708. def _create_a(self, address):
  709. rrset = RRset(Name('a.example.com'), TEST_RRCLASS, RRType.A(),
  710. RRTTL(3600))
  711. rrset.add_rdata(Rdata(RRType.A(), TEST_RRCLASS, address))
  712. return rrset
  713. def _create_soa(self, serial):
  714. rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.SOA(),
  715. RRTTL(3600))
  716. rdata_str = 'm. r. ' + serial + ' 3600 1800 2419200 7200'
  717. rrset.add_rdata(Rdata(RRType.SOA(), TEST_RRCLASS, rdata_str))
  718. return rrset
  719. def _create_ns(self, nsname='ns.'+TEST_ZONE_NAME_STR):
  720. rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.NS(), RRTTL(3600))
  721. rrset.add_rdata(Rdata(RRType.NS(), TEST_RRCLASS, nsname))
  722. return rrset
  723. def _set_test_zone(self, zone_name):
  724. '''Set the zone name for transfer to the specified one.
  725. It also make sure that the SOA RR (if exist) is correctly (re)set.
  726. '''
  727. self.conn._zone_name = zone_name
  728. self.conn._zone_soa = self.conn._get_zone_soa()
  729. class TestAXFR(TestXfrinConnection):
  730. def setUp(self):
  731. # replace time.time with a steadily increasing fake one
  732. self.orig_time_time = time.time
  733. time.time = get_fake_time_time()
  734. super().setUp()
  735. XfrinInitialSOA().set_xfrstate(self.conn, XfrinInitialSOA())
  736. def tearDown(self):
  737. time.time = self.orig_time_time
  738. super().tearDown()
  739. def __create_mock_tsig(self, key, error, has_last_signature=True):
  740. # This helper function creates a MockTSIGContext for a given key
  741. # and TSIG error to be used as a result of verify (normally faked
  742. # one)
  743. mock_ctx = MockTSIGContext(key)
  744. mock_ctx.error = error
  745. if not has_last_signature:
  746. mock_ctx.last_had_signature = lambda: False
  747. return mock_ctx
  748. def __match_exception(self, expected_exception, expected_msg, expression):
  749. # This helper method is a higher-granularity version of assertRaises().
  750. # If it's not sufficient to check the exception class (e.g., when
  751. # the same type of exceptions can be thrown from many places), this
  752. # method can be used to check it with the exception argument.
  753. try:
  754. expression()
  755. except expected_exception as ex:
  756. self.assertEqual(str(ex), expected_msg)
  757. else:
  758. self.assertFalse('exception is expected, but not raised')
  759. def test_close(self):
  760. # we shouldn't be using the global asyncore map.
  761. self.assertEqual(len(asyncore.socket_map), 0)
  762. # there should be exactly one entry in our local map
  763. self.assertEqual(len(self.sock_map), 1)
  764. # once closing the dispatch the map should become empty
  765. self.conn.close()
  766. self.assertEqual(len(self.sock_map), 0)
  767. def test_init_ip6(self):
  768. # This test simply creates a new XfrinConnection object with an
  769. # IPv6 address, tries to bind it to an IPv6 wildcard address/port
  770. # to confirm an AF_INET6 socket has been created. A naive application
  771. # tends to assume it's IPv4 only and hardcode AF_INET. This test
  772. # uncovers such a bug.
  773. c = MockXfrinConnection({}, TEST_ZONE_NAME, TEST_RRCLASS, None,
  774. threading.Event(), TEST_MASTER_IPV6_ADDRINFO)
  775. c.init_socket()
  776. c.bind(('::', 0))
  777. c.close()
  778. def test_init_chclass(self):
  779. c = MockXfrinConnection({}, TEST_ZONE_NAME, RRClass.CH(), None,
  780. threading.Event(), TEST_MASTER_IPV4_ADDRINFO)
  781. c.init_socket()
  782. axfrmsg = c._create_query(RRType.AXFR())
  783. self.assertEqual(axfrmsg.get_question()[0].get_class(),
  784. RRClass.CH())
  785. c.close()
  786. def test_create_query(self):
  787. def check_query(expected_qtype, expected_auth):
  788. '''Helper method to repeat the same pattern of tests'''
  789. self.assertEqual(Opcode.QUERY(), msg.get_opcode())
  790. self.assertEqual(Rcode.NOERROR(), msg.get_rcode())
  791. self.assertEqual(1, msg.get_rr_count(Message.SECTION_QUESTION))
  792. self.assertEqual(TEST_ZONE_NAME, msg.get_question()[0].get_name())
  793. self.assertEqual(expected_qtype, msg.get_question()[0].get_type())
  794. self.assertEqual(0, msg.get_rr_count(Message.SECTION_ANSWER))
  795. self.assertEqual(0, msg.get_rr_count(Message.SECTION_ADDITIONAL))
  796. if expected_auth is None:
  797. self.assertEqual(0,
  798. msg.get_rr_count(Message.SECTION_AUTHORITY))
  799. else:
  800. self.assertEqual(1,
  801. msg.get_rr_count(Message.SECTION_AUTHORITY))
  802. auth_rr = msg.get_section(Message.SECTION_AUTHORITY)[0]
  803. self.assertEqual(expected_auth.get_name(), auth_rr.get_name())
  804. self.assertEqual(expected_auth.get_type(), auth_rr.get_type())
  805. self.assertEqual(expected_auth.get_class(),
  806. auth_rr.get_class())
  807. # In our test scenario RDATA must be 1
  808. self.assertEqual(1, expected_auth.get_rdata_count())
  809. self.assertEqual(1, auth_rr.get_rdata_count())
  810. self.assertEqual(expected_auth.get_rdata()[0],
  811. auth_rr.get_rdata()[0])
  812. # Actual tests start here
  813. # SOA query
  814. msg = self.conn._create_query(RRType.SOA())
  815. check_query(RRType.SOA(), None)
  816. # AXFR query
  817. msg = self.conn._create_query(RRType.AXFR())
  818. check_query(RRType.AXFR(), None)
  819. # IXFR query
  820. msg = self.conn._create_query(RRType.IXFR())
  821. check_query(RRType.IXFR(), begin_soa_rrset)
  822. self.assertEqual(1230, self.conn._request_serial.get_value())
  823. def test_create_ixfr_query_fail(self):
  824. # In these cases _create_query() will fail to find a valid SOA RR to
  825. # insert in the IXFR query, and should raise an exception.
  826. self._set_test_zone(Name('no-such-zone.example'))
  827. self.assertRaises(XfrinException, self.conn._create_query,
  828. RRType.IXFR())
  829. self._set_test_zone(Name('partial-match-zone.example'))
  830. self.assertRaises(XfrinException, self.conn._create_query,
  831. RRType.IXFR())
  832. self._set_test_zone(Name('no-soa.example'))
  833. self.assertRaises(XfrinException, self.conn._create_query,
  834. RRType.IXFR())
  835. self._set_test_zone(Name('dup-soa.example'))
  836. self.conn._zone_soa = self.conn._get_zone_soa()
  837. self.assertRaises(XfrinException, self.conn._create_query,
  838. RRType.IXFR())
  839. def test_send_query(self):
  840. def message_has_tsig(data):
  841. # a simple check if the actual data contains a TSIG RR.
  842. # At our level this simple check should suffice; other detailed
  843. # tests regarding the TSIG protocol are done in pydnspp.
  844. msg = Message(Message.PARSE)
  845. msg.from_wire(data)
  846. return msg.get_tsig_record() is not None
  847. # soa request with tsig
  848. self.conn._tsig_key = TSIG_KEY
  849. self.conn._send_query(RRType.SOA())
  850. self.assertTrue(message_has_tsig(self.conn.query_data[2:]))
  851. # axfr request with tsig
  852. self.conn._send_query(RRType.AXFR())
  853. self.assertTrue(message_has_tsig(self.conn.query_data[2:]))
  854. def test_response_with_invalid_msg(self):
  855. self.conn.reply_data = b'aaaxxxx'
  856. self.assertRaises(XfrinTestException,
  857. self.conn._handle_xfrin_responses)
  858. def test_response_with_tsigfail(self):
  859. self.conn._tsig_key = TSIG_KEY
  860. # server tsig check fail, return with RCODE 9 (NOTAUTH)
  861. self.conn._send_query(RRType.SOA())
  862. self.conn.reply_data = \
  863. self.conn.create_response_data(rcode=Rcode.NOTAUTH())
  864. self.assertRaises(XfrinProtocolError,
  865. self.conn._handle_xfrin_responses)
  866. def test_response_without_end_soa(self):
  867. self.conn._send_query(RRType.AXFR())
  868. self.conn.reply_data = self.conn.create_response_data()
  869. # This should result in timeout in the asyncore loop. We emulate
  870. # that situation in recv() by emptying the reply data buffer.
  871. self.assertRaises(XfrinTestTimeoutException,
  872. self.conn._handle_xfrin_responses)
  873. def test_response_bad_qid(self):
  874. self.conn._send_query(RRType.AXFR())
  875. self.conn.reply_data = self.conn.create_response_data(bad_qid=True)
  876. self.assertRaises(XfrinProtocolError,
  877. self.conn._handle_xfrin_responses)
  878. def test_response_error_code_bad_sig(self):
  879. self.conn._tsig_key = TSIG_KEY
  880. self.conn._tsig_ctx_creator = \
  881. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_SIG)
  882. self.conn._send_query(RRType.AXFR())
  883. self.conn.reply_data = self.conn.create_response_data(
  884. rcode=Rcode.SERVFAIL())
  885. # xfrin should check TSIG before other part of incoming message
  886. # validate log message for XfrinException
  887. self.__match_exception(XfrinProtocolError,
  888. "TSIG verify fail: BADSIG",
  889. self.conn._handle_xfrin_responses)
  890. def test_response_bad_qid_bad_key(self):
  891. self.conn._tsig_key = TSIG_KEY
  892. self.conn._tsig_ctx_creator = \
  893. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_KEY)
  894. self.conn._send_query(RRType.AXFR())
  895. self.conn.reply_data = self.conn.create_response_data(bad_qid=True)
  896. # xfrin should check TSIG before other part of incoming message
  897. # validate log message for XfrinException
  898. self.__match_exception(XfrinProtocolError,
  899. "TSIG verify fail: BADKEY",
  900. self.conn._handle_xfrin_responses)
  901. def test_response_non_response(self):
  902. self.conn._send_query(RRType.AXFR())
  903. self.conn.reply_data = self.conn.create_response_data(response=False)
  904. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  905. def test_response_error_code(self):
  906. self.conn._send_query(RRType.AXFR())
  907. self.conn.reply_data = self.conn.create_response_data(
  908. rcode=Rcode.SERVFAIL())
  909. self.assertRaises(XfrinProtocolError,
  910. self.conn._handle_xfrin_responses)
  911. def test_response_multi_question(self):
  912. self.conn._send_query(RRType.AXFR())
  913. self.conn.reply_data = self.conn.create_response_data(
  914. questions=[example_axfr_question, example_axfr_question])
  915. self.assertRaises(XfrinProtocolError,
  916. self.conn._handle_xfrin_responses)
  917. def test_response_non_response(self):
  918. self.conn._send_query(RRType.AXFR())
  919. self.conn.reply_data = self.conn.create_response_data(response = False)
  920. self.assertRaises(XfrinProtocolError,
  921. self.conn._handle_xfrin_responses)
  922. def test_soacheck(self):
  923. # we need to defer the creation until we know the QID, which is
  924. # determined in _check_soa_serial(), so we use response_generator.
  925. self.conn.response_generator = self._create_soa_response_data
  926. self.assertEqual(self.conn._check_soa_serial(), XFRIN_OK)
  927. def test_soacheck_with_bad_response(self):
  928. self.conn.response_generator = self._create_broken_response_data
  929. self.assertRaises(MessageTooShort, self.conn._check_soa_serial)
  930. def test_soacheck_badqid(self):
  931. self.soa_response_params['bad_qid'] = True
  932. self.conn.response_generator = self._create_soa_response_data
  933. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  934. def test_soacheck_bad_qid_bad_sig(self):
  935. self.conn._tsig_key = TSIG_KEY
  936. self.conn._tsig_ctx_creator = \
  937. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_SIG)
  938. self.soa_response_params['bad_qid'] = True
  939. self.conn.response_generator = self._create_soa_response_data
  940. # xfrin should check TSIG before other part of incoming message
  941. # validate log message for XfrinException
  942. self.__match_exception(XfrinProtocolError,
  943. "TSIG verify fail: BADSIG",
  944. self.conn._check_soa_serial)
  945. def test_soacheck_non_response(self):
  946. self.soa_response_params['response'] = False
  947. self.conn.response_generator = self._create_soa_response_data
  948. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  949. def test_soacheck_error_code(self):
  950. self.soa_response_params['rcode'] = Rcode.SERVFAIL()
  951. self.conn.response_generator = self._create_soa_response_data
  952. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  953. def test_soacheck_notauth(self):
  954. self.soa_response_params['auth'] = False
  955. self.conn.response_generator = self._create_soa_response_data
  956. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  957. def test_soacheck_uptodate(self):
  958. # Primary's SOA serial is identical the local serial
  959. self.soa_response_params['answers'] = [begin_soa_rrset]
  960. self.conn.response_generator = self._create_soa_response_data
  961. self.assertRaises(XfrinZoneUptodate, self.conn._check_soa_serial)
  962. def test_soacheck_uptodate2(self):
  963. # Primary's SOA serial is "smaller" than the local serial
  964. self.soa_response_params['answers'] = [create_soa(1229)]
  965. self.conn.response_generator = self._create_soa_response_data
  966. self.assertRaises(XfrinZoneUptodate, self.conn._check_soa_serial)
  967. def test_soacheck_uptodate3(self):
  968. # Similar to the previous case, but checking the comparison is based
  969. # on the serial number arithmetic.
  970. self.soa_response_params['answers'] = [create_soa(0xffffffff)]
  971. self.conn.response_generator = self._create_soa_response_data
  972. self.assertRaises(XfrinZoneUptodate, self.conn._check_soa_serial)
  973. def test_soacheck_newzone(self):
  974. # Primary's SOA is 'old', but this secondary doesn't know anything
  975. # about the zone yet, so it should accept it.
  976. def response_generator():
  977. # _request_serial is set in _check_soa_serial(). Reset it here.
  978. self.conn._request_serial = None
  979. self._create_soa_response_data()
  980. self.soa_response_params['answers'] = [begin_soa_rrset]
  981. self.conn.response_generator = response_generator
  982. self.assertEqual(XFRIN_OK, self.conn._check_soa_serial())
  983. def test_soacheck_question_empty(self):
  984. self.conn.response_generator = self._create_soa_response_data
  985. self.soa_response_params['questions'] = []
  986. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  987. def test_soacheck_question_name_mismatch(self):
  988. self.conn.response_generator = self._create_soa_response_data
  989. self.soa_response_params['questions'] = [Question(Name('example.org'),
  990. TEST_RRCLASS,
  991. RRType.SOA())]
  992. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  993. def test_soacheck_question_class_mismatch(self):
  994. self.conn.response_generator = self._create_soa_response_data
  995. self.soa_response_params['questions'] = [Question(TEST_ZONE_NAME,
  996. RRClass.CH(),
  997. RRType.SOA())]
  998. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  999. def test_soacheck_question_type_mismatch(self):
  1000. self.conn.response_generator = self._create_soa_response_data
  1001. self.soa_response_params['questions'] = [Question(TEST_ZONE_NAME,
  1002. TEST_RRCLASS,
  1003. RRType.AAAA())]
  1004. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1005. def test_soacheck_no_soa(self):
  1006. # The response just doesn't contain SOA without any other indication
  1007. # of errors.
  1008. self.conn.response_generator = self._create_soa_response_data
  1009. self.soa_response_params['answers'] = []
  1010. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1011. def test_soacheck_soa_name_mismatch(self):
  1012. self.conn.response_generator = self._create_soa_response_data
  1013. self.soa_response_params['answers'] = [create_soa(1234,
  1014. Name('example.org'))]
  1015. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1016. def test_soacheck_soa_class_mismatch(self):
  1017. self.conn.response_generator = self._create_soa_response_data
  1018. soa = RRset(TEST_ZONE_NAME, RRClass.CH(), RRType.SOA(), RRTTL(0))
  1019. soa.add_rdata(Rdata(RRType.SOA(), RRClass.CH(), 'm. r. 1234 0 0 0 0'))
  1020. self.soa_response_params['answers'] = [soa]
  1021. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1022. def test_soacheck_multiple_soa(self):
  1023. self.conn.response_generator = self._create_soa_response_data
  1024. self.soa_response_params['answers'] = [soa_rrset, soa_rrset]
  1025. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1026. def test_soacheck_cname_response(self):
  1027. self.conn.response_generator = self._create_soa_response_data
  1028. # Add SOA to answer, too, to make sure that it that deceives the parser
  1029. self.soa_response_params['answers'] = [soa_rrset, create_cname()]
  1030. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1031. def test_soacheck_referral_response(self):
  1032. self.conn.response_generator = self._create_soa_response_data
  1033. self.soa_response_params['answers'] = []
  1034. self.soa_response_params['authorities'] = [create_ns('ns.example.com.')]
  1035. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1036. def test_soacheck_nodata_response(self):
  1037. self.conn.response_generator = self._create_soa_response_data
  1038. self.soa_response_params['answers'] = []
  1039. self.soa_response_params['authorities'] = [soa_rrset]
  1040. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1041. def test_soacheck_with_tsig(self):
  1042. # Use a mock tsig context emulating a validly signed response
  1043. self.conn._tsig_key = TSIG_KEY
  1044. self.conn._tsig_ctx_creator = \
  1045. lambda key: self.__create_mock_tsig(key, TSIGError.NOERROR)
  1046. self.conn.response_generator = self._create_soa_response_data
  1047. self.assertEqual(self.conn._check_soa_serial(), XFRIN_OK)
  1048. self.assertEqual(self.conn._tsig_ctx.get_error(), TSIGError.NOERROR)
  1049. def test_soacheck_with_tsig_notauth(self):
  1050. # emulate a valid error response
  1051. self.conn._tsig_key = TSIG_KEY
  1052. self.conn._tsig_ctx_creator = \
  1053. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_SIG)
  1054. self.soa_response_params['rcode'] = Rcode.NOTAUTH()
  1055. self.conn.response_generator = self._create_soa_response_data
  1056. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1057. def test_soacheck_with_tsig_noerror_badsig(self):
  1058. self.conn._tsig_key = TSIG_KEY
  1059. self.conn._tsig_ctx_creator = \
  1060. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_SIG)
  1061. # emulate a normal response bad verification failure due to BADSIG.
  1062. # According RFC2845, in this case we should ignore it and keep
  1063. # waiting for a valid response until a timeout. But we immediately
  1064. # treat this as a final failure (just as BIND 9 does).
  1065. self.conn.response_generator = self._create_soa_response_data
  1066. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1067. def test_soacheck_with_tsig_unsigned_response(self):
  1068. # we can use a real TSIGContext for this. the response doesn't
  1069. # contain a TSIG while we sent a signed query. RFC2845 states
  1070. # we should wait for a valid response in this case, but we treat
  1071. # it as a fatal transaction failure, too.
  1072. self.conn._tsig_key = TSIG_KEY
  1073. self.conn.response_generator = self._create_soa_response_data
  1074. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1075. def test_soacheck_with_unexpected_tsig_response(self):
  1076. # we reject unexpected TSIG in responses (following BIND 9's
  1077. # behavior)
  1078. self.soa_response_params['tsig'] = True
  1079. self.conn.response_generator = self._create_soa_response_data
  1080. self.assertRaises(XfrinProtocolError, self.conn._check_soa_serial)
  1081. def test_response_shutdown(self):
  1082. self.conn.response_generator = self._create_normal_response_data
  1083. self.conn._shutdown_event.set()
  1084. self.conn._send_query(RRType.AXFR())
  1085. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  1086. def test_response_timeout(self):
  1087. self.conn.response_generator = self._create_normal_response_data
  1088. self.conn.force_time_out = True
  1089. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  1090. def test_response_remote_close(self):
  1091. self.conn.response_generator = self._create_normal_response_data
  1092. self.conn.force_close = True
  1093. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  1094. def test_response_bad_message(self):
  1095. self.conn.response_generator = self._create_broken_response_data
  1096. self.conn._send_query(RRType.AXFR())
  1097. self.assertRaises(Exception, self.conn._handle_xfrin_responses)
  1098. def test_axfr_response(self):
  1099. # A simple normal case: AXFR consists of SOA, NS, then trailing SOA.
  1100. self.conn.response_generator = self._create_normal_response_data
  1101. self.conn._send_query(RRType.AXFR())
  1102. self.conn._handle_xfrin_responses()
  1103. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1104. check_diffs(self.assertEqual,
  1105. [[('add', self._create_ns()), ('add', soa_rrset)]],
  1106. self.conn._datasrc_client.committed_diffs)
  1107. def test_response_empty_answer(self):
  1108. '''Test with an empty AXFR answer section.
  1109. This is an unusual response, but there is no reason to reject it.
  1110. The second message is a complete AXFR response, and transfer should
  1111. succeed just like the normal case.
  1112. '''
  1113. self.axfr_response_params['answer_1st'] = []
  1114. self.axfr_response_params['answer_2nd'] = [soa_rrset,
  1115. self._create_ns(),
  1116. soa_rrset]
  1117. self.conn.response_generator = self._create_normal_response_data
  1118. self.conn._send_query(RRType.AXFR())
  1119. self.conn._handle_xfrin_responses()
  1120. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1121. check_diffs(self.assertEqual,
  1122. [[('add', self._create_ns()), ('add', soa_rrset)]],
  1123. self.conn._datasrc_client.committed_diffs)
  1124. def test_axfr_response_soa_mismatch(self):
  1125. '''AXFR response whose begin/end SOAs are not same.
  1126. What should we do this is moot, for now we accept it, so does BIND 9.
  1127. '''
  1128. ns_rr = self._create_ns()
  1129. a_rr = self._create_a('192.0.2.1')
  1130. self.conn._send_query(RRType.AXFR())
  1131. self.conn.reply_data = self.conn.create_response_data(
  1132. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1133. RRType.AXFR())],
  1134. # begin serial=1230, end serial=1234. end will be used.
  1135. answers=[begin_soa_rrset, ns_rr, a_rr, soa_rrset])
  1136. self.conn._handle_xfrin_responses()
  1137. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1138. check_diffs(self.assertEqual,
  1139. [[('add', ns_rr), ('add', a_rr), ('add', soa_rrset)]],
  1140. self.conn._datasrc_client.committed_diffs)
  1141. def test_axfr_response_fail_validation(self):
  1142. """
  1143. Test we reject a zone transfer if it fails the check_zone validation.
  1144. """
  1145. a_rr = self._create_a('192.0.2.1')
  1146. self.conn._send_query(RRType.AXFR())
  1147. self.conn.reply_data = self.conn.create_response_data(
  1148. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1149. RRType.AXFR())],
  1150. # begin serial=1230, end serial=1234. end will be used.
  1151. answers=[begin_soa_rrset, a_rr, soa_rrset])
  1152. # Make it fail the validation
  1153. self._check_zone_result = False
  1154. self.assertRaises(XfrinZoneError, self.conn._handle_xfrin_responses)
  1155. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1156. self.assertEqual([], self.conn._datasrc_client.committed_diffs)
  1157. # Check the validation is called with the correct parameters
  1158. self.assertEqual(TEST_ZONE_NAME, self._check_zone_params[0])
  1159. self.assertEqual(TEST_RRCLASS, self._check_zone_params[1])
  1160. self.assertTrue(isinstance(self._check_zone_params[2],
  1161. MockRRsetCollection))
  1162. # Check we can safely call the callbacks. They have no sideeffects
  1163. # we can check (checking logging is hard), but we at least check
  1164. # they don't crash.
  1165. self._check_zone_params[3][0]("Test error")
  1166. self._check_zone_params[3][1]("Test warning")
  1167. def test_axfr_response_extra(self):
  1168. '''Test with an extra RR after the end of AXFR session.
  1169. The session should be rejected, and nothing should be committed.
  1170. '''
  1171. ns_rr = self._create_ns()
  1172. a_rr = self._create_a('192.0.2.1')
  1173. self.conn._send_query(RRType.AXFR())
  1174. self.conn.reply_data = self.conn.create_response_data(
  1175. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1176. RRType.AXFR())],
  1177. answers=[soa_rrset, ns_rr, a_rr, soa_rrset, a_rr])
  1178. self.assertRaises(XfrinProtocolError,
  1179. self.conn._handle_xfrin_responses)
  1180. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1181. self.assertEqual([], self.conn._datasrc_client.committed_diffs)
  1182. def test_axfr_response_qname_mismatch(self):
  1183. '''AXFR response with a mismatch question name.
  1184. Our implementation accepts that, so does BIND 9.
  1185. '''
  1186. self.axfr_response_params['question_1st'] = \
  1187. [Question(Name('mismatch.example'), TEST_RRCLASS, RRType.AXFR())]
  1188. self.conn.response_generator = self._create_normal_response_data
  1189. self.conn._send_query(RRType.AXFR())
  1190. self.conn._handle_xfrin_responses()
  1191. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1192. check_diffs(self.assertEqual,
  1193. [[('add', self._create_ns()), ('add', soa_rrset)]],
  1194. self.conn._datasrc_client.committed_diffs)
  1195. def test_axfr_response_qclass_mismatch(self):
  1196. '''AXFR response with a mismatch RR class.
  1197. Our implementation accepts that, so does BIND 9.
  1198. '''
  1199. self.axfr_response_params['question_1st'] = \
  1200. [Question(TEST_ZONE_NAME, RRClass.CH(), RRType.AXFR())]
  1201. self.conn.response_generator = self._create_normal_response_data
  1202. self.conn._send_query(RRType.AXFR())
  1203. self.conn._handle_xfrin_responses()
  1204. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1205. check_diffs(self.assertEqual,
  1206. [[('add', self._create_ns()), ('add', soa_rrset)]],
  1207. self.conn._datasrc_client.committed_diffs)
  1208. def test_axfr_response_qtype_mismatch(self):
  1209. '''AXFR response with a mismatch RR type.
  1210. Our implementation accepts that, so does BIND 9.
  1211. '''
  1212. # returning IXFR in question to AXFR query
  1213. self.axfr_response_params['question_1st'] = \
  1214. [Question(TEST_ZONE_NAME, RRClass.CH(), RRType.IXFR())]
  1215. self.conn.response_generator = self._create_normal_response_data
  1216. self.conn._send_query(RRType.AXFR())
  1217. self.conn._handle_xfrin_responses()
  1218. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1219. check_diffs(self.assertEqual,
  1220. [[('add', self._create_ns()), ('add', soa_rrset)]],
  1221. self.conn._datasrc_client.committed_diffs)
  1222. def test_axfr_response_empty_question(self):
  1223. '''AXFR response with an empty question.
  1224. Our implementation accepts that, so does BIND 9.
  1225. '''
  1226. self.axfr_response_params['question_1st'] = []
  1227. self.conn.response_generator = self._create_normal_response_data
  1228. self.conn._send_query(RRType.AXFR())
  1229. self.conn._handle_xfrin_responses()
  1230. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1231. check_diffs(self.assertEqual,
  1232. [[('add', self._create_ns()), ('add', soa_rrset)]],
  1233. self.conn._datasrc_client.committed_diffs)
  1234. def test_do_xfrin(self):
  1235. self.conn.response_generator = self._create_normal_response_data
  1236. self.assertEqual(self.conn.do_xfrin(False), XFRIN_OK)
  1237. self.assertFalse(self.conn._datasrc_client._journaling_enabled)
  1238. self.assertEqual(2, self.conn._transfer_stats.message_count)
  1239. self.assertEqual(2, self.conn._transfer_stats.axfr_rr_count)
  1240. self.assertEqual(0, self.conn._transfer_stats.ixfr_changeset_count)
  1241. self.assertEqual(0, self.conn._transfer_stats.ixfr_deletion_count)
  1242. self.assertEqual(0, self.conn._transfer_stats.ixfr_addition_count)
  1243. self.assertEqual(177, self.conn._transfer_stats.byte_count)
  1244. self.assertGreater(self.conn._transfer_stats.get_running_time(), 0)
  1245. def test_do_xfrin_with_tsig(self):
  1246. # use TSIG with a mock context. we fake all verify results to
  1247. # emulate successful verification.
  1248. self.conn._tsig_key = TSIG_KEY
  1249. self.conn._tsig_ctx_creator = \
  1250. lambda key: self.__create_mock_tsig(key, TSIGError.NOERROR)
  1251. self.conn.response_generator = self._create_normal_response_data
  1252. self.assertEqual(self.conn.do_xfrin(False), XFRIN_OK)
  1253. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1254. check_diffs(self.assertEqual,
  1255. [[('add', self._create_ns()), ('add', soa_rrset)]],
  1256. self.conn._datasrc_client.committed_diffs)
  1257. def test_do_xfrin_with_tsig_fail(self):
  1258. # TSIG verify will fail for the first message. xfrin should fail
  1259. # immediately.
  1260. self.conn._tsig_key = TSIG_KEY
  1261. self.conn._tsig_ctx_creator = \
  1262. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_SIG)
  1263. self.conn.response_generator = self._create_normal_response_data
  1264. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1265. self.assertEqual(1, self.conn._tsig_ctx.verify_called)
  1266. def test_do_xfrin_without_last_tsig(self):
  1267. # TSIG verify will succeed, but it will pretend the last message is
  1268. # not signed.
  1269. self.conn._tsig_key = TSIG_KEY
  1270. self.conn._tsig_ctx_creator = \
  1271. lambda key: self.__create_mock_tsig(key, TSIGError.NOERROR, False)
  1272. self.conn.response_generator = self._create_normal_response_data
  1273. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1274. self.assertEqual(2, self.conn._tsig_ctx.verify_called)
  1275. def test_do_xfrin_with_tsig_fail_for_second_message(self):
  1276. # Similar to the previous test, but first verify succeeds. There
  1277. # should be a second verify attempt, which will fail, which should
  1278. # make xfrin fail.
  1279. def fake_tsig_error(ctx):
  1280. if self.conn._tsig_ctx.verify_called == 1:
  1281. return TSIGError.NOERROR
  1282. return TSIGError.BAD_SIG
  1283. self.conn._tsig_key = TSIG_KEY
  1284. self.conn._tsig_ctx_creator = \
  1285. lambda key: self.__create_mock_tsig(key, fake_tsig_error)
  1286. self.conn.response_generator = self._create_normal_response_data
  1287. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1288. self.assertEqual(2, self.conn._tsig_ctx.verify_called)
  1289. def test_do_xfrin_with_missing_tsig(self):
  1290. # XFR request sent with TSIG, but the response doesn't have TSIG.
  1291. # xfr should fail.
  1292. self.conn._tsig_key = TSIG_KEY
  1293. self.conn._tsig_ctx_creator = \
  1294. lambda key: self.__create_mock_tsig(key, None)
  1295. self.conn._tsig_ctx = MockTSIGContext(TSIG_KEY)
  1296. self.conn.response_generator = self._create_normal_response_data
  1297. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1298. self.assertEqual(1, self.conn._tsig_ctx.verify_called)
  1299. def test_do_xfrin_with_missing_tsig_for_second_message(self):
  1300. # Similar to the previous test, but firt one contains TSIG and verify
  1301. # succeeds (due to fake). The second message lacks TSIG.
  1302. #
  1303. # Note: this test case is actually not that trivial: Skipping
  1304. # intermediate TSIG is allowed. In this case, however, the second
  1305. # message is the last one, which must contain TSIG anyway, so the
  1306. # expected result is correct. If/when we support skipping
  1307. # intermediate TSIGs, we'll need additional test cases.
  1308. def fake_tsig_error(ctx):
  1309. if self.conn._tsig_ctx.verify_called == 1:
  1310. return TSIGError.NOERROR
  1311. return TSIGError.FORMERR
  1312. self.conn._tsig_key = TSIG_KEY
  1313. self.conn._tsig_ctx_creator = \
  1314. lambda key: self.__create_mock_tsig(key, fake_tsig_error)
  1315. self.conn.response_generator = self._create_normal_response_data
  1316. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1317. self.assertEqual(2, self.conn._tsig_ctx.verify_called)
  1318. def test_do_xfrin_with_unexpected_tsig(self):
  1319. # XFR request wasn't signed, but response includes TSIG. Like BIND 9,
  1320. # we reject that.
  1321. self.axfr_response_params['tsig_1st'] = TSIGContext(TSIG_KEY)
  1322. self.conn.response_generator = self._create_normal_response_data
  1323. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1324. def test_do_xfrin_with_unexpected_tsig_for_second_message(self):
  1325. # similar to the previous test, but the first message is normal.
  1326. # the second one contains an unexpected TSIG. should be rejected.
  1327. self.axfr_response_params['tsig_2nd'] = TSIGContext(TSIG_KEY)
  1328. self.conn.response_generator = self._create_normal_response_data
  1329. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1330. def test_do_xfrin_empty_response(self):
  1331. # skipping the creation of response data, so the transfer will fail.
  1332. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1333. def test_do_xfrin_bad_response(self):
  1334. self.conn.response_generator = self._create_broken_response_data
  1335. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1336. def test_do_xfrin_datasrc_error(self):
  1337. # Emulate failure in the data source client on commit.
  1338. self.conn._datasrc_client.force_fail = True
  1339. self.conn.response_generator = self._create_normal_response_data
  1340. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1341. def test_do_xfrin_invalid_zone(self):
  1342. """
  1343. Test receiving an invalid zone. We mock the check and see the whole
  1344. transfer is rejected.
  1345. """
  1346. self._check_zone_result = False
  1347. self.conn.response_generator = self._create_normal_response_data
  1348. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1349. def test_do_soacheck_and_xfrin(self):
  1350. self.conn.response_generator = self._create_soa_response_data
  1351. self.assertEqual(self.conn.do_xfrin(True), XFRIN_OK)
  1352. def test_do_soacheck_uptodate(self):
  1353. self.soa_response_params['answers'] = [begin_soa_rrset]
  1354. self.conn.response_generator = self._create_soa_response_data
  1355. self.assertEqual(self.conn.do_xfrin(True), XFRIN_OK)
  1356. def test_do_soacheck_protocol_error(self):
  1357. # There are several cases, but at this level it's sufficient to check
  1358. # only one. We use the case where there's no SOA in the response.
  1359. self.soa_response_params['answers'] = []
  1360. self.conn.response_generator = self._create_soa_response_data
  1361. self.assertEqual(self.conn.do_xfrin(True), XFRIN_FAIL)
  1362. def test_do_soacheck_and_xfrin_with_tsig(self):
  1363. # We are going to have a SOA query/response transaction, followed by
  1364. # AXFR, all TSIG signed. xfrin should use a new TSIG context for
  1365. # AXFR. We are not interested in whether verify works correctly in
  1366. # this test, so we simply fake the results (they need to succeed for
  1367. # this test)
  1368. self.conn._tsig_key = TSIG_KEY
  1369. self.conn._tsig_ctx_creator = \
  1370. lambda key: self.__create_mock_tsig(key, TSIGError.NOERROR)
  1371. self.soa_response_params['tsig'] = True
  1372. self.conn.response_generator = self._create_soa_response_data
  1373. self.assertEqual(self.conn.do_xfrin(True), XFRIN_OK)
  1374. # We should've got 3 response messages: 1 SOA and two AXFR, but
  1375. # the context should be replaced for AXFR, so verify() should be
  1376. # called only twice for the latest context.
  1377. self.assertEqual(2, self.conn._tsig_ctx.verify_called)
  1378. def test_do_soacheck_broken_response(self):
  1379. self.conn.response_generator = self._create_broken_response_data
  1380. self.assertEqual(self.conn.do_xfrin(True), XFRIN_FAIL)
  1381. def test_do_soacheck_badqid(self):
  1382. # the QID mismatch would internally trigger a XfrinException exception,
  1383. # and covers part of the code that other tests can't.
  1384. self.soa_response_params['bad_qid'] = True
  1385. self.conn.response_generator = self._create_soa_response_data
  1386. self.assertEqual(self.conn.do_xfrin(True), XFRIN_FAIL)
  1387. class TestIXFRResponse(TestXfrinConnection):
  1388. def setUp(self):
  1389. # replace time.time with a steadily increasing fake one
  1390. self.orig_time_time = time.time
  1391. time.time = get_fake_time_time()
  1392. super().setUp()
  1393. self.conn._query_id = self.conn.qid = 1035
  1394. self.conn._request_serial = isc.dns.Serial(1230)
  1395. self.conn._request_type = RRType.IXFR()
  1396. self.conn._datasrc_client = MockDataSourceClient()
  1397. XfrinInitialSOA().set_xfrstate(self.conn, XfrinInitialSOA())
  1398. def tearDown(self):
  1399. time.time = self.orig_time_time
  1400. def test_ixfr_response(self):
  1401. '''A simplest form of IXFR response.
  1402. It simply updates the zone's SOA one time.
  1403. '''
  1404. self.conn.reply_data = self.conn.create_response_data(
  1405. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1406. answers=[soa_rrset, begin_soa_rrset, soa_rrset, soa_rrset])
  1407. self.conn._handle_xfrin_responses()
  1408. self.assertEqual(type(XfrinIXFREnd()), type(self.conn.get_xfrstate()))
  1409. self.assertTrue(self.conn._datasrc_client._journaling_enabled)
  1410. self.assertEqual([], self.conn._datasrc_client.diffs)
  1411. check_diffs(self.assertEqual,
  1412. [[('delete', begin_soa_rrset), ('add', soa_rrset)]],
  1413. self.conn._datasrc_client.committed_diffs)
  1414. def test_ixfr_response_fail_validation(self):
  1415. '''
  1416. An IXFR that fails validation later on. Check it is rejected.
  1417. '''
  1418. self.conn.reply_data = self.conn.create_response_data(
  1419. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1420. answers=[soa_rrset, begin_soa_rrset, soa_rrset, soa_rrset])
  1421. self._check_zone_result = False
  1422. self.assertRaises(XfrinZoneError, self.conn._handle_xfrin_responses)
  1423. self.assertEqual([], self.conn._datasrc_client.committed_diffs)
  1424. self.assertEqual(TEST_ZONE_NAME, self._check_zone_params[0])
  1425. self.assertEqual(TEST_RRCLASS, self._check_zone_params[1])
  1426. self.assertTrue(isinstance(self._check_zone_params[2],
  1427. MockRRsetCollection))
  1428. # Check we can safely call the callbacks. They have no sideeffects
  1429. # we can check (checking logging is hard), but we at least check
  1430. # they don't crash.
  1431. self._check_zone_params[3][0]("Test error")
  1432. self._check_zone_params[3][1]("Test warning")
  1433. def test_ixfr_response_multi_sequences(self):
  1434. '''Similar to the previous case, but with multiple diff seqs.
  1435. '''
  1436. self.conn.reply_data = self.conn.create_response_data(
  1437. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1438. answers=[soa_rrset,
  1439. # removing one A in serial 1230
  1440. begin_soa_rrset, self._create_a('192.0.2.1'),
  1441. # adding one A in serial 1231
  1442. self._create_soa('1231'), self._create_a('192.0.2.2'),
  1443. # removing one A in serial 1231
  1444. self._create_soa('1231'), self._create_a('192.0.2.3'),
  1445. # adding one A in serial 1232
  1446. self._create_soa('1232'), self._create_a('192.0.2.4'),
  1447. # removing one A in serial 1232
  1448. self._create_soa('1232'), self._create_a('192.0.2.5'),
  1449. # adding one A in serial 1234
  1450. soa_rrset, self._create_a('192.0.2.6'),
  1451. soa_rrset])
  1452. self.conn._handle_xfrin_responses()
  1453. self.assertEqual(type(XfrinIXFREnd()), type(self.conn.get_xfrstate()))
  1454. self.assertEqual([], self.conn._datasrc_client.diffs)
  1455. # Everything is committed as one bunch, currently we commit at the very
  1456. # end.
  1457. check_diffs(self.assertEqual,
  1458. [[('delete', begin_soa_rrset),
  1459. ('delete', self._create_a('192.0.2.1')),
  1460. ('add', self._create_soa('1231')),
  1461. ('add', self._create_a('192.0.2.2')),
  1462. ('delete', self._create_soa('1231')),
  1463. ('delete', self._create_a('192.0.2.3')),
  1464. ('add', self._create_soa('1232')),
  1465. ('add', self._create_a('192.0.2.4')),
  1466. ('delete', self._create_soa('1232')),
  1467. ('delete', self._create_a('192.0.2.5')),
  1468. ('add', soa_rrset),
  1469. ('add', self._create_a('192.0.2.6'))]],
  1470. self.conn._datasrc_client.committed_diffs)
  1471. def test_ixfr_response_multi_messages(self):
  1472. '''Similar to the first case, but RRs span over multiple messages.
  1473. '''
  1474. self.conn.reply_data = self.conn.create_response_data(
  1475. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1476. answers=[soa_rrset, begin_soa_rrset, soa_rrset])
  1477. self.conn.reply_data += self.conn.create_response_data(
  1478. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1479. answers=[soa_rrset])
  1480. self.conn._handle_xfrin_responses()
  1481. self.assertEqual(type(XfrinIXFREnd()), type(self.conn.get_xfrstate()))
  1482. check_diffs(self.assertEqual,
  1483. [[('delete', begin_soa_rrset), ('add', soa_rrset)]],
  1484. self.conn._datasrc_client.committed_diffs)
  1485. def test_ixfr_response_uptodate(self):
  1486. '''IXFR response indicates the zone is new enough'''
  1487. self.conn.reply_data = self.conn.create_response_data(
  1488. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1489. answers=[begin_soa_rrset])
  1490. self.assertRaises(XfrinZoneUptodate, self.conn._handle_xfrin_responses)
  1491. # no diffs should have been committed
  1492. check_diffs(self.assertEqual,
  1493. [], self.conn._datasrc_client.committed_diffs)
  1494. def test_ixfr_response_broken(self):
  1495. '''Test with a broken response.
  1496. '''
  1497. # SOA sequence is out-of-sync
  1498. self.conn.reply_data = self.conn.create_response_data(
  1499. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1500. answers=[soa_rrset, begin_soa_rrset, soa_rrset,
  1501. self._create_soa('1235')])
  1502. self.assertRaises(XfrinProtocolError,
  1503. self.conn._handle_xfrin_responses)
  1504. # no diffs should have been committed
  1505. check_diffs(self.assertEqual,
  1506. [], self.conn._datasrc_client.committed_diffs)
  1507. def test_ixfr_response_extra(self):
  1508. '''Test with an extra RR after the end of IXFR diff sequences.
  1509. IXFR should be rejected, but complete diff sequences should be
  1510. committed; it's not clear whether it's compliant to the protocol
  1511. specification, but it is how BIND 9 works and we do the same.
  1512. '''
  1513. self.conn.reply_data = self.conn.create_response_data(
  1514. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1515. answers=[soa_rrset, begin_soa_rrset, soa_rrset, soa_rrset,
  1516. self._create_a('192.0.2.1')])
  1517. self.assertRaises(XfrinProtocolError,
  1518. self.conn._handle_xfrin_responses)
  1519. check_diffs(self.assertEqual,
  1520. [[('delete', begin_soa_rrset), ('add', soa_rrset)]],
  1521. self.conn._datasrc_client.committed_diffs)
  1522. def test_ixfr_response_uptodate_extra(self):
  1523. '''Similar to 'uptodate' test, but with extra bogus data.
  1524. In either case an exception will be raised, but in this case it's
  1525. considered an error.
  1526. '''
  1527. self.conn.reply_data = self.conn.create_response_data(
  1528. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1529. answers=[begin_soa_rrset, soa_rrset])
  1530. self.assertRaises(XfrinProtocolError,
  1531. self.conn._handle_xfrin_responses)
  1532. # no diffs should have been committed
  1533. check_diffs(self.assertEqual,
  1534. [], self.conn._datasrc_client.committed_diffs)
  1535. def test_ixfr_to_axfr_response(self):
  1536. '''AXFR-style IXFR response.
  1537. It simply updates the zone's SOA one time.
  1538. '''
  1539. ns_rr = self._create_ns()
  1540. a_rr = self._create_a('192.0.2.1')
  1541. self.conn.reply_data = self.conn.create_response_data(
  1542. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1543. answers=[soa_rrset, ns_rr, a_rr, soa_rrset])
  1544. self.conn._handle_xfrin_responses()
  1545. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1546. # In the case AXFR-style IXFR, journaling must have been disabled.
  1547. self.assertFalse(self.conn._datasrc_client._journaling_enabled)
  1548. self.assertEqual([], self.conn._datasrc_client.diffs)
  1549. # The SOA should be added exactly once, and in our implementation
  1550. # it should be added at the end of the sequence.
  1551. check_diffs(self.assertEqual,
  1552. [[('add', ns_rr), ('add', a_rr), ('add', soa_rrset)]],
  1553. self.conn._datasrc_client.committed_diffs)
  1554. def test_ixfr_to_axfr_response_mismatch_soa(self):
  1555. '''AXFR-style IXFR response, but the two SOA are not the same.
  1556. In the current implementation, we accept it and use the second SOA.
  1557. '''
  1558. ns_rr = self._create_ns()
  1559. a_rr = self._create_a('192.0.2.1')
  1560. self.conn.reply_data = self.conn.create_response_data(
  1561. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1562. answers=[soa_rrset, ns_rr, a_rr, begin_soa_rrset])
  1563. self.conn._handle_xfrin_responses()
  1564. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1565. self.assertEqual([], self.conn._datasrc_client.diffs)
  1566. check_diffs(self.assertEqual,
  1567. [[('add', ns_rr), ('add', a_rr),
  1568. ('add', begin_soa_rrset)]],
  1569. self.conn._datasrc_client.committed_diffs)
  1570. def test_ixfr_to_axfr_response_extra(self):
  1571. '''Test with an extra RR after the end of AXFR-style IXFR session.
  1572. The session should be rejected, and nothing should be committed.
  1573. '''
  1574. ns_rr = self._create_ns()
  1575. a_rr = self._create_a('192.0.2.1')
  1576. self.conn.reply_data = self.conn.create_response_data(
  1577. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1578. answers=[soa_rrset, ns_rr, a_rr, soa_rrset, a_rr])
  1579. self.assertRaises(XfrinProtocolError,
  1580. self.conn._handle_xfrin_responses)
  1581. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1582. self.assertEqual([], self.conn._datasrc_client.committed_diffs)
  1583. class TestIXFRSession(TestXfrinConnection):
  1584. '''Tests for a full IXFR session (query and response).
  1585. Detailed corner cases should have been covered in test_create_query()
  1586. and TestIXFRResponse, so we'll only check some typical cases to confirm
  1587. the general logic flow.
  1588. '''
  1589. def setUp(self):
  1590. # replace time.time with a steadily increasing fake one
  1591. self.orig_time_time = time.time
  1592. time.time = get_fake_time_time()
  1593. super().setUp()
  1594. def tearDown(self):
  1595. time.time = self.orig_time_time
  1596. def test_do_xfrin(self):
  1597. def create_ixfr_response():
  1598. self.conn.reply_data = self.conn.create_response_data(
  1599. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1600. RRType.IXFR())],
  1601. answers=[soa_rrset, begin_soa_rrset, soa_rrset, soa_rrset])
  1602. self.conn.response_generator = create_ixfr_response
  1603. self.assertEqual(XFRIN_OK, self.conn.do_xfrin(False, RRType.IXFR()))
  1604. # Check some details of the IXFR protocol processing
  1605. self.assertEqual(type(XfrinIXFREnd()), type(self.conn.get_xfrstate()))
  1606. check_diffs(self.assertEqual,
  1607. [[('delete', begin_soa_rrset), ('add', soa_rrset)]],
  1608. self.conn._datasrc_client.committed_diffs)
  1609. # Check if the query was IXFR.
  1610. qdata = self.conn.query_data[2:]
  1611. qmsg = Message(Message.PARSE)
  1612. qmsg.from_wire(qdata, len(qdata))
  1613. self.assertEqual(1, qmsg.get_rr_count(Message.SECTION_QUESTION))
  1614. self.assertEqual(TEST_ZONE_NAME, qmsg.get_question()[0].get_name())
  1615. self.assertEqual(RRType.IXFR(), qmsg.get_question()[0].get_type())
  1616. self.assertEqual(1, self.conn._transfer_stats.message_count)
  1617. self.assertEqual(0, self.conn._transfer_stats.axfr_rr_count)
  1618. self.assertEqual(1, self.conn._transfer_stats.ixfr_changeset_count)
  1619. self.assertEqual(1, self.conn._transfer_stats.ixfr_deletion_count)
  1620. self.assertEqual(1, self.conn._transfer_stats.ixfr_addition_count)
  1621. self.assertEqual(188, self.conn._transfer_stats.byte_count)
  1622. self.assertGreater(self.conn._transfer_stats.get_running_time(), 0)
  1623. def test_do_xfrin_fail(self):
  1624. '''IXFR fails due to a protocol error.
  1625. '''
  1626. def create_ixfr_response():
  1627. self.conn.reply_data = self.conn.create_response_data(
  1628. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1629. RRType.IXFR())],
  1630. answers=[soa_rrset, begin_soa_rrset, soa_rrset,
  1631. self._create_soa('1235')])
  1632. self.conn.response_generator = create_ixfr_response
  1633. self.assertEqual(XFRIN_FAIL, self.conn.do_xfrin(False, RRType.IXFR()))
  1634. def test_do_xfrin_fail2(self):
  1635. '''IXFR fails due to a bogus DNS message.
  1636. '''
  1637. self._create_broken_response_data()
  1638. self.assertEqual(XFRIN_FAIL, self.conn.do_xfrin(False, RRType.IXFR()))
  1639. def test_do_xfrin_uptodate(self):
  1640. '''IXFR is (gracefully) aborted because serial is not new
  1641. '''
  1642. def create_response():
  1643. self.conn.reply_data = self.conn.create_response_data(
  1644. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1645. RRType.IXFR())],
  1646. answers=[begin_soa_rrset])
  1647. self.conn.response_generator = create_response
  1648. self.assertEqual(XFRIN_OK, self.conn.do_xfrin(False, RRType.IXFR()))
  1649. self.assertEqual(1, self.conn._transfer_stats.message_count)
  1650. self.assertEqual(0, self.conn._transfer_stats.axfr_rr_count)
  1651. self.assertEqual(0, self.conn._transfer_stats.ixfr_changeset_count)
  1652. self.assertEqual(0, self.conn._transfer_stats.ixfr_deletion_count)
  1653. self.assertEqual(0, self.conn._transfer_stats.ixfr_addition_count)
  1654. self.assertEqual(80, self.conn._transfer_stats.byte_count)
  1655. self.assertGreater(self.conn._transfer_stats.get_running_time(), 0)
  1656. class TestXFRSessionWithSQLite3(TestXfrinConnection):
  1657. '''Tests for XFR sessions using an SQLite3 DB.
  1658. These are provided mainly to confirm the implementation actually works
  1659. in an environment closer to actual operational environments. So we
  1660. only check a few common cases; other details are tested using mock
  1661. data sources.
  1662. '''
  1663. def setUp(self):
  1664. self.sqlite3db_src = TESTDATA_SRCDIR + '/example.com.sqlite3'
  1665. self.sqlite3db_obj = TESTDATA_OBJDIR + '/example.com.sqlite3.copy'
  1666. self.empty_sqlite3db_obj = TESTDATA_OBJDIR + '/empty.sqlite3'
  1667. self.sqlite3db_cfg = "{ \"database_file\": \"" +\
  1668. self.sqlite3db_obj + "\"}"
  1669. # replace time.time with a steadily increasing fake one
  1670. self.orig_time_time = time.time
  1671. time.time = get_fake_time_time()
  1672. super().setUp()
  1673. if os.path.exists(self.sqlite3db_obj):
  1674. os.unlink(self.sqlite3db_obj)
  1675. if os.path.exists(self.empty_sqlite3db_obj):
  1676. os.unlink(self.empty_sqlite3db_obj)
  1677. shutil.copyfile(self.sqlite3db_src, self.sqlite3db_obj)
  1678. self.conn._datasrc_client = DataSourceClient("sqlite3",
  1679. self.sqlite3db_cfg)
  1680. def tearDown(self):
  1681. if os.path.exists(self.sqlite3db_obj):
  1682. os.unlink(self.sqlite3db_obj)
  1683. if os.path.exists(self.empty_sqlite3db_obj):
  1684. os.unlink(self.empty_sqlite3db_obj)
  1685. time.time = self.orig_time_time
  1686. def get_zone_serial(self):
  1687. result, finder = self.conn._datasrc_client.find_zone(TEST_ZONE_NAME)
  1688. self.assertEqual(DataSourceClient.SUCCESS, result)
  1689. result, soa, _ = finder.find(TEST_ZONE_NAME, RRType.SOA())
  1690. self.assertEqual(ZoneFinder.SUCCESS, result)
  1691. self.assertEqual(1, soa.get_rdata_count())
  1692. return get_soa_serial(soa.get_rdata()[0])
  1693. def record_exist(self, name, type):
  1694. result, finder = self.conn._datasrc_client.find_zone(TEST_ZONE_NAME)
  1695. self.assertEqual(DataSourceClient.SUCCESS, result)
  1696. result, soa, _ = finder.find(name, type)
  1697. return result == ZoneFinder.SUCCESS
  1698. def test_do_ixfrin_sqlite3(self):
  1699. def create_ixfr_response():
  1700. self.conn.reply_data = self.conn.create_response_data(
  1701. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1702. RRType.IXFR())],
  1703. answers=[soa_rrset, begin_soa_rrset, soa_rrset, soa_rrset])
  1704. self.conn.response_generator = create_ixfr_response
  1705. # Confirm xfrin succeeds and SOA is updated
  1706. self.assertEqual(1230, self.get_zone_serial().get_value())
  1707. self.assertEqual(XFRIN_OK, self.conn.do_xfrin(False, RRType.IXFR()))
  1708. self.assertEqual(1234, self.get_zone_serial().get_value())
  1709. # Also confirm the corresponding diffs are stored in the diffs table
  1710. conn = sqlite3.connect(self.sqlite3db_obj)
  1711. cur = conn.cursor()
  1712. cur.execute('SELECT name, rrtype, ttl, rdata FROM diffs ORDER BY id')
  1713. soa_rdata_base = 'master.example.com. admin.example.com. ' + \
  1714. 'SERIAL 3600 1800 2419200 7200'
  1715. self.assertEqual(cur.fetchall(),
  1716. [(TEST_ZONE_NAME_STR, 'SOA', 3600,
  1717. re.sub('SERIAL', str(1230), soa_rdata_base)),
  1718. (TEST_ZONE_NAME_STR, 'SOA', 3600,
  1719. re.sub('SERIAL', str(1234), soa_rdata_base))])
  1720. conn.close()
  1721. def test_do_ixfrin_sqlite3_fail(self):
  1722. '''Similar to the previous test, but xfrin fails due to error.
  1723. Check the DB is not changed.
  1724. '''
  1725. def create_ixfr_response():
  1726. self.conn.reply_data = self.conn.create_response_data(
  1727. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1728. RRType.IXFR())],
  1729. answers=[soa_rrset, begin_soa_rrset, soa_rrset,
  1730. self._create_soa('1235')])
  1731. self.conn.response_generator = create_ixfr_response
  1732. self.assertEqual(1230, self.get_zone_serial().get_value())
  1733. self.assertEqual(XFRIN_FAIL, self.conn.do_xfrin(False, RRType.IXFR()))
  1734. self.assertEqual(1230, self.get_zone_serial().get_value())
  1735. def test_do_ixfrin_nozone_sqlite3(self):
  1736. self._set_test_zone(Name('nosuchzone.example'))
  1737. self.assertEqual(XFRIN_FAIL, self.conn.do_xfrin(False, RRType.IXFR()))
  1738. # This should fail even before starting state transition
  1739. self.assertEqual(None, self.conn.get_xfrstate())
  1740. def axfr_check(self, type):
  1741. '''Common checks for AXFR and AXFR-style IXFR
  1742. '''
  1743. def create_response():
  1744. self.conn.reply_data = self.conn.create_response_data(
  1745. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, type)],
  1746. answers=[soa_rrset, self._create_ns(), soa_rrset])
  1747. self.conn.response_generator = create_response
  1748. # Confirm xfrin succeeds and SOA is updated, A RR is deleted.
  1749. self.assertEqual(1230, self.get_zone_serial().get_value())
  1750. self.assertTrue(self.record_exist(Name('dns01.example.com'),
  1751. RRType.A()))
  1752. self.assertEqual(XFRIN_OK, self.conn.do_xfrin(False, type))
  1753. self.assertEqual(1234, self.get_zone_serial().get_value())
  1754. self.assertFalse(self.record_exist(Name('dns01.example.com'),
  1755. RRType.A()))
  1756. def test_do_ixfrin_axfr_sqlite3(self):
  1757. '''AXFR-style IXFR.
  1758. '''
  1759. self.axfr_check(RRType.IXFR())
  1760. def test_do_axfrin_sqlite3(self):
  1761. '''AXFR.
  1762. '''
  1763. self.axfr_check(RRType.AXFR())
  1764. def axfr_failure_check(self, type):
  1765. '''Similar to the previous two tests, but xfrin fails due to error.
  1766. Check the DB is not changed.
  1767. '''
  1768. def create_response():
  1769. self.conn.reply_data = self.conn.create_response_data(
  1770. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, type)],
  1771. answers=[soa_rrset, self._create_ns(), soa_rrset, soa_rrset])
  1772. self.conn.response_generator = create_response
  1773. self.assertEqual(1230, self.get_zone_serial().get_value())
  1774. self.assertTrue(self.record_exist(Name('dns01.example.com'),
  1775. RRType.A()))
  1776. self.assertEqual(XFRIN_FAIL, self.conn.do_xfrin(False, type))
  1777. self.assertEqual(1230, self.get_zone_serial().get_value())
  1778. self.assertTrue(self.record_exist(Name('dns01.example.com'),
  1779. RRType.A()))
  1780. def test_do_xfrin_axfr_sqlite3_fail(self):
  1781. '''Failure case for AXFR-style IXFR.
  1782. '''
  1783. self.axfr_failure_check(RRType.IXFR())
  1784. def test_do_axfrin_sqlite3_fail(self):
  1785. '''Failure case for AXFR.
  1786. '''
  1787. self.axfr_failure_check(RRType.AXFR())
  1788. def test_do_axfrin_nozone_sqlite3(self):
  1789. '''AXFR test with an empty SQLite3 DB file, thus no target zone there.
  1790. For now, we provide backward compatible behavior: xfrin will create
  1791. the zone (after even setting up the entire schema) in the zone.
  1792. Note: a future version of this test will make it fail.
  1793. '''
  1794. self.conn._db_file = self.empty_sqlite3db_obj
  1795. self.conn._datasrc_client = DataSourceClient(
  1796. "sqlite3",
  1797. "{ \"database_file\": \"" + self.empty_sqlite3db_obj + "\"}")
  1798. def create_response():
  1799. self.conn.reply_data = self.conn.create_response_data(
  1800. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1801. RRType.AXFR())],
  1802. answers=[soa_rrset, self._create_ns(), soa_rrset])
  1803. self.conn.response_generator = create_response
  1804. self._set_test_zone(Name('example.com'))
  1805. self.assertEqual(XFRIN_OK, self.conn.do_xfrin(False, RRType.AXFR()))
  1806. self.assertEqual(type(XfrinAXFREnd()),
  1807. type(self.conn.get_xfrstate()))
  1808. self.assertEqual(1234, self.get_zone_serial().get_value())
  1809. self.assertFalse(self.record_exist(Name('dns01.example.com'),
  1810. RRType.A()))
  1811. class TestXfrinRecorder(unittest.TestCase):
  1812. def setUp(self):
  1813. self.recorder = XfrinRecorder()
  1814. def test_increment(self):
  1815. self.assertEqual(self.recorder.count(), 0)
  1816. self.recorder.increment(TEST_ZONE_NAME)
  1817. self.assertEqual(self.recorder.count(), 1)
  1818. # duplicate "increment" should probably be rejected. but it's not
  1819. # checked at this moment
  1820. self.recorder.increment(TEST_ZONE_NAME)
  1821. self.assertEqual(self.recorder.count(), 2)
  1822. def test_decrement(self):
  1823. self.assertEqual(self.recorder.count(), 0)
  1824. self.recorder.increment(TEST_ZONE_NAME)
  1825. self.assertEqual(self.recorder.count(), 1)
  1826. self.recorder.decrement(TEST_ZONE_NAME)
  1827. self.assertEqual(self.recorder.count(), 0)
  1828. def test_decrement_from_empty(self):
  1829. self.assertEqual(self.recorder.count(), 0)
  1830. self.recorder.decrement(TEST_ZONE_NAME)
  1831. self.assertEqual(self.recorder.count(), 0)
  1832. def test_inprogress(self):
  1833. self.assertEqual(self.recorder.count(), 0)
  1834. self.recorder.increment(TEST_ZONE_NAME)
  1835. self.assertEqual(self.recorder.xfrin_in_progress(TEST_ZONE_NAME), True)
  1836. self.recorder.decrement(TEST_ZONE_NAME)
  1837. self.assertEqual(self.recorder.xfrin_in_progress(TEST_ZONE_NAME), False)
  1838. class TestXfrinProcess(unittest.TestCase):
  1839. def setUp(self):
  1840. self.unlocked = False
  1841. self.conn_closed = False
  1842. self.do_raise_on_close = False
  1843. self.do_raise_on_connect = False
  1844. self.do_raise_on_publish = False
  1845. self.master = (socket.AF_INET, socket.SOCK_STREAM,
  1846. (TEST_MASTER_IPV4_ADDRESS, TEST_MASTER_PORT))
  1847. def tearDown(self):
  1848. # whatever happens the lock acquired in xfrin_recorder.increment
  1849. # must always be released. We checked the condition for all test
  1850. # cases.
  1851. self.assertTrue(self.unlocked)
  1852. # Same for the connection
  1853. self.assertTrue(self.conn_closed)
  1854. def increment(self, zone_name):
  1855. '''Fake method of xfrin_recorder.increment.
  1856. '''
  1857. self.unlocked = False
  1858. def decrement(self, zone_name):
  1859. '''Fake method of xfrin_recorder.decrement.
  1860. '''
  1861. self.unlocked = True
  1862. def publish_xfrin_news(self, zone_name, rrclass, ret):
  1863. '''Fake method of serve.publish_xfrin_news
  1864. '''
  1865. if self.do_raise_on_publish:
  1866. raise XfrinTestException('Emulated exception in publish')
  1867. def connect_to_master(self, conn):
  1868. self.sock_fd = conn.fileno()
  1869. if self.do_raise_on_connect:
  1870. raise XfrinTestException('Emulated exception in connect')
  1871. return True
  1872. def conn_close(self, conn):
  1873. self.conn_closed = True
  1874. XfrinConnection.close(conn)
  1875. if self.do_raise_on_close:
  1876. raise XfrinTestException('Emulated exception in connect')
  1877. def create_xfrinconn(self, sock_map, zone_name, rrclass, datasrc_client,
  1878. shutdown_event, master_addrinfo, tsig_key):
  1879. conn = MockXfrinConnection(sock_map, zone_name, rrclass,
  1880. datasrc_client, shutdown_event,
  1881. master_addrinfo, tsig_key)
  1882. # An awkward check that would specifically identify an old bug
  1883. # where initialziation of XfrinConnection._tsig_ctx_creator caused
  1884. # self reference and subsequently led to reference leak.
  1885. orig_ref = sys.getrefcount(conn)
  1886. conn._tsig_ctx_creator = None
  1887. self.assertEqual(orig_ref, sys.getrefcount(conn))
  1888. # Replace some methods for connect with our internal ones for the
  1889. # convenience of tests
  1890. conn.connect_to_master = lambda : self.connect_to_master(conn)
  1891. conn.do_xfrin = lambda x, y : XFRIN_OK
  1892. conn.close = lambda : self.conn_close(conn)
  1893. return conn
  1894. def test_process_xfrin_normal(self):
  1895. # Normal, successful case. We only check that things are cleaned up
  1896. # at the tearDown time.
  1897. process_xfrin(self, self, TEST_ZONE_NAME, TEST_RRCLASS, None, None,
  1898. self.master, False, None, RRType.AXFR(),
  1899. self.create_xfrinconn)
  1900. def test_process_xfrin_exception_on_connect(self):
  1901. # connect_to_master() will raise an exception. Things must still be
  1902. # cleaned up.
  1903. self.do_raise_on_connect = True
  1904. process_xfrin(self, self, TEST_ZONE_NAME, TEST_RRCLASS, None, None,
  1905. self.master, False, None, RRType.AXFR(),
  1906. self.create_xfrinconn)
  1907. def test_process_xfrin_exception_on_close(self):
  1908. # connect() will result in exception, and even the cleanup close()
  1909. # will fail with an exception. This should be quite likely a bug,
  1910. # but we deal with that case.
  1911. self.do_raise_on_connect = True
  1912. self.do_raise_on_close = True
  1913. process_xfrin(self, self, TEST_ZONE_NAME, TEST_RRCLASS, None, None,
  1914. self.master, False, None, RRType.AXFR(),
  1915. self.create_xfrinconn)
  1916. def test_process_xfrin_exception_on_publish(self):
  1917. # xfr succeeds but notifying the zonemgr fails with exception.
  1918. # everything must still be cleaned up.
  1919. self.do_raise_on_publish = True
  1920. process_xfrin(self, self, TEST_ZONE_NAME, TEST_RRCLASS, None, None,
  1921. self.master, False, None, RRType.AXFR(),
  1922. self.create_xfrinconn)
  1923. class TestXfrin(unittest.TestCase):
  1924. def setUp(self):
  1925. # redirect output
  1926. self.stderr_backup = sys.stderr
  1927. sys.stderr = open(os.devnull, 'w')
  1928. self.xfr = MockXfrin()
  1929. self.args = {}
  1930. self.args['zone_name'] = TEST_ZONE_NAME_STR
  1931. self.args['class'] = TEST_RRCLASS_STR
  1932. self.args['port'] = TEST_MASTER_PORT
  1933. self.args['master'] = TEST_MASTER_IPV4_ADDRESS
  1934. self.args['db_file'] = TEST_DB_FILE
  1935. self.args['tsig_key'] = ''
  1936. def tearDown(self):
  1937. self.assertFalse(self.xfr._module_cc.stopped);
  1938. self.xfr.shutdown()
  1939. self.assertTrue(self.xfr._module_cc.stopped);
  1940. sys.stderr.close()
  1941. sys.stderr = self.stderr_backup
  1942. def _do_parse_zone_name_class(self):
  1943. return self.xfr._parse_zone_name_and_class(self.args)
  1944. def _do_parse_master_port(self):
  1945. name, rrclass = self._do_parse_zone_name_class()
  1946. return self.xfr._parse_master_and_port(self.args, name, rrclass)
  1947. def test_parse_cmd_params(self):
  1948. name, rrclass = self._do_parse_zone_name_class()
  1949. master_addrinfo = self._do_parse_master_port()
  1950. db_file = self.args.get('db_file')
  1951. self.assertEqual(master_addrinfo[2][1], int(TEST_MASTER_PORT))
  1952. self.assertEqual(name, TEST_ZONE_NAME)
  1953. self.assertEqual(rrclass, TEST_RRCLASS)
  1954. self.assertEqual(master_addrinfo[2][0], TEST_MASTER_IPV4_ADDRESS)
  1955. self.assertEqual(db_file, TEST_DB_FILE)
  1956. def test_parse_cmd_params_default_port(self):
  1957. del self.args['port']
  1958. master_addrinfo = self._do_parse_master_port()
  1959. self.assertEqual(master_addrinfo[2][1], 53)
  1960. def test_parse_cmd_params_ip6master(self):
  1961. self.args['master'] = TEST_MASTER_IPV6_ADDRESS
  1962. master_addrinfo = self._do_parse_master_port()
  1963. self.assertEqual(master_addrinfo[2][0], TEST_MASTER_IPV6_ADDRESS)
  1964. def test_parse_cmd_params_chclass(self):
  1965. self.args['zone_class'] = 'CH'
  1966. self.assertEqual(self._do_parse_zone_name_class()[1], RRClass.CH())
  1967. def test_parse_cmd_params_bogusclass(self):
  1968. self.args['zone_class'] = 'XXX'
  1969. self.assertRaises(XfrinZoneInfoException, self._do_parse_zone_name_class)
  1970. def test_parse_cmd_params_nozone(self):
  1971. # zone name is mandatory.
  1972. del self.args['zone_name']
  1973. self.assertRaises(XfrinException, self._do_parse_zone_name_class)
  1974. def test_parse_cmd_params_nomaster(self):
  1975. # master address is mandatory.
  1976. del self.args['master']
  1977. self.assertRaises(XfrinException, self._do_parse_master_port)
  1978. def test_parse_cmd_params_bad_ip4(self):
  1979. self.args['master'] = '3.3.3.3.3'
  1980. self.assertRaises(XfrinException, self._do_parse_master_port)
  1981. def test_parse_cmd_params_bad_ip6(self):
  1982. self.args['master'] = '1::1::1'
  1983. self.assertRaises(XfrinException, self._do_parse_master_port)
  1984. def test_parse_cmd_params_bad_port(self):
  1985. self.args['port'] = '-1'
  1986. self.assertRaises(XfrinException, self._do_parse_master_port)
  1987. self.args['port'] = '65536'
  1988. self.assertRaises(XfrinException, self._do_parse_master_port)
  1989. self.args['port'] = 'http'
  1990. self.assertRaises(XfrinException, self._do_parse_master_port)
  1991. def test_command_handler_shutdown(self):
  1992. self.assertEqual(self.xfr.command_handler("shutdown",
  1993. None)['result'][0], 0)
  1994. # shutdown command doesn't expect an argument, but accepts it if any.
  1995. self.assertEqual(self.xfr.command_handler("shutdown",
  1996. "unused")['result'][0], 0)
  1997. def test_command_handler_retransfer(self):
  1998. self.assertEqual(self.xfr.command_handler("retransfer",
  1999. self.args)['result'][0], 0)
  2000. self.assertEqual(self.args['master'], self.xfr.xfrin_started_master_addr)
  2001. self.assertEqual(int(self.args['port']), self.xfr.xfrin_started_master_port)
  2002. # By default we use AXFR (for now)
  2003. self.assertEqual(RRType.AXFR(), self.xfr.xfrin_started_request_type)
  2004. def test_command_handler_retransfer_short_command1(self):
  2005. # try it when only specifying the zone name (of unknown zone)
  2006. # this should fail because master address is not specified.
  2007. short_args = {}
  2008. short_args['zone_name'] = TEST_ZONE_NAME_STR
  2009. self.assertEqual(self.xfr.command_handler("retransfer",
  2010. short_args)['result'][0], 1)
  2011. def test_command_handler_retransfer_short_command2(self):
  2012. # try it when only specifying the zone name (of known zone)
  2013. short_args = {}
  2014. short_args['zone_name'] = TEST_ZONE_NAME_STR
  2015. zones = { 'zones': [
  2016. { 'name': TEST_ZONE_NAME_STR,
  2017. 'master_addr': TEST_MASTER_IPV4_ADDRESS,
  2018. 'master_port': TEST_MASTER_PORT
  2019. }
  2020. ]}
  2021. self.xfr.config_handler(zones)
  2022. self.assertEqual(self.xfr.command_handler("retransfer",
  2023. short_args)['result'][0], 0)
  2024. self.assertEqual(TEST_MASTER_IPV4_ADDRESS,
  2025. self.xfr.xfrin_started_master_addr)
  2026. self.assertEqual(int(TEST_MASTER_PORT),
  2027. self.xfr.xfrin_started_master_port)
  2028. def test_command_handler_retransfer_short_command3(self):
  2029. # try it when only specifying the zone name (of known zone)
  2030. short_args = {}
  2031. # test it without the trailing root dot
  2032. short_args['zone_name'] = TEST_ZONE_NAME_STR[:-1]
  2033. zones = { 'zones': [
  2034. { 'name': TEST_ZONE_NAME_STR,
  2035. 'master_addr': TEST_MASTER_IPV4_ADDRESS,
  2036. 'master_port': TEST_MASTER_PORT
  2037. }
  2038. ]}
  2039. self.xfr.config_handler(zones)
  2040. self.assertEqual(self.xfr.command_handler("retransfer",
  2041. short_args)['result'][0], 0)
  2042. self.assertEqual(TEST_MASTER_IPV4_ADDRESS,
  2043. self.xfr.xfrin_started_master_addr)
  2044. self.assertEqual(int(TEST_MASTER_PORT),
  2045. self.xfr.xfrin_started_master_port)
  2046. def test_command_handler_retransfer_short_command4(self):
  2047. # try it when only specifying the zone name (of known zone, with
  2048. # different case)
  2049. short_args = {}
  2050. # swap the case of the zone name in our command
  2051. short_args['zone_name'] = TEST_ZONE_NAME_STR.swapcase()
  2052. zones = { 'zones': [
  2053. { 'name': TEST_ZONE_NAME_STR,
  2054. 'master_addr': TEST_MASTER_IPV4_ADDRESS,
  2055. 'master_port': TEST_MASTER_PORT
  2056. }
  2057. ]}
  2058. self.xfr.config_handler(zones)
  2059. self.assertEqual(self.xfr.command_handler("retransfer",
  2060. short_args)['result'][0], 0)
  2061. self.assertEqual(TEST_MASTER_IPV4_ADDRESS,
  2062. self.xfr.xfrin_started_master_addr)
  2063. self.assertEqual(int(TEST_MASTER_PORT),
  2064. self.xfr.xfrin_started_master_port)
  2065. def test_command_handler_retransfer_badcommand(self):
  2066. self.args['master'] = 'invalid'
  2067. self.assertEqual(self.xfr.command_handler("retransfer",
  2068. self.args)['result'][0], 1)
  2069. def test_command_handler_retransfer_quota(self):
  2070. self.args['master'] = TEST_MASTER_IPV4_ADDRESS
  2071. for i in range(self.xfr._max_transfers_in - 1):
  2072. self.xfr.recorder.increment(Name(str(i) + TEST_ZONE_NAME_STR))
  2073. # there can be one more outstanding transfer.
  2074. self.assertEqual(self.xfr.command_handler("retransfer",
  2075. self.args)['result'][0], 0)
  2076. # make sure the # xfrs would excceed the quota
  2077. self.xfr.recorder.increment(Name(str(self.xfr._max_transfers_in) + TEST_ZONE_NAME_STR))
  2078. # this one should fail
  2079. self.assertEqual(self.xfr.command_handler("retransfer",
  2080. self.args)['result'][0], 1)
  2081. def test_command_handler_retransfer_inprogress(self):
  2082. self.xfr.recorder.increment(TEST_ZONE_NAME)
  2083. self.assertEqual(self.xfr.command_handler("retransfer",
  2084. self.args)['result'][0], 1)
  2085. def test_command_handler_retransfer_nomodule(self):
  2086. dns_module = sys.modules['pydnspp'] # this must exist
  2087. del sys.modules['pydnspp']
  2088. self.assertEqual(self.xfr.command_handler("retransfer",
  2089. self.args)['result'][0], 1)
  2090. # sys.modules is global, so we must recover it
  2091. sys.modules['pydnspp'] = dns_module
  2092. def test_command_handler_refresh(self):
  2093. # at this level, refresh is no different than retransfer.
  2094. # just confirm the successful case with a different family of address.
  2095. self.args['master'] = TEST_MASTER_IPV6_ADDRESS
  2096. self.assertEqual(self.xfr.command_handler("refresh",
  2097. self.args)['result'][0], 0)
  2098. self.assertEqual(TEST_MASTER_IPV6_ADDRESS,
  2099. self.xfr.xfrin_started_master_addr)
  2100. self.assertEqual(int(TEST_MASTER_PORT),
  2101. self.xfr.xfrin_started_master_port)
  2102. # By default we use AXFR (for now)
  2103. self.assertEqual(RRType.AXFR(), self.xfr.xfrin_started_request_type)
  2104. def test_command_handler_notify(self):
  2105. # at this level, refresh is no different than retransfer.
  2106. self.args['master'] = TEST_MASTER_IPV6_ADDRESS
  2107. # ...but the zone is unknown so this would return an error
  2108. self.assertEqual(self.xfr.command_handler("notify",
  2109. self.args)['result'][0], 1)
  2110. def test_command_handler_notify_known_zone_bad_addr(self):
  2111. # try it with a known zone
  2112. self.args['master'] = TEST_MASTER_IPV6_ADDRESS
  2113. # but use a different address in the actual command
  2114. zones = { 'zones': [
  2115. { 'name': TEST_ZONE_NAME_STR,
  2116. 'master_addr': TEST_MASTER_IPV4_ADDRESS,
  2117. 'master_port': TEST_MASTER_PORT
  2118. }
  2119. ]}
  2120. self.xfr.config_handler(zones)
  2121. # the command should now fail
  2122. self.assertEqual(self.xfr.command_handler("notify",
  2123. self.args)['result'][0], 1)
  2124. # also try a different port in the actual command
  2125. zones = { 'zones': [
  2126. { 'name': TEST_ZONE_NAME_STR,
  2127. 'master_addr': TEST_MASTER_IPV6_ADDRESS,
  2128. 'master_port': str(int(TEST_MASTER_PORT) + 1)
  2129. }
  2130. ]}
  2131. self.xfr.config_handler(zones)
  2132. # the command should now fail
  2133. self.assertEqual(self.xfr.command_handler("notify",
  2134. self.args)['result'][0], 1)
  2135. def test_command_handler_notify_known_zone(self):
  2136. # try it with a known zone
  2137. self.args['master'] = TEST_MASTER_IPV6_ADDRESS
  2138. # with a zone configuration that has a matching master address.
  2139. zones = { 'zones': [
  2140. { 'name': TEST_ZONE_NAME_STR,
  2141. 'master_addr': TEST_MASTER_IPV6_ADDRESS,
  2142. 'master_port': TEST_MASTER_PORT
  2143. }
  2144. ]}
  2145. self.xfr.config_handler(zones)
  2146. self.assertEqual(self.xfr.command_handler("notify",
  2147. self.args)['result'][0], 0)
  2148. def test_command_handler_unknown(self):
  2149. self.assertEqual(self.xfr.command_handler("xxx", None)['result'][0], 1)
  2150. def test_command_handler_transfers_in(self):
  2151. self.assertEqual(self.xfr.config_handler({})['result'][0], 0)
  2152. self.assertEqual(self.xfr.config_handler({'transfers_in': 3})['result'][0], 0)
  2153. self.assertEqual(self.xfr._max_transfers_in, 3)
  2154. def _check_zones_config(self, config_given):
  2155. if 'transfers_in' in config_given:
  2156. self.assertEqual(config_given['transfers_in'],
  2157. self.xfr._max_transfers_in)
  2158. for zone_config in config_given['zones']:
  2159. zone_name = zone_config['name']
  2160. zone_info = self.xfr._get_zone_info(Name(zone_name), RRClass.IN())
  2161. self.assertEqual(str(zone_info.master_addr), zone_config['master_addr'])
  2162. self.assertEqual(zone_info.master_port, zone_config['master_port'])
  2163. if 'tsig_key' in zone_config:
  2164. self.assertEqual(zone_info.tsig_key_name.to_text(),
  2165. Name(zone_config['tsig_key']).to_text())
  2166. else:
  2167. self.assertIsNone(zone_info.tsig_key_name)
  2168. if 'use_ixfr' in zone_config and\
  2169. zone_config.get('use_ixfr'):
  2170. self.assertTrue(zone_info.use_ixfr)
  2171. else:
  2172. # if not set, should default to False
  2173. self.assertFalse(zone_info.use_ixfr)
  2174. def test_config_handler_zones(self):
  2175. # This test passes a number of good and bad configs, and checks whether
  2176. # the values are reflected in the structure that will dictate the
  2177. # actual behaviour. It also checks if bad values are correctly
  2178. # handled
  2179. config1 = { 'transfers_in': 3,
  2180. 'zones': [
  2181. { 'name': 'test.example.',
  2182. 'master_addr': '192.0.2.1',
  2183. 'master_port': 53,
  2184. 'use_ixfr': False
  2185. }
  2186. ]}
  2187. self.assertEqual(self.xfr.config_handler(config1)['result'][0], 0)
  2188. self._check_zones_config(config1)
  2189. config2 = { 'transfers_in': 4,
  2190. 'zones': [
  2191. { 'name': 'test.example.',
  2192. 'master_addr': '192.0.2.2',
  2193. 'master_port': 53,
  2194. 'tsig_key': "example.com:SFuWd/q99SzF8Yzd1QbB9g==",
  2195. 'use_ixfr': True
  2196. }
  2197. ]}
  2198. self.assertEqual(self.xfr.config_handler(config2)['result'][0], 0)
  2199. self._check_zones_config(config2)
  2200. # test that configuring the zone multiple times fails
  2201. zones = { 'transfers_in': 5,
  2202. 'zones': [
  2203. { 'name': 'test.example.',
  2204. 'master_addr': '192.0.2.1',
  2205. 'master_port': 53
  2206. },
  2207. { 'name': 'test.example.',
  2208. 'master_addr': '192.0.2.2',
  2209. 'master_port': 53
  2210. }
  2211. ]}
  2212. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  2213. # since this has failed, we should still have the previous config
  2214. self._check_zones_config(config2)
  2215. zones = { 'zones': [
  2216. { 'name': 'test.example.',
  2217. 'master_addr': '192.0.2.3',
  2218. 'master_port': 53,
  2219. 'class': 'BADCLASS'
  2220. }
  2221. ]}
  2222. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  2223. self._check_zones_config(config2)
  2224. zones = { 'zones': [
  2225. { 'master_addr': '192.0.2.4',
  2226. 'master_port': 53
  2227. }
  2228. ]}
  2229. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  2230. # since this has failed, we should still have the previous config
  2231. self._check_zones_config(config2)
  2232. zones = { 'zones': [
  2233. { 'name': 'bad..zone.',
  2234. 'master_addr': '192.0.2.5',
  2235. 'master_port': 53
  2236. }
  2237. ]}
  2238. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  2239. # since this has failed, we should still have the previous config
  2240. self._check_zones_config(config2)
  2241. zones = { 'zones': [
  2242. { 'name': '',
  2243. 'master_addr': '192.0.2.6',
  2244. 'master_port': 53
  2245. }
  2246. ]}
  2247. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  2248. # since this has failed, we should still have the previous config
  2249. self._check_zones_config(config2)
  2250. zones = { 'zones': [
  2251. { 'name': 'test.example',
  2252. 'master_addr': 'badaddress',
  2253. 'master_port': 53
  2254. }
  2255. ]}
  2256. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  2257. # since this has failed, we should still have the previous config
  2258. self._check_zones_config(config2)
  2259. zones = { 'zones': [
  2260. { 'name': 'test.example',
  2261. 'master_addr': '192.0.2.7',
  2262. 'master_port': 'bad_port'
  2263. }
  2264. ]}
  2265. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  2266. # since this has failed, we should still have the previous config
  2267. self._check_zones_config(config2)
  2268. zones = { 'zones': [
  2269. { 'name': 'test.example',
  2270. 'master_addr': '192.0.2.7',
  2271. 'master_port': 53,
  2272. # using a bad TSIG key spec
  2273. 'tsig_key': "bad..example.com:SFuWd/q99SzF8Yzd1QbB9g=="
  2274. }
  2275. ]}
  2276. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  2277. # since this has failed, we should still have the previous config
  2278. self._check_zones_config(config2)
  2279. # let's also add a zone that is correct too, and make sure
  2280. # that the new config is not partially taken
  2281. zones = { 'zones': [
  2282. { 'name': 'test.example.',
  2283. 'master_addr': '192.0.2.8',
  2284. 'master_port': 53
  2285. },
  2286. { 'name': 'test2.example.',
  2287. 'master_addr': '192.0.2.9',
  2288. 'master_port': 53,
  2289. 'tsig_key': 'badkey..'
  2290. }
  2291. ]}
  2292. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  2293. # since this has failed, we should still have the previous config
  2294. self._check_zones_config(config2)
  2295. def test_config_handler_zones_default(self):
  2296. # Checking it some default config values apply. Using a separate
  2297. # test case for a fresh xfr object.
  2298. config = { 'zones': [
  2299. { 'name': 'test.example.',
  2300. 'master_addr': '192.0.2.1',
  2301. 'master_port': 53,
  2302. }
  2303. ]}
  2304. self.assertEqual(self.xfr.config_handler(config)['result'][0], 0)
  2305. self._check_zones_config(config)
  2306. def common_ixfr_setup(self, xfr_mode, use_ixfr, tsig_key_str = None):
  2307. # This helper method explicitly sets up a zone configuration with
  2308. # use_ixfr, and invokes either retransfer or refresh.
  2309. # Shared by some of the following test cases.
  2310. config = {'zones': [
  2311. {'name': 'example.com.',
  2312. 'master_addr': '192.0.2.1',
  2313. 'tsig_key': tsig_key_str,
  2314. 'use_ixfr': use_ixfr}]}
  2315. self.assertEqual(self.xfr.config_handler(config)['result'][0], 0)
  2316. self.assertEqual(self.xfr.command_handler(xfr_mode,
  2317. self.args)['result'][0], 0)
  2318. def test_command_handler_retransfer_ixfr_enabled(self):
  2319. # If IXFR is explicitly enabled in config, IXFR will be used
  2320. self.common_ixfr_setup('retransfer', True)
  2321. self.assertEqual(RRType.IXFR(), self.xfr.xfrin_started_request_type)
  2322. def test_command_handler_refresh_ixfr_enabled(self):
  2323. # Same for refresh
  2324. self.common_ixfr_setup('refresh', True)
  2325. self.assertEqual(RRType.IXFR(), self.xfr.xfrin_started_request_type)
  2326. def test_command_handler_retransfer_with_tsig(self):
  2327. self.common_ixfr_setup('retransfer', False, 'example.com.key')
  2328. self.assertEqual(RRType.AXFR(), self.xfr.xfrin_started_request_type)
  2329. def test_command_handler_retransfer_with_tsig_bad_key(self):
  2330. # bad keys should not reach xfrin, but should they somehow,
  2331. # they are ignored (and result in 'key not found' + error log).
  2332. self.assertRaises(XfrinZoneInfoException, self.common_ixfr_setup,
  2333. 'retransfer', False, 'bad.key')
  2334. def test_command_handler_retransfer_with_tsig_unknown_key(self):
  2335. self.assertRaises(XfrinZoneInfoException, self.common_ixfr_setup,
  2336. 'retransfer', False, 'no.such.key')
  2337. def test_command_handler_refresh_with_tsig(self):
  2338. self.common_ixfr_setup('refresh', False, 'example.com.key')
  2339. self.assertEqual(RRType.AXFR(), self.xfr.xfrin_started_request_type)
  2340. def test_command_handler_refresh_with_tsig_bad_key(self):
  2341. # bad keys should not reach xfrin, but should they somehow,
  2342. # they are ignored (and result in 'key not found' + error log).
  2343. self.assertRaises(XfrinZoneInfoException, self.common_ixfr_setup,
  2344. 'refresh', False, 'bad.key')
  2345. def test_command_handler_refresh_with_tsig_unknown_key(self):
  2346. self.assertRaises(XfrinZoneInfoException, self.common_ixfr_setup,
  2347. 'refresh', False, 'no.such.key')
  2348. def test_command_handler_retransfer_ixfr_disabled(self):
  2349. # Similar to the previous case, but explicitly disabled. AXFR should
  2350. # be used.
  2351. self.common_ixfr_setup('retransfer', False)
  2352. self.assertEqual(RRType.AXFR(), self.xfr.xfrin_started_request_type)
  2353. def test_command_handler_refresh_ixfr_disabled(self):
  2354. # Same for refresh
  2355. self.common_ixfr_setup('refresh', False)
  2356. self.assertEqual(RRType.AXFR(), self.xfr.xfrin_started_request_type)
  2357. class TestXfrinMemoryZones(unittest.TestCase):
  2358. def setUp(self):
  2359. self.xfr = MockXfrin()
  2360. # Configuration snippet containing 2 memory datasources,
  2361. # one for IN and one for CH. Both contain a zone 'example.com'
  2362. # the IN ds also contains a zone example2.com, and a zone example3.com,
  2363. # which is of file type 'text' (and hence, should be ignored)
  2364. self.config = { 'datasources': [
  2365. { 'type': 'memory',
  2366. 'class': 'IN',
  2367. 'zones': [
  2368. { 'origin': 'example.com',
  2369. 'filetype': 'sqlite3' },
  2370. { 'origin': 'EXAMPLE2.com.',
  2371. 'filetype': 'sqlite3' },
  2372. { 'origin': 'example3.com',
  2373. 'filetype': 'text' }
  2374. ]
  2375. },
  2376. { 'type': 'memory',
  2377. 'class': 'ch',
  2378. 'zones': [
  2379. { 'origin': 'example.com',
  2380. 'filetype': 'sqlite3' }
  2381. ]
  2382. }
  2383. ] }
  2384. def test_updates(self):
  2385. self.assertFalse(self.xfr._is_memory_zone("example.com", "IN"))
  2386. self.assertFalse(self.xfr._is_memory_zone("example2.com", "IN"))
  2387. self.assertFalse(self.xfr._is_memory_zone("example3.com", "IN"))
  2388. self.assertFalse(self.xfr._is_memory_zone("example.com", "CH"))
  2389. # add them all
  2390. self.xfr._set_memory_zones(self.config, None)
  2391. self.assertTrue(self.xfr._is_memory_zone("example.com", "IN"))
  2392. self.assertTrue(self.xfr._is_memory_zone("example2.com", "IN"))
  2393. self.assertFalse(self.xfr._is_memory_zone("example3.com", "IN"))
  2394. self.assertTrue(self.xfr._is_memory_zone("example.com", "CH"))
  2395. # Remove the CH data source from the self.config snippet, and update
  2396. del self.config['datasources'][1]
  2397. self.xfr._set_memory_zones(self.config, None)
  2398. self.assertTrue(self.xfr._is_memory_zone("example.com", "IN"))
  2399. self.assertTrue(self.xfr._is_memory_zone("example2.com", "IN"))
  2400. self.assertFalse(self.xfr._is_memory_zone("example3.com", "IN"))
  2401. self.assertFalse(self.xfr._is_memory_zone("example.com", "CH"))
  2402. # Remove example2.com from the datasource, and update
  2403. del self.config['datasources'][0]['zones'][1]
  2404. self.xfr._set_memory_zones(self.config, None)
  2405. self.assertTrue(self.xfr._is_memory_zone("example.com", "IN"))
  2406. self.assertFalse(self.xfr._is_memory_zone("example2.com", "IN"))
  2407. self.assertFalse(self.xfr._is_memory_zone("example3.com", "IN"))
  2408. self.assertFalse(self.xfr._is_memory_zone("example.com", "CH"))
  2409. # If 'datasources' is not in the self.config update list (i.e. its
  2410. # self.config has not changed), no difference should be found
  2411. self.xfr._set_memory_zones({}, None)
  2412. self.assertTrue(self.xfr._is_memory_zone("example.com", "IN"))
  2413. self.assertFalse(self.xfr._is_memory_zone("example2.com", "IN"))
  2414. self.assertFalse(self.xfr._is_memory_zone("example3.com", "IN"))
  2415. self.assertFalse(self.xfr._is_memory_zone("example.com", "CH"))
  2416. # If datasources list becomes empty, everything should be removed
  2417. self.config['datasources'][0]['zones'] = []
  2418. self.xfr._set_memory_zones(self.config, None)
  2419. self.assertFalse(self.xfr._is_memory_zone("example.com", "IN"))
  2420. self.assertFalse(self.xfr._is_memory_zone("example2.com", "IN"))
  2421. self.assertFalse(self.xfr._is_memory_zone("example3.com", "IN"))
  2422. self.assertFalse(self.xfr._is_memory_zone("example.com", "CH"))
  2423. def test_normalization(self):
  2424. self.xfr._set_memory_zones(self.config, None)
  2425. # make sure it is case insensitive, root-dot-insensitive,
  2426. # and supports CLASSXXX notation
  2427. self.assertTrue(self.xfr._is_memory_zone("EXAMPLE.com", "IN"))
  2428. self.assertTrue(self.xfr._is_memory_zone("example.com", "in"))
  2429. self.assertTrue(self.xfr._is_memory_zone("example2.com.", "IN"))
  2430. self.assertTrue(self.xfr._is_memory_zone("example.com", "CLASS3"))
  2431. def test_bad_name(self):
  2432. # First set it to some config
  2433. self.xfr._set_memory_zones(self.config, None)
  2434. # Error checking; bad owner name should result in no changes
  2435. self.config['datasources'][1]['zones'][0]['origin'] = ".."
  2436. self.xfr._set_memory_zones(self.config, None)
  2437. self.assertTrue(self.xfr._is_memory_zone("example.com", "IN"))
  2438. self.assertTrue(self.xfr._is_memory_zone("example2.com", "IN"))
  2439. self.assertFalse(self.xfr._is_memory_zone("example3.com", "IN"))
  2440. self.assertTrue(self.xfr._is_memory_zone("example.com", "CH"))
  2441. def test_bad_class(self):
  2442. # First set it to some config
  2443. self.xfr._set_memory_zones(self.config, None)
  2444. # Error checking; bad owner name should result in no changes
  2445. self.config['datasources'][1]['class'] = "Foo"
  2446. self.xfr._set_memory_zones(self.config, None)
  2447. self.assertTrue(self.xfr._is_memory_zone("example.com", "IN"))
  2448. self.assertTrue(self.xfr._is_memory_zone("example2.com", "IN"))
  2449. self.assertFalse(self.xfr._is_memory_zone("example3.com", "IN"))
  2450. self.assertTrue(self.xfr._is_memory_zone("example.com", "CH"))
  2451. def test_no_filetype(self):
  2452. # omitting the filetype should leave that zone out, but not
  2453. # the rest
  2454. del self.config['datasources'][1]['zones'][0]['filetype']
  2455. self.xfr._set_memory_zones(self.config, None)
  2456. self.assertTrue(self.xfr._is_memory_zone("example.com", "IN"))
  2457. self.assertTrue(self.xfr._is_memory_zone("example2.com", "IN"))
  2458. self.assertFalse(self.xfr._is_memory_zone("example3.com", "IN"))
  2459. self.assertFalse(self.xfr._is_memory_zone("example.com", "CH"))
  2460. def test_class_filetype(self):
  2461. # omitting the class should have it default to what is in the
  2462. # specfile for Auth.
  2463. AuthConfigData = isc.config.config_data.ConfigData(
  2464. isc.config.module_spec_from_file(xfrin.AUTH_SPECFILE_LOCATION))
  2465. del self.config['datasources'][0]['class']
  2466. self.xfr._set_memory_zones(self.config, AuthConfigData)
  2467. self.assertTrue(self.xfr._is_memory_zone("example.com", "IN"))
  2468. self.assertTrue(self.xfr._is_memory_zone("example2.com", "IN"))
  2469. self.assertFalse(self.xfr._is_memory_zone("example3.com", "IN"))
  2470. self.assertTrue(self.xfr._is_memory_zone("example.com", "CH"))
  2471. def raise_interrupt():
  2472. raise KeyboardInterrupt()
  2473. def raise_ccerror():
  2474. raise isc.cc.session.SessionError('test error')
  2475. def raise_exception():
  2476. raise Exception('test exception')
  2477. class TestMain(unittest.TestCase):
  2478. def setUp(self):
  2479. MockXfrin.check_command_hook = None
  2480. def tearDown(self):
  2481. MockXfrin.check_command_hook = None
  2482. def test_startup(self):
  2483. main(MockXfrin, False)
  2484. def test_startup_interrupt(self):
  2485. MockXfrin.check_command_hook = raise_interrupt
  2486. main(MockXfrin, False)
  2487. def test_startup_ccerror(self):
  2488. MockXfrin.check_command_hook = raise_ccerror
  2489. main(MockXfrin, False)
  2490. def test_startup_generalerror(self):
  2491. MockXfrin.check_command_hook = raise_exception
  2492. main(MockXfrin, False)
  2493. class TestXfrinProcessMockCC:
  2494. def __init__(self):
  2495. self.config = []
  2496. class TestXfrinProcessMockCCSession:
  2497. def __init__(self):
  2498. self.send_called = False
  2499. self.send_called_correctly = False
  2500. self.recv_called = False
  2501. self.recv_called_correctly = False
  2502. def group_sendmsg(self, msg, module):
  2503. self.send_called = True
  2504. if module == 'Auth' and msg['command'][0] == 'loadzone':
  2505. self.send_called_correctly = True
  2506. seq = "random-e068c2de26d760f20cf10afc4b87ef0f"
  2507. else:
  2508. seq = None
  2509. return seq
  2510. def group_recvmsg(self, message, seq):
  2511. self.recv_called = True
  2512. if message == False and seq == "random-e068c2de26d760f20cf10afc4b87ef0f":
  2513. self.recv_called_correctly = True
  2514. # return values are ignored
  2515. return (None, None)
  2516. class TestXfrinProcess(unittest.TestCase):
  2517. """
  2518. Some tests for the xfrin_process function. This replaces the
  2519. XfrinConnection class with itself, so we can emulate whatever behavior we
  2520. might want.
  2521. Currently only tests for retry if IXFR fails.
  2522. """
  2523. def setUp(self):
  2524. """
  2525. Backs up the original class implementation so it can be restored
  2526. and places our own version in place of the constructor.
  2527. Also sets up several internal variables to watch what happens.
  2528. """
  2529. self._module_cc = TestXfrinProcessMockCC()
  2530. self._send_cc_session = TestXfrinProcessMockCCSession()
  2531. # This will hold a "log" of what transfers were attempted.
  2532. self.__transfers = []
  2533. # This will "log" if failures or successes happened.
  2534. self.__published = []
  2535. # How many connections were created.
  2536. self.__created_connections = 0
  2537. def __get_connection(self, *args):
  2538. """
  2539. Provides a "connection". To mock the connection and see what it is
  2540. asked to do, we pretend to be the connection.
  2541. """
  2542. self.__created_connections += 1
  2543. return self
  2544. def connect_to_master(self):
  2545. """
  2546. Part of pretending to be the connection. It pretends it connected
  2547. correctly every time.
  2548. """
  2549. return True
  2550. def do_xfrin(self, check_soa, request_type):
  2551. """
  2552. Part of pretending to be the connection. It looks what answer should
  2553. be answered now and logs what request happened.
  2554. """
  2555. self.__transfers.append(request_type)
  2556. ret = self.__rets[0]
  2557. self.__rets = self.__rets[1:]
  2558. return ret
  2559. def zone_str(self):
  2560. """
  2561. Part of pretending to be the connection. It provides the logging name
  2562. of zone.
  2563. """
  2564. return "example.org/IN"
  2565. def publish_xfrin_news(self, zone_name, rrclass, ret):
  2566. """
  2567. Part of pretending to be the server as well. This just logs the
  2568. success/failure of the previous operation.
  2569. """
  2570. if ret == XFRIN_OK:
  2571. xfrin._do_auth_loadzone(self, zone_name, rrclass)
  2572. self.__published.append(ret)
  2573. def close(self):
  2574. """
  2575. Part of pretending to be the connection.
  2576. """
  2577. pass
  2578. def init_socket(self):
  2579. """
  2580. Part of pretending to be the connection.
  2581. """
  2582. pass
  2583. def __do_test(self, rets, transfers, request_type):
  2584. """
  2585. Do the actual test. The request type, prepared sucesses/failures
  2586. and expected sequence of transfers is passed to specify what test
  2587. should happen.
  2588. """
  2589. self.__rets = rets
  2590. published = rets[-1]
  2591. xfrin.process_xfrin(self, XfrinRecorder(), Name("example.org."),
  2592. RRClass.IN(), None, None, None, True, None,
  2593. request_type, self.__get_connection)
  2594. self.assertEqual([], self.__rets)
  2595. self.assertEqual(transfers, self.__transfers)
  2596. # Create a connection for each attempt
  2597. self.assertEqual(len(transfers), self.__created_connections)
  2598. self.assertEqual([published], self.__published)
  2599. def test_ixfr_ok(self):
  2600. """
  2601. Everything OK the first time, over IXFR.
  2602. """
  2603. self.__do_test([XFRIN_OK], [RRType.IXFR()], RRType.IXFR())
  2604. # Check there was loadzone command
  2605. self.assertTrue(self._send_cc_session.send_called)
  2606. self.assertTrue(self._send_cc_session.send_called_correctly)
  2607. self.assertTrue(self._send_cc_session.recv_called)
  2608. self.assertTrue(self._send_cc_session.recv_called_correctly)
  2609. def test_axfr_ok(self):
  2610. """
  2611. Everything OK the first time, over AXFR.
  2612. """
  2613. self.__do_test([XFRIN_OK], [RRType.AXFR()], RRType.AXFR())
  2614. def test_axfr_fail(self):
  2615. """
  2616. The transfer failed over AXFR. Should not be retried (we don't expect
  2617. to fail on AXFR, but succeed on IXFR and we didn't use IXFR in the first
  2618. place for some reason.
  2619. """
  2620. self.__do_test([XFRIN_FAIL], [RRType.AXFR()], RRType.AXFR())
  2621. def test_ixfr_fallback(self):
  2622. """
  2623. The transfer fails over IXFR, but suceeds over AXFR. It should fall back
  2624. to it and say everything is OK.
  2625. """
  2626. self.__do_test([XFRIN_FAIL, XFRIN_OK], [RRType.IXFR(), RRType.AXFR()],
  2627. RRType.IXFR())
  2628. def test_ixfr_fail(self):
  2629. """
  2630. The transfer fails both over IXFR and AXFR. It should report failure
  2631. (only once) and should try both before giving up.
  2632. """
  2633. self.__do_test([XFRIN_FAIL, XFRIN_FAIL],
  2634. [RRType.IXFR(), RRType.AXFR()], RRType.IXFR())
  2635. def test_send_loadzone(self):
  2636. """
  2637. Check the loadzone command is sent after successful transfer.
  2638. """
  2639. self.__do_test([XFRIN_OK], [RRType.IXFR()], RRType.IXFR())
  2640. self.assertTrue(self._send_cc_session.send_called)
  2641. self.assertTrue(self._send_cc_session.send_called_correctly)
  2642. self.assertTrue(self._send_cc_session.recv_called)
  2643. self.assertTrue(self._send_cc_session.recv_called_correctly)
  2644. class TestFormatting(unittest.TestCase):
  2645. # If the formatting functions are moved to a more general library
  2646. # (ticket #1379), these tests should be moved with them.
  2647. def test_format_zone_str(self):
  2648. self.assertEqual("example.com/IN",
  2649. format_zone_str(isc.dns.Name("example.com"),
  2650. isc.dns.RRClass("IN")))
  2651. self.assertEqual("example.com/CH",
  2652. format_zone_str(isc.dns.Name("example.com"),
  2653. isc.dns.RRClass("CH")))
  2654. self.assertEqual("example.org/IN",
  2655. format_zone_str(isc.dns.Name("example.org"),
  2656. isc.dns.RRClass("IN")))
  2657. def test_format_addrinfo(self):
  2658. # This test may need to be updated if the input type is changed,
  2659. # right now it is a nested tuple:
  2660. # (family, sockettype, (address, port))
  2661. # of which sockettype is ignored
  2662. self.assertEqual("192.0.2.1:53",
  2663. format_addrinfo((socket.AF_INET, socket.SOCK_STREAM,
  2664. ("192.0.2.1", 53))))
  2665. self.assertEqual("192.0.2.2:53",
  2666. format_addrinfo((socket.AF_INET, socket.SOCK_STREAM,
  2667. ("192.0.2.2", 53))))
  2668. self.assertEqual("192.0.2.1:54",
  2669. format_addrinfo((socket.AF_INET, socket.SOCK_STREAM,
  2670. ("192.0.2.1", 54))))
  2671. self.assertEqual("[2001:db8::1]:53",
  2672. format_addrinfo((socket.AF_INET6, socket.SOCK_STREAM,
  2673. ("2001:db8::1", 53))))
  2674. self.assertEqual("[2001:db8::2]:53",
  2675. format_addrinfo((socket.AF_INET6, socket.SOCK_STREAM,
  2676. ("2001:db8::2", 53))))
  2677. self.assertEqual("[2001:db8::1]:54",
  2678. format_addrinfo((socket.AF_INET6, socket.SOCK_STREAM,
  2679. ("2001:db8::1", 54))))
  2680. self.assertEqual("/some/file",
  2681. format_addrinfo((socket.AF_UNIX, socket.SOCK_STREAM,
  2682. "/some/file")))
  2683. # second element of passed tuple should be ignored
  2684. self.assertEqual("192.0.2.1:53",
  2685. format_addrinfo((socket.AF_INET, None,
  2686. ("192.0.2.1", 53))))
  2687. self.assertEqual("192.0.2.1:53",
  2688. format_addrinfo((socket.AF_INET, "Just some string",
  2689. ("192.0.2.1", 53))))
  2690. self.assertRaises(TypeError, format_addrinfo, 1)
  2691. self.assertRaises(TypeError, format_addrinfo,
  2692. (socket.AF_INET, "asdf"))
  2693. self.assertRaises(TypeError, format_addrinfo,
  2694. (socket.AF_INET, "asdf", ()))
  2695. class TestXfrinTransferStats(unittest.TestCase):
  2696. def setUp(self):
  2697. # replace time.time with a steadily increasing fake one
  2698. self.orig_time_time = time.time
  2699. time.time = get_fake_time_time()
  2700. self.stats = XfrinTransferStats()
  2701. def tearDown(self):
  2702. time.time = self.orig_time_time
  2703. def zero_check(self):
  2704. # Checks whether all counters are zero
  2705. self.assertEqual(0, self.stats.message_count)
  2706. self.assertEqual(0, self.stats.axfr_rr_count)
  2707. self.assertEqual(0, self.stats.byte_count)
  2708. self.assertEqual(0, self.stats.ixfr_changeset_count)
  2709. self.assertEqual(0, self.stats.ixfr_deletion_count)
  2710. self.assertEqual(0, self.stats.ixfr_addition_count)
  2711. def test_init(self):
  2712. self.zero_check()
  2713. self.assertIsNone(self.stats._end_time)
  2714. def test_get_running_time(self):
  2715. self.assertIsNone(self.stats._end_time)
  2716. runtime = self.stats.get_running_time()
  2717. self.assertIsNotNone(self.stats._end_time)
  2718. self.assertGreater(runtime, 0)
  2719. # make sure a second get does not change anything
  2720. runtime2 = self.stats.get_running_time()
  2721. self.assertEqual(runtime, runtime2)
  2722. # And that no counters have been modified
  2723. self.zero_check()
  2724. def test_bytes_per_second(self):
  2725. zbps = self.stats.get_bytes_per_second()
  2726. self.assertEqual(0, zbps)
  2727. self.stats._start_time = 1
  2728. self.stats._end_time = 2
  2729. self.stats.byte_count += 4
  2730. zbps = self.stats.get_bytes_per_second()
  2731. self.assertEqual(4, zbps)
  2732. self.stats._start_time = float(1)
  2733. self.stats._end_time = float(11)
  2734. self.assertEqual(10, self.stats.get_running_time())
  2735. self.stats.byte_count = 1234
  2736. zbps = self.stats.get_bytes_per_second()
  2737. self.assertEqual(123.4, zbps)
  2738. # if for some reason the runtime is 0, depending
  2739. # on whether bytes have actually been seen, bps is either
  2740. # 0 or 'infinite'
  2741. self.stats._end_time = self.stats._start_time
  2742. zbps = self.stats.get_bytes_per_second()
  2743. self.assertEqual(float("inf"), zbps)
  2744. self.stats.byte_count = 0
  2745. zbps = self.stats.get_bytes_per_second()
  2746. self.assertEqual(0, zbps)
  2747. if __name__== "__main__":
  2748. try:
  2749. isc.log.resetUnitTestRootLogger()
  2750. unittest.main()
  2751. except KeyboardInterrupt as e:
  2752. print(e)