xfrin_test.py 123 KB

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