xfrin_test.py 132 KB

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