xfrin_test.py 110 KB

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