xfrin_test.py 137 KB

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