query.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """Talk to a DNS server."""
  17. from __future__ import generators
  18. import errno
  19. import select
  20. import socket
  21. import struct
  22. import sys
  23. import time
  24. import dns.exception
  25. import dns.inet
  26. import dns.name
  27. import dns.message
  28. import dns.rcode
  29. import dns.rdataclass
  30. import dns.rdatatype
  31. from ._compat import long, string_types, PY3
  32. if PY3:
  33. select_error = OSError
  34. else:
  35. select_error = select.error
  36. # Function used to create a socket. Can be overridden if needed in special
  37. # situations.
  38. socket_factory = socket.socket
  39. class UnexpectedSource(dns.exception.DNSException):
  40. """A DNS query response came from an unexpected address or port."""
  41. class BadResponse(dns.exception.FormError):
  42. """A DNS query response does not respond to the question asked."""
  43. class TransferError(dns.exception.DNSException):
  44. """A zone transfer response got a non-zero rcode."""
  45. def __init__(self, rcode):
  46. message = 'Zone transfer error: %s' % dns.rcode.to_text(rcode)
  47. super(TransferError, self).__init__(message)
  48. self.rcode = rcode
  49. def _compute_expiration(timeout):
  50. if timeout is None:
  51. return None
  52. else:
  53. return time.time() + timeout
  54. # This module can use either poll() or select() as the "polling backend".
  55. #
  56. # A backend function takes an fd, bools for readability, writablity, and
  57. # error detection, and a timeout.
  58. def _poll_for(fd, readable, writable, error, timeout):
  59. """Poll polling backend."""
  60. event_mask = 0
  61. if readable:
  62. event_mask |= select.POLLIN
  63. if writable:
  64. event_mask |= select.POLLOUT
  65. if error:
  66. event_mask |= select.POLLERR
  67. pollable = select.poll()
  68. pollable.register(fd, event_mask)
  69. if timeout:
  70. event_list = pollable.poll(long(timeout * 1000))
  71. else:
  72. event_list = pollable.poll()
  73. return bool(event_list)
  74. def _select_for(fd, readable, writable, error, timeout):
  75. """Select polling backend."""
  76. rset, wset, xset = [], [], []
  77. if readable:
  78. rset = [fd]
  79. if writable:
  80. wset = [fd]
  81. if error:
  82. xset = [fd]
  83. if timeout is None:
  84. (rcount, wcount, xcount) = select.select(rset, wset, xset)
  85. else:
  86. (rcount, wcount, xcount) = select.select(rset, wset, xset, timeout)
  87. return bool((rcount or wcount or xcount))
  88. def _wait_for(fd, readable, writable, error, expiration):
  89. # Use the selected polling backend to wait for any of the specified
  90. # events. An "expiration" absolute time is converted into a relative
  91. # timeout.
  92. done = False
  93. while not done:
  94. if expiration is None:
  95. timeout = None
  96. else:
  97. timeout = expiration - time.time()
  98. if timeout <= 0.0:
  99. raise dns.exception.Timeout
  100. try:
  101. if not _polling_backend(fd, readable, writable, error, timeout):
  102. raise dns.exception.Timeout
  103. except select_error as e:
  104. if e.args[0] != errno.EINTR:
  105. raise e
  106. done = True
  107. def _set_polling_backend(fn):
  108. # Internal API. Do not use.
  109. global _polling_backend
  110. _polling_backend = fn
  111. if hasattr(select, 'poll'):
  112. # Prefer poll() on platforms that support it because it has no
  113. # limits on the maximum value of a file descriptor (plus it will
  114. # be more efficient for high values).
  115. _polling_backend = _poll_for
  116. else:
  117. _polling_backend = _select_for
  118. def _wait_for_readable(s, expiration):
  119. _wait_for(s, True, False, True, expiration)
  120. def _wait_for_writable(s, expiration):
  121. _wait_for(s, False, True, True, expiration)
  122. def _addresses_equal(af, a1, a2):
  123. # Convert the first value of the tuple, which is a textual format
  124. # address into binary form, so that we are not confused by different
  125. # textual representations of the same address
  126. try:
  127. n1 = dns.inet.inet_pton(af, a1[0])
  128. n2 = dns.inet.inet_pton(af, a2[0])
  129. except dns.exception.SyntaxError:
  130. return False
  131. return n1 == n2 and a1[1:] == a2[1:]
  132. def _matches_destination(af, from_address, destination, ignore_unexpected):
  133. # Check that from_address is appropriate for a response to a query
  134. # sent to destination.
  135. if not destination:
  136. return True
  137. if _addresses_equal(af, from_address, destination) or (
  138. dns.inet.is_multicast(destination[0]) and from_address[1:] == destination[1:]
  139. ):
  140. return True
  141. elif ignore_unexpected:
  142. return False
  143. raise UnexpectedSource('got a response from '
  144. '%s instead of %s' % (from_address,
  145. destination))
  146. def _destination_and_source(af, where, port, source, source_port):
  147. # Apply defaults and compute destination and source tuples
  148. # suitable for use in connect(), sendto(), or bind().
  149. if af is None:
  150. try:
  151. af = dns.inet.af_for_address(where)
  152. except Exception:
  153. af = dns.inet.AF_INET
  154. if af == dns.inet.AF_INET:
  155. destination = (where, port)
  156. if source is not None or source_port != 0:
  157. if source is None:
  158. source = '0.0.0.0'
  159. source = (source, source_port)
  160. elif af == dns.inet.AF_INET6:
  161. destination = (where, port, 0, 0)
  162. if source is not None or source_port != 0:
  163. if source is None:
  164. source = '::'
  165. source = (source, source_port, 0, 0)
  166. return (af, destination, source)
  167. def send_udp(sock, what, destination, expiration=None):
  168. """Send a DNS message to the specified UDP socket.
  169. *sock*, a ``socket``.
  170. *what*, a ``binary`` or ``dns.message.Message``, the message to send.
  171. *destination*, a destination tuple appropriate for the address family
  172. of the socket, specifying where to send the query.
  173. *expiration*, a ``float`` or ``None``, the absolute time at which
  174. a timeout exception should be raised. If ``None``, no timeout will
  175. occur.
  176. Returns an ``(int, float)`` tuple of bytes sent and the sent time.
  177. """
  178. if isinstance(what, dns.message.Message):
  179. what = what.to_wire()
  180. _wait_for_writable(sock, expiration)
  181. sent_time = time.time()
  182. n = sock.sendto(what, destination)
  183. return (n, sent_time)
  184. def receive_udp(sock, destination, expiration=None,
  185. ignore_unexpected=False, one_rr_per_rrset=False,
  186. keyring=None, request_mac=b'', ignore_trailing=False,
  187. ignore_errors=False,
  188. query=None):
  189. """Read a DNS message from a UDP socket.
  190. *sock*, a ``socket``.
  191. *destination*, a destination tuple appropriate for the address family
  192. of the socket, specifying where the associated query was sent.
  193. *expiration*, a ``float`` or ``None``, the absolute time at which
  194. a timeout exception should be raised. If ``None``, no timeout will
  195. occur.
  196. *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from
  197. unexpected sources.
  198. *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
  199. RRset.
  200. *keyring*, a ``dict``, the keyring to use for TSIG.
  201. *request_mac*, a ``binary``, the MAC of the request (for TSIG).
  202. *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
  203. junk at end of the received message.
  204. *ignore_errors*, a ``bool``. If various format errors or response
  205. mismatches occur, ignore them and keep listening for a valid response.
  206. The default is ``False``.
  207. *query*, a ``dns.message.Message`` or ``None``. If not ``None`` and
  208. *ignore_errors* is ``True``, check that the received message is a response
  209. to this query, and if not keep listening for a valid response.
  210. Raises if the message is malformed, if network errors occur, of if
  211. there is a timeout.
  212. Returns a ``dns.message.Message`` object.
  213. """
  214. wire = b''
  215. while 1:
  216. _wait_for_readable(sock, expiration)
  217. (wire, from_address) = sock.recvfrom(65535)
  218. if not _matches_destination(
  219. sock.family, from_address, destination, ignore_unexpected
  220. ):
  221. continue
  222. received_time = time.time()
  223. try:
  224. r = dns.message.from_wire(wire, keyring=keyring, request_mac=request_mac,
  225. one_rr_per_rrset=one_rr_per_rrset,
  226. ignore_trailing=ignore_trailing)
  227. except dns.message.Truncated as e:
  228. # If we got Truncated and not FORMERR, we at least got the header with TC
  229. # set, and very likely the question section, so we'll re-raise if the
  230. # message seems to be a response as we need to know when truncation happens.
  231. # We need to check that it seems to be a response as we don't want a random
  232. # injected message with TC set to cause us to bail out.
  233. if (
  234. ignore_errors
  235. and query is not None
  236. and not query.is_response(e.message())
  237. ):
  238. continue
  239. else:
  240. raise
  241. except Exception:
  242. if ignore_errors:
  243. continue
  244. else:
  245. raise
  246. if ignore_errors and query is not None and not query.is_response(r):
  247. continue
  248. if destination:
  249. return (r, received_time)
  250. else:
  251. return (r, received_time, from_address)
  252. def udp(q, where, timeout=None, port=53, af=None, source=None, source_port=0,
  253. ignore_unexpected=False, one_rr_per_rrset=False, ignore_trailing=False,
  254. ignore_errors=False):
  255. """Return the response obtained after sending a query via UDP.
  256. *q*, a ``dns.message.Message``, the query to send
  257. *where*, a ``text`` containing an IPv4 or IPv6 address, where
  258. to send the message.
  259. *timeout*, a ``float`` or ``None``, the number of seconds to wait before the
  260. query times out. If ``None``, the default, wait forever.
  261. *port*, an ``int``, the port send the message to. The default is 53.
  262. *af*, an ``int``, the address family to use. The default is ``None``,
  263. which causes the address family to use to be inferred from the form of
  264. *where*. If the inference attempt fails, AF_INET is used. This
  265. parameter is historical; you need never set it.
  266. *source*, a ``text`` containing an IPv4 or IPv6 address, specifying
  267. the source address. The default is the wildcard address.
  268. *source_port*, an ``int``, the port from which to send the message.
  269. The default is 0.
  270. *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from
  271. unexpected sources.
  272. *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
  273. RRset.
  274. *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
  275. junk at end of the received message.
  276. *ignore_errors*, a ``bool``. If various format errors or response
  277. mismatches occur, ignore them and keep listening for a valid response.
  278. The default is ``False``.
  279. Returns a ``dns.message.Message``.
  280. """
  281. wire = q.to_wire()
  282. (af, destination, source) = _destination_and_source(af, where, port,
  283. source, source_port)
  284. s = socket_factory(af, socket.SOCK_DGRAM, 0)
  285. received_time = None
  286. sent_time = None
  287. try:
  288. expiration = _compute_expiration(timeout)
  289. s.setblocking(0)
  290. if source is not None:
  291. s.bind(source)
  292. (_, sent_time) = send_udp(s, wire, destination, expiration)
  293. (r, received_time) = receive_udp(s, destination, expiration,
  294. ignore_unexpected, one_rr_per_rrset,
  295. q.keyring, q.mac, ignore_trailing,
  296. ignore_errors, q)
  297. finally:
  298. if sent_time is None or received_time is None:
  299. response_time = 0
  300. else:
  301. response_time = received_time - sent_time
  302. s.close()
  303. r.time = response_time
  304. # We don't need to check q.is_response() if we are in ignore_errors mode
  305. # as receive_udp() will have checked it.
  306. if not (ignore_errors or q.is_response(r)):
  307. raise BadResponse
  308. return r
  309. def _net_read(sock, count, expiration):
  310. """Read the specified number of bytes from sock. Keep trying until we
  311. either get the desired amount, or we hit EOF.
  312. A Timeout exception will be raised if the operation is not completed
  313. by the expiration time.
  314. """
  315. s = b''
  316. while count > 0:
  317. _wait_for_readable(sock, expiration)
  318. n = sock.recv(count)
  319. if n == b'':
  320. raise EOFError
  321. count = count - len(n)
  322. s = s + n
  323. return s
  324. def _net_write(sock, data, expiration):
  325. """Write the specified data to the socket.
  326. A Timeout exception will be raised if the operation is not completed
  327. by the expiration time.
  328. """
  329. current = 0
  330. l = len(data)
  331. while current < l:
  332. _wait_for_writable(sock, expiration)
  333. current += sock.send(data[current:])
  334. def send_tcp(sock, what, expiration=None):
  335. """Send a DNS message to the specified TCP socket.
  336. *sock*, a ``socket``.
  337. *what*, a ``binary`` or ``dns.message.Message``, the message to send.
  338. *expiration*, a ``float`` or ``None``, the absolute time at which
  339. a timeout exception should be raised. If ``None``, no timeout will
  340. occur.
  341. Returns an ``(int, float)`` tuple of bytes sent and the sent time.
  342. """
  343. if isinstance(what, dns.message.Message):
  344. what = what.to_wire()
  345. l = len(what)
  346. # copying the wire into tcpmsg is inefficient, but lets us
  347. # avoid writev() or doing a short write that would get pushed
  348. # onto the net
  349. tcpmsg = struct.pack("!H", l) + what
  350. _wait_for_writable(sock, expiration)
  351. sent_time = time.time()
  352. _net_write(sock, tcpmsg, expiration)
  353. return (len(tcpmsg), sent_time)
  354. def receive_tcp(sock, expiration=None, one_rr_per_rrset=False,
  355. keyring=None, request_mac=b'', ignore_trailing=False):
  356. """Read a DNS message from a TCP socket.
  357. *sock*, a ``socket``.
  358. *expiration*, a ``float`` or ``None``, the absolute time at which
  359. a timeout exception should be raised. If ``None``, no timeout will
  360. occur.
  361. *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
  362. RRset.
  363. *keyring*, a ``dict``, the keyring to use for TSIG.
  364. *request_mac*, a ``binary``, the MAC of the request (for TSIG).
  365. *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
  366. junk at end of the received message.
  367. Raises if the message is malformed, if network errors occur, of if
  368. there is a timeout.
  369. Returns a ``dns.message.Message`` object.
  370. """
  371. ldata = _net_read(sock, 2, expiration)
  372. (l,) = struct.unpack("!H", ldata)
  373. wire = _net_read(sock, l, expiration)
  374. received_time = time.time()
  375. r = dns.message.from_wire(wire, keyring=keyring, request_mac=request_mac,
  376. one_rr_per_rrset=one_rr_per_rrset,
  377. ignore_trailing=ignore_trailing)
  378. return (r, received_time)
  379. def _connect(s, address):
  380. try:
  381. s.connect(address)
  382. except socket.error:
  383. (ty, v) = sys.exc_info()[:2]
  384. if hasattr(v, 'errno'):
  385. v_err = v.errno
  386. else:
  387. v_err = v[0]
  388. if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
  389. raise v
  390. def tcp(q, where, timeout=None, port=53, af=None, source=None, source_port=0,
  391. one_rr_per_rrset=False, ignore_trailing=False):
  392. """Return the response obtained after sending a query via TCP.
  393. *q*, a ``dns.message.Message``, the query to send
  394. *where*, a ``text`` containing an IPv4 or IPv6 address, where
  395. to send the message.
  396. *timeout*, a ``float`` or ``None``, the number of seconds to wait before the
  397. query times out. If ``None``, the default, wait forever.
  398. *port*, an ``int``, the port send the message to. The default is 53.
  399. *af*, an ``int``, the address family to use. The default is ``None``,
  400. which causes the address family to use to be inferred from the form of
  401. *where*. If the inference attempt fails, AF_INET is used. This
  402. parameter is historical; you need never set it.
  403. *source*, a ``text`` containing an IPv4 or IPv6 address, specifying
  404. the source address. The default is the wildcard address.
  405. *source_port*, an ``int``, the port from which to send the message.
  406. The default is 0.
  407. *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
  408. RRset.
  409. *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
  410. junk at end of the received message.
  411. Returns a ``dns.message.Message``.
  412. """
  413. wire = q.to_wire()
  414. (af, destination, source) = _destination_and_source(af, where, port,
  415. source, source_port)
  416. s = socket_factory(af, socket.SOCK_STREAM, 0)
  417. begin_time = None
  418. received_time = None
  419. try:
  420. expiration = _compute_expiration(timeout)
  421. s.setblocking(0)
  422. begin_time = time.time()
  423. if source is not None:
  424. s.bind(source)
  425. _connect(s, destination)
  426. send_tcp(s, wire, expiration)
  427. (r, received_time) = receive_tcp(s, expiration, one_rr_per_rrset,
  428. q.keyring, q.mac, ignore_trailing)
  429. finally:
  430. if begin_time is None or received_time is None:
  431. response_time = 0
  432. else:
  433. response_time = received_time - begin_time
  434. s.close()
  435. r.time = response_time
  436. if not q.is_response(r):
  437. raise BadResponse
  438. return r
  439. def xfr(where, zone, rdtype=dns.rdatatype.AXFR, rdclass=dns.rdataclass.IN,
  440. timeout=None, port=53, keyring=None, keyname=None, relativize=True,
  441. af=None, lifetime=None, source=None, source_port=0, serial=0,
  442. use_udp=False, keyalgorithm=dns.tsig.default_algorithm):
  443. """Return a generator for the responses to a zone transfer.
  444. *where*. If the inference attempt fails, AF_INET is used. This
  445. parameter is historical; you need never set it.
  446. *zone*, a ``dns.name.Name`` or ``text``, the name of the zone to transfer.
  447. *rdtype*, an ``int`` or ``text``, the type of zone transfer. The
  448. default is ``dns.rdatatype.AXFR``. ``dns.rdatatype.IXFR`` can be
  449. used to do an incremental transfer instead.
  450. *rdclass*, an ``int`` or ``text``, the class of the zone transfer.
  451. The default is ``dns.rdataclass.IN``.
  452. *timeout*, a ``float``, the number of seconds to wait for each
  453. response message. If None, the default, wait forever.
  454. *port*, an ``int``, the port send the message to. The default is 53.
  455. *keyring*, a ``dict``, the keyring to use for TSIG.
  456. *keyname*, a ``dns.name.Name`` or ``text``, the name of the TSIG
  457. key to use.
  458. *relativize*, a ``bool``. If ``True``, all names in the zone will be
  459. relativized to the zone origin. It is essential that the
  460. relativize setting matches the one specified to
  461. ``dns.zone.from_xfr()`` if using this generator to make a zone.
  462. *af*, an ``int``, the address family to use. The default is ``None``,
  463. which causes the address family to use to be inferred from the form of
  464. *where*. If the inference attempt fails, AF_INET is used. This
  465. parameter is historical; you need never set it.
  466. *lifetime*, a ``float``, the total number of seconds to spend
  467. doing the transfer. If ``None``, the default, then there is no
  468. limit on the time the transfer may take.
  469. *source*, a ``text`` containing an IPv4 or IPv6 address, specifying
  470. the source address. The default is the wildcard address.
  471. *source_port*, an ``int``, the port from which to send the message.
  472. The default is 0.
  473. *serial*, an ``int``, the SOA serial number to use as the base for
  474. an IXFR diff sequence (only meaningful if *rdtype* is
  475. ``dns.rdatatype.IXFR``).
  476. *use_udp*, a ``bool``. If ``True``, use UDP (only meaningful for IXFR).
  477. *keyalgorithm*, a ``dns.name.Name`` or ``text``, the TSIG algorithm to use.
  478. Raises on errors, and so does the generator.
  479. Returns a generator of ``dns.message.Message`` objects.
  480. """
  481. if isinstance(zone, string_types):
  482. zone = dns.name.from_text(zone)
  483. if isinstance(rdtype, string_types):
  484. rdtype = dns.rdatatype.from_text(rdtype)
  485. q = dns.message.make_query(zone, rdtype, rdclass)
  486. if rdtype == dns.rdatatype.IXFR:
  487. rrset = dns.rrset.from_text(zone, 0, 'IN', 'SOA',
  488. '. . %u 0 0 0 0' % serial)
  489. q.authority.append(rrset)
  490. if keyring is not None:
  491. q.use_tsig(keyring, keyname, algorithm=keyalgorithm)
  492. wire = q.to_wire()
  493. (af, destination, source) = _destination_and_source(af, where, port,
  494. source, source_port)
  495. if use_udp:
  496. if rdtype != dns.rdatatype.IXFR:
  497. raise ValueError('cannot do a UDP AXFR')
  498. s = socket_factory(af, socket.SOCK_DGRAM, 0)
  499. else:
  500. s = socket_factory(af, socket.SOCK_STREAM, 0)
  501. s.setblocking(0)
  502. if source is not None:
  503. s.bind(source)
  504. expiration = _compute_expiration(lifetime)
  505. _connect(s, destination)
  506. l = len(wire)
  507. if use_udp:
  508. _wait_for_writable(s, expiration)
  509. s.send(wire)
  510. else:
  511. tcpmsg = struct.pack("!H", l) + wire
  512. _net_write(s, tcpmsg, expiration)
  513. done = False
  514. delete_mode = True
  515. expecting_SOA = False
  516. soa_rrset = None
  517. if relativize:
  518. origin = zone
  519. oname = dns.name.empty
  520. else:
  521. origin = None
  522. oname = zone
  523. tsig_ctx = None
  524. first = True
  525. while not done:
  526. mexpiration = _compute_expiration(timeout)
  527. if mexpiration is None or mexpiration > expiration:
  528. mexpiration = expiration
  529. if use_udp:
  530. _wait_for_readable(s, expiration)
  531. (wire, from_address) = s.recvfrom(65535)
  532. else:
  533. ldata = _net_read(s, 2, mexpiration)
  534. (l,) = struct.unpack("!H", ldata)
  535. wire = _net_read(s, l, mexpiration)
  536. is_ixfr = (rdtype == dns.rdatatype.IXFR)
  537. r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac,
  538. xfr=True, origin=origin, tsig_ctx=tsig_ctx,
  539. multi=True, first=first,
  540. one_rr_per_rrset=is_ixfr)
  541. rcode = r.rcode()
  542. if rcode != dns.rcode.NOERROR:
  543. raise TransferError(rcode)
  544. tsig_ctx = r.tsig_ctx
  545. first = False
  546. answer_index = 0
  547. if soa_rrset is None:
  548. if not r.answer or r.answer[0].name != oname:
  549. raise dns.exception.FormError(
  550. "No answer or RRset not for qname")
  551. rrset = r.answer[0]
  552. if rrset.rdtype != dns.rdatatype.SOA:
  553. raise dns.exception.FormError("first RRset is not an SOA")
  554. answer_index = 1
  555. soa_rrset = rrset.copy()
  556. if rdtype == dns.rdatatype.IXFR:
  557. if soa_rrset[0].serial <= serial:
  558. #
  559. # We're already up-to-date.
  560. #
  561. done = True
  562. else:
  563. expecting_SOA = True
  564. #
  565. # Process SOAs in the answer section (other than the initial
  566. # SOA in the first message).
  567. #
  568. for rrset in r.answer[answer_index:]:
  569. if done:
  570. raise dns.exception.FormError("answers after final SOA")
  571. if rrset.rdtype == dns.rdatatype.SOA and rrset.name == oname:
  572. if expecting_SOA:
  573. if rrset[0].serial != serial:
  574. raise dns.exception.FormError(
  575. "IXFR base serial mismatch")
  576. expecting_SOA = False
  577. elif rdtype == dns.rdatatype.IXFR:
  578. delete_mode = not delete_mode
  579. #
  580. # If this SOA RRset is equal to the first we saw then we're
  581. # finished. If this is an IXFR we also check that we're seeing
  582. # the record in the expected part of the response.
  583. #
  584. if rrset == soa_rrset and \
  585. (rdtype == dns.rdatatype.AXFR or
  586. (rdtype == dns.rdatatype.IXFR and delete_mode)):
  587. done = True
  588. elif expecting_SOA:
  589. #
  590. # We made an IXFR request and are expecting another
  591. # SOA RR, but saw something else, so this must be an
  592. # AXFR response.
  593. #
  594. rdtype = dns.rdatatype.AXFR
  595. expecting_SOA = False
  596. if done and q.keyring and not r.had_tsig:
  597. raise dns.exception.FormError("missing TSIG")
  598. yield r
  599. s.close()