xfrin_test.py 157 KB

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