xfrin_test.py 135 KB

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