xfrin_test.py 150 KB

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