notify_out.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. # Copyright (C) 2010-2012 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 select
  16. import sys
  17. import random
  18. import socket
  19. import threading
  20. import time
  21. import errno
  22. from isc.datasrc import sqlite3_ds
  23. from isc.datasrc import DataSourceClient
  24. from isc.net import addr
  25. import isc
  26. from isc.log_messages.notify_out_messages import *
  27. from isc.statistics.dns import Counters
  28. from isc.util.address_formatter import AddressFormatter
  29. logger = isc.log.Logger("notify_out")
  30. # there used to be a printed message if this import failed, but if
  31. # we can't import we should not start anyway, and logging an error
  32. # is a bad idea since the logging system is most likely not
  33. # initialized yet. see trac ticket #1103
  34. from isc.dns import *
  35. ZONE_NEW_DATA_READY_CMD = 'zone_new_data_ready'
  36. ZONE_XFRIN_FAILED = 'zone_xfrin_failed'
  37. _MAX_NOTIFY_NUM = 30
  38. _MAX_NOTIFY_TRY_NUM = 5
  39. _EVENT_READ = 1
  40. _EVENT_TIMEOUT = 2
  41. _NOTIFY_TIMEOUT = 1
  42. # define the rcode for parsing notify reply message
  43. _REPLY_OK = 0
  44. _BAD_QUERY_ID = 1
  45. _BAD_QUERY_NAME = 2
  46. _BAD_OPCODE = 3
  47. _BAD_QR = 4
  48. _BAD_REPLY_PACKET = 5
  49. SOCK_DATA = b's'
  50. # borrowed from xfrin.py @ #1298. We should eventually unify it.
  51. def format_zone_str(zone_name, zone_class):
  52. """Helper function to format a zone name and class as a string of
  53. the form '<name>/<class>'.
  54. Parameters:
  55. zone_name (isc.dns.Name) name to format
  56. zone_class (isc.dns.RRClass) class to format
  57. """
  58. return zone_name.to_text() + '/' + str(zone_class)
  59. class NotifyOutDataSourceError(Exception):
  60. """An exception raised when data source error happens within notify out.
  61. This exception is expected to be caught within the notify_out module.
  62. """
  63. pass
  64. class ZoneNotifyInfo:
  65. '''This class keeps track of notify-out information for one zone.'''
  66. def __init__(self, zone_name_, class_):
  67. self._notify_current = None
  68. self._slave_index = 0
  69. self._sock = None
  70. self.notify_slaves = []
  71. self.zone_name = zone_name_
  72. self.zone_class = class_
  73. self.notify_msg_id = 0
  74. # Absolute time for next notify reply. When the zone is preparing for
  75. # sending notify message, notify_timeout_ is set to now, that means
  76. # the first sending is triggered by the 'Timeout' mechanism.
  77. self.notify_timeout = None
  78. self.notify_try_num = 0 # Notify times sending to one target.
  79. def set_next_notify_target(self):
  80. if self._slave_index < (len(self.notify_slaves) - 1):
  81. self._slave_index += 1
  82. self._notify_current = self.notify_slaves[self._slave_index]
  83. else:
  84. self._notify_current = None
  85. def prepare_notify_out(self):
  86. '''Set notify timeout time to now'''
  87. self.notify_timeout = time.time()
  88. self.notify_try_num = 0
  89. self._slave_index = 0
  90. if len(self.notify_slaves) > 0:
  91. self._notify_current = self.notify_slaves[0]
  92. def finish_notify_out(self):
  93. if self._sock:
  94. self._sock.close()
  95. self._sock = None
  96. self.notify_timeout = None
  97. def create_socket(self, dest_addr):
  98. self._sock = socket.socket(addr.IPAddr(dest_addr).family,
  99. socket.SOCK_DGRAM)
  100. return self._sock
  101. def get_socket(self):
  102. return self._sock
  103. def get_current_notify_target(self):
  104. return self._notify_current
  105. class NotifyOut:
  106. '''This class is used to handle notify logic for all zones(sending
  107. notify message to its slaves). notify service can be started by
  108. calling dispatcher(), and it can be stopped by calling shutdown()
  109. in another thread. '''
  110. def __init__(self, datasrc_file, verbose=True):
  111. self._notify_infos = {} # key is (zone_name, zone_class)
  112. self._waiting_zones = []
  113. self._notifying_zones = []
  114. self._serving = False
  115. self._read_sock, self._write_sock = socket.socketpair()
  116. self._read_sock.setblocking(False)
  117. self.notify_num = 0 # the count of in progress notifies
  118. self._verbose = verbose
  119. self._lock = threading.Lock()
  120. self._db_file = datasrc_file
  121. self._init_notify_out(datasrc_file)
  122. # Use nonblock event to eliminate busy loop
  123. # If there are no notifying zones, clear the event bit and wait.
  124. self._nonblock_event = threading.Event()
  125. self._counters = Counters()
  126. def _init_notify_out(self, datasrc_file):
  127. '''Get all the zones name and its notify target's address.
  128. TODO, currently the zones are got by going through the zone
  129. table in database. There should be a better way to get them
  130. and also the setting 'also_notify', and there should be one
  131. mechanism to cover the changed datasrc.
  132. '''
  133. self._db_file = datasrc_file
  134. for zone_name, zone_class in sqlite3_ds.get_zones_info(datasrc_file):
  135. zone_id = (zone_name, zone_class)
  136. self._notify_infos[zone_id] = ZoneNotifyInfo(zone_name, zone_class)
  137. slaves = self._get_notify_slaves_from_ns(Name(zone_name),
  138. RRClass(zone_class))
  139. for item in slaves:
  140. self._notify_infos[zone_id].notify_slaves.append((item, 53))
  141. def add_slave(self, address, port):
  142. for zone_name, zone_class in sqlite3_ds.get_zones_info(self._db_file):
  143. zone_id = (zone_name, zone_class)
  144. if zone_id in self._notify_infos:
  145. self._notify_infos[zone_id].notify_slaves.append((address, port))
  146. def send_notify(self, zone_name, zone_class='IN'):
  147. '''Send notify to one zone's slaves, this function is
  148. the only interface for class NotifyOut which can be called
  149. by other object.
  150. Internally, the function only set the zone's notify-reply
  151. timeout to now, then notify message will be sent out.
  152. Returns False if the zone/class is not known, True if it is
  153. (even if there are no slaves)'''
  154. if zone_name[len(zone_name) - 1] != '.':
  155. zone_name += '.'
  156. zone_id = (zone_name, zone_class)
  157. if zone_id not in self._notify_infos:
  158. return False
  159. # Has no slave servers, skip it.
  160. if (len(self._notify_infos[zone_id].notify_slaves) <= 0):
  161. return True
  162. with self._lock:
  163. if (self.notify_num >= _MAX_NOTIFY_NUM) or (zone_id in self._notifying_zones):
  164. if zone_id not in self._waiting_zones:
  165. self._waiting_zones.append(zone_id)
  166. else:
  167. self._notify_infos[zone_id].prepare_notify_out()
  168. self.notify_num += 1
  169. self._notifying_zones.append(zone_id)
  170. if not self._nonblock_event.isSet():
  171. self._nonblock_event.set()
  172. return True
  173. def _dispatcher(self, started_event):
  174. started_event.set() # Let the master know we are alive already
  175. while self._serving:
  176. replied_zones, not_replied_zones = self._wait_for_notify_reply()
  177. for name_ in replied_zones:
  178. self._zone_notify_handler(replied_zones[name_], _EVENT_READ)
  179. for name_ in not_replied_zones:
  180. if not_replied_zones[name_].notify_timeout <= time.time():
  181. self._zone_notify_handler(not_replied_zones[name_],
  182. _EVENT_TIMEOUT)
  183. def dispatcher(self, daemon=False):
  184. """Spawns a thread that will handle notify related events.
  185. If one zone get the notify reply before timeout, call the
  186. handle to process the reply. If one zone can't get the notify
  187. before timeout, call the handler to resend notify or notify
  188. next slave.
  189. The thread can be stopped by calling shutdown().
  190. Returns the thread object to anyone interested.
  191. """
  192. if self._serving:
  193. raise RuntimeError(
  194. 'Dispatcher already running, tried to start twice')
  195. # Prepare for launch
  196. self._serving = True
  197. started_event = threading.Event()
  198. # Start
  199. self._thread = threading.Thread(target=self._dispatcher,
  200. args=[started_event])
  201. if daemon:
  202. self._thread.daemon = daemon
  203. self._thread.start()
  204. # Wait for it to get started
  205. started_event.wait()
  206. # Return it to anyone listening
  207. return self._thread
  208. def shutdown(self):
  209. """Stop the dispatcher() thread. Blocks until the thread stopped."""
  210. if not self._serving:
  211. raise RuntimeError('Tried to stop while not running')
  212. # Ask it to stop
  213. self._serving = False
  214. if not self._nonblock_event.isSet():
  215. # set self._nonblock_event to stop waiting for new notifying zones.
  216. self._nonblock_event.set()
  217. self._write_sock.send(SOCK_DATA) # make self._read_sock be readable.
  218. # Wait for it
  219. self._thread.join()
  220. # Clean up
  221. self._write_sock.close()
  222. self._write_sock = None
  223. self._read_sock.close()
  224. self._read_sock = None
  225. self._thread = None
  226. def _get_rdata_data(self, rr):
  227. return rr[7].strip()
  228. def _get_notify_slaves_from_ns(self, zone_name, zone_class):
  229. '''Get all NS records, then remove the primary master from ns rrset,
  230. then use the name in NS record rdata part to get the a/aaaa records
  231. in the same zone. the targets listed in a/aaaa record rdata are treated
  232. as the notify slaves.
  233. Note: this is the simplest way to get the address of slaves,
  234. but not correct, it can't handle the delegation slaves, or the CNAME
  235. and DNAME logic.
  236. TODO. the function should be provided by one library.
  237. '''
  238. # Prepare data source client. This should eventually be moved to
  239. # an earlier stage of initialization and also support multiple
  240. # data sources.
  241. datasrc_config = '{ "database_file": "' + self._db_file + '"}'
  242. try:
  243. ds_client = DataSourceClient('sqlite3', datasrc_config)
  244. except isc.datasrc.Error as ex:
  245. logger.error(NOTIFY_OUT_DATASRC_ACCESS_FAILURE, ex)
  246. return []
  247. result, finder = ds_client.find_zone(zone_name)
  248. if result is not DataSourceClient.SUCCESS:
  249. logger.error(NOTIFY_OUT_DATASRC_ZONE_NOT_FOUND,
  250. format_zone_str(zone_name, zone_class))
  251. return []
  252. result, ns_rrset, _ = finder.find(zone_name, RRType.NS)
  253. if result is not finder.SUCCESS or ns_rrset is None:
  254. logger.warn(NOTIFY_OUT_ZONE_NO_NS,
  255. format_zone_str(zone_name, zone_class))
  256. return []
  257. result, soa_rrset, _ = finder.find(zone_name, RRType.SOA)
  258. if result is not finder.SUCCESS or soa_rrset is None or \
  259. soa_rrset.get_rdata_count() != 1:
  260. logger.warn(NOTIFY_OUT_ZONE_BAD_SOA,
  261. format_zone_str(zone_name, zone_class))
  262. return [] # broken zone anyway, stop here.
  263. soa_mname = Name(soa_rrset.get_rdata()[0].to_text().split(' ')[0])
  264. addrs = []
  265. for ns_rdata in ns_rrset.get_rdata():
  266. ns_name = Name(ns_rdata.to_text())
  267. if soa_mname == ns_name:
  268. continue
  269. ns_result, ns_finder = ds_client.find_zone(ns_name)
  270. if ns_result is DataSourceClient.SUCCESS or \
  271. ns_result is DataSourceClient.PARTIALMATCH:
  272. result, rrset, _ = ns_finder.find(ns_name, RRType.A)
  273. if result is ns_finder.SUCCESS and rrset is not None:
  274. addrs.extend([a.to_text() for a in rrset.get_rdata()])
  275. result, rrset, _ = ns_finder.find(ns_name, RRType.AAAA)
  276. if result is ns_finder.SUCCESS and rrset is not None:
  277. addrs.extend([aaaa.to_text()
  278. for aaaa in rrset.get_rdata()])
  279. return addrs
  280. def _prepare_select_info(self):
  281. '''
  282. Prepare the information for select(), returned
  283. value is one tuple
  284. (block_timeout, valid_socks, notifying_zones)
  285. block_timeout: the timeout for select()
  286. valid_socks: sockets list for waiting ready reading.
  287. notifying_zones: the zones which have been triggered
  288. for notify.
  289. '''
  290. valid_socks = []
  291. notifying_zones = {}
  292. min_timeout = None
  293. for info in self._notify_infos:
  294. sock = self._notify_infos[info].get_socket()
  295. if sock:
  296. valid_socks.append(sock)
  297. # If a non null timeout is specified notify has been scheduled
  298. # (in which case socket is still None) or sent (with a valid
  299. # socket). In either case we need add the zone to notifying_zones
  300. # so that we can invoke the appropriate event for the zone after
  301. # select.
  302. tmp_timeout = self._notify_infos[info].notify_timeout
  303. if tmp_timeout is not None:
  304. notifying_zones[info] = self._notify_infos[info]
  305. if min_timeout is not None:
  306. if tmp_timeout < min_timeout:
  307. min_timeout = tmp_timeout
  308. else:
  309. min_timeout = tmp_timeout
  310. block_timeout = None
  311. if min_timeout is not None:
  312. block_timeout = min_timeout - time.time()
  313. if block_timeout < 0:
  314. block_timeout = 0
  315. return (block_timeout, valid_socks, notifying_zones)
  316. def _wait_for_notify_reply(self):
  317. '''
  318. Receive notify replies in specified time. returned value
  319. is one tuple:(replied_zones, not_replied_zones). ({}, {}) is
  320. returned if shutdown() was called.
  321. replied_zones: the zones which receive notify reply.
  322. not_replied_zones: the zones which haven't got notify reply.
  323. '''
  324. (block_timeout, valid_socks, notifying_zones) = \
  325. self._prepare_select_info()
  326. # This is None only during some tests
  327. if self._read_sock is not None:
  328. valid_socks.append(self._read_sock)
  329. # Currently, there is no notifying zones, waiting for zones to send notify
  330. if block_timeout is None:
  331. self._nonblock_event.clear()
  332. self._nonblock_event.wait()
  333. # has new notifying zone, check immediately
  334. block_timeout = 0
  335. try:
  336. r_fds, w, e = select.select(valid_socks, [], [], block_timeout)
  337. except select.error as err:
  338. if err.args[0] != errno.EINTR:
  339. return {}, {}
  340. if self._read_sock in r_fds: # user has called shutdown()
  341. try:
  342. # Noone should write anything else than shutdown
  343. assert self._read_sock.recv(len(SOCK_DATA)) == SOCK_DATA
  344. return {}, {}
  345. except socket.error as e: # Workaround around rare linux bug
  346. if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
  347. raise
  348. not_replied_zones = {}
  349. replied_zones = {}
  350. for info in notifying_zones:
  351. if notifying_zones[info].get_socket() in r_fds:
  352. replied_zones[info] = notifying_zones[info]
  353. else:
  354. not_replied_zones[info] = notifying_zones[info]
  355. return replied_zones, not_replied_zones
  356. def _zone_notify_handler(self, zone_notify_info, event_type):
  357. """Notify handler for one zone.
  358. For the event type of _EVENT_READ, this method reads a new notify
  359. response message from the corresponding socket. If it succeeds
  360. and the response is the expected one, it will send another notify
  361. to the next slave for the zone (if any) or the next zone (if any)
  362. waiting for its turn of sending notifies.
  363. In the case of _EVENT_TIMEOUT, or if the read fails or the response
  364. is not an expected one in the case of _EVENT_READ, this method will
  365. resend the notify request to the same slave up to _MAX_NOTIFY_TRY_NUM
  366. times. If it reaches the max, it will swith to the next slave or
  367. the next zone like the successful case above.
  368. The first notify message is always triggered by the event
  369. "_EVENT_TIMEOUT" since when one zone prepares to notify its slaves,
  370. its notify_timeout is set to now, which is used to trigger sending
  371. notify message when dispatcher() scanning zones.
  372. Parameters:
  373. zone_notify_info(ZoneNotifyInfo): the notify context for the event
  374. event_type(int): either _EVENT_READ or _EVENT_TIMEOUT constant
  375. """
  376. tgt = zone_notify_info.get_current_notify_target()
  377. if event_type == _EVENT_READ:
  378. # Note: _get_notify_reply() should also check the response's
  379. # source address (see #2924). When it's done the following code
  380. # should also be adjusted a bit.
  381. reply = self._get_notify_reply(zone_notify_info.get_socket(), tgt)
  382. if reply is not None:
  383. if (self._handle_notify_reply(zone_notify_info, reply, tgt) ==
  384. _REPLY_OK):
  385. self._notify_next_target(zone_notify_info)
  386. else:
  387. assert event_type == _EVENT_TIMEOUT
  388. if zone_notify_info.notify_try_num > 0:
  389. logger.info(NOTIFY_OUT_TIMEOUT, AddressFormatter(tgt))
  390. tgt = zone_notify_info.get_current_notify_target()
  391. if tgt:
  392. zone_notify_info.notify_try_num += 1
  393. if zone_notify_info.notify_try_num > _MAX_NOTIFY_TRY_NUM:
  394. logger.warn(NOTIFY_OUT_RETRY_EXCEEDED, AddressFormatter(tgt),
  395. _MAX_NOTIFY_TRY_NUM)
  396. self._notify_next_target(zone_notify_info)
  397. else:
  398. # set exponential backoff according to rfc1996 section 3.6
  399. retry_timeout = (_NOTIFY_TIMEOUT *
  400. pow(2, zone_notify_info.notify_try_num))
  401. zone_notify_info.notify_timeout = time.time() + retry_timeout
  402. self._send_notify_message_udp(zone_notify_info, tgt)
  403. def _notify_next_target(self, zone_notify_info):
  404. '''Notify next address for the same zone. If all the targets
  405. has been notified, notify the first zone in waiting list. '''
  406. zone_notify_info.notify_try_num = 0
  407. zone_notify_info.set_next_notify_target()
  408. tgt = zone_notify_info.get_current_notify_target()
  409. if not tgt:
  410. zone_notify_info.finish_notify_out()
  411. with self._lock:
  412. self.notify_num -= 1
  413. self._notifying_zones.remove((zone_notify_info.zone_name,
  414. zone_notify_info.zone_class))
  415. # trigger notify out for waiting zones
  416. if len(self._waiting_zones) > 0:
  417. zone_id = self._waiting_zones.pop(0)
  418. self._notify_infos[zone_id].prepare_notify_out()
  419. self.notify_num += 1
  420. self._notifying_zones.append(zone_id)
  421. if not self._nonblock_event.isSet():
  422. self._nonblock_event.set()
  423. def _send_notify_message_udp(self, zone_notify_info, addrinfo):
  424. msg, qid = self._create_notify_message(
  425. Name(zone_notify_info.zone_name),
  426. RRClass(zone_notify_info.zone_class))
  427. render = MessageRenderer()
  428. render.set_length_limit(512)
  429. msg.to_wire(render)
  430. zone_notify_info.notify_msg_id = qid
  431. try:
  432. sock = zone_notify_info.create_socket(addrinfo[0])
  433. sock.sendto(render.get_data(), 0, addrinfo)
  434. # count notifying by IPv4 or IPv6 for statistics
  435. if zone_notify_info.get_socket().family == socket.AF_INET:
  436. self._counters.inc('zones',
  437. zone_notify_info.zone_class,
  438. zone_notify_info.zone_name,
  439. 'notifyoutv4')
  440. elif zone_notify_info.get_socket().family == socket.AF_INET6:
  441. self._counters.inc('zones',
  442. zone_notify_info.zone_class,
  443. zone_notify_info.zone_name,
  444. 'notifyoutv6')
  445. logger.info(NOTIFY_OUT_SENDING_NOTIFY, AddressFormatter(addrinfo))
  446. except (socket.error, addr.InvalidAddress) as err:
  447. logger.error(NOTIFY_OUT_SOCKET_ERROR, AddressFormatter(addrinfo),
  448. err)
  449. return False
  450. except addr.InvalidAddress as iae:
  451. logger.error(NOTIFY_OUT_INVALID_ADDRESS,
  452. AddressFormatter(addrinfo), iae)
  453. return False
  454. return True
  455. def _create_notify_message(self, zone_name, zone_class):
  456. msg = Message(Message.RENDER)
  457. qid = random.randint(0, 0xFFFF)
  458. msg.set_qid(qid)
  459. msg.set_opcode(Opcode.NOTIFY)
  460. msg.set_rcode(Rcode.NOERROR)
  461. msg.set_header_flag(Message.HEADERFLAG_AA)
  462. msg.add_question(Question(zone_name, zone_class, RRType.SOA))
  463. msg.add_rrset(Message.SECTION_ANSWER, self._get_zone_soa(zone_name,
  464. zone_class))
  465. return msg, qid
  466. def _get_zone_soa(self, zone_name, zone_class):
  467. # We create (and soon drop) the data source client here because
  468. # clients should be thread specific. We could let the main thread
  469. # loop (_dispatcher) create and retain the client in order to avoid
  470. # the overhead when we generalize the interface (and we may also
  471. # revisit the design of notify_out more substantially anyway).
  472. datasrc_config = '{ "database_file": "' + self._db_file + '"}'
  473. result, finder = DataSourceClient('sqlite3',
  474. datasrc_config).find_zone(zone_name)
  475. if result is not DataSourceClient.SUCCESS:
  476. raise NotifyOutDataSourceError('_get_zone_soa: Zone ' +
  477. zone_name.to_text() + '/' +
  478. zone_class.to_text() + ' not found')
  479. result, soa_rrset, _ = finder.find(zone_name, RRType.SOA)
  480. if result is not finder.SUCCESS or soa_rrset is None or \
  481. soa_rrset.get_rdata_count() != 1:
  482. raise NotifyOutDataSourceError('_get_zone_soa: Zone ' +
  483. zone_name.to_text() + '/' +
  484. zone_class.to_text() +
  485. ' is broken: no valid SOA found')
  486. return soa_rrset
  487. def _handle_notify_reply(self, zone_notify_info, msg_data, from_addr):
  488. """Parse the notify reply message.
  489. rcode will not be checked here; if we get the response
  490. from the slave, it means the slave got the notify.
  491. """
  492. msg = Message(Message.PARSE)
  493. try:
  494. msg.from_wire(msg_data)
  495. if not msg.get_header_flag(Message.HEADERFLAG_QR):
  496. logger.warn(NOTIFY_OUT_REPLY_QR_NOT_SET,
  497. AddressFormatter(from_addr))
  498. return _BAD_QR
  499. if msg.get_qid() != zone_notify_info.notify_msg_id:
  500. logger.warn(NOTIFY_OUT_REPLY_BAD_QID,
  501. AddressFormatter(from_addr), msg.get_qid(),
  502. zone_notify_info.notify_msg_id)
  503. return _BAD_QUERY_ID
  504. question = msg.get_question()[0]
  505. if question.get_name() != Name(zone_notify_info.zone_name):
  506. logger.warn(NOTIFY_OUT_REPLY_BAD_QUERY_NAME,
  507. AddressFormatter(from_addr),
  508. question.get_name().to_text(),
  509. Name(zone_notify_info.zone_name).to_text())
  510. return _BAD_QUERY_NAME
  511. if msg.get_opcode() != Opcode.NOTIFY:
  512. logger.warn(NOTIFY_OUT_REPLY_BAD_OPCODE,
  513. AddressFormatter(from_addr),
  514. msg.get_opcode().to_text())
  515. return _BAD_OPCODE
  516. except Exception as err:
  517. # We don't care what exception, just report it?
  518. logger.error(NOTIFY_OUT_REPLY_UNCAUGHT_EXCEPTION, err)
  519. return _BAD_REPLY_PACKET
  520. logger.debug(logger.DBGLVL_TRACE_BASIC, NOTIFY_OUT_REPLY_RECEIVED,
  521. zone_notify_info.zone_name, zone_notify_info.zone_class,
  522. AddressFormatter(from_addr), msg.get_rcode())
  523. return _REPLY_OK
  524. def _get_notify_reply(self, sock, tgt_addr):
  525. try:
  526. msg, addr = sock.recvfrom(512)
  527. except socket.error as err:
  528. logger.error(NOTIFY_OUT_SOCKET_RECV_ERROR,
  529. AddressFormatter(tgt_addr), err)
  530. return None
  531. return msg