xfrout.py.in 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. #!@PYTHON@
  2. # Copyright (C) 2010 Internet Systems Consortium.
  3. #
  4. # Permission to use, copy, modify, and distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  9. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  10. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  11. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  12. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  13. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  14. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  15. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. import sys; sys.path.append ('@@PYTHONPATH@@')
  17. import isc
  18. import isc.cc
  19. import threading
  20. import struct
  21. import signal
  22. from isc.datasrc import sqlite3_ds
  23. from socketserver import *
  24. import os
  25. from isc.config.ccsession import *
  26. from isc.cc import SessionError, SessionTimeout
  27. from isc.notify import notify_out
  28. import isc.util.process
  29. import socket
  30. import select
  31. import errno
  32. from optparse import OptionParser, OptionValueError
  33. from isc.util import socketserver_mixin
  34. from isc.log_messages.xfrout_messages import *
  35. isc.log.init("b10-xfrout")
  36. logger = isc.log.Logger("xfrout")
  37. try:
  38. from libutil_io_python import *
  39. from pydnspp import *
  40. except ImportError as e:
  41. # C++ loadable module may not be installed; even so the xfrout process
  42. # must keep running, so we warn about it and move forward.
  43. log.error(XFROUT_IMPORT, str(e))
  44. from isc.acl.acl import ACCEPT, REJECT, DROP, LoaderError
  45. from isc.acl.dns import REQUEST_LOADER
  46. isc.util.process.rename()
  47. class XfroutConfigError(Exception):
  48. """An exception indicating an error in updating xfrout configuration.
  49. This exception is raised when the xfrout process encouters an error in
  50. handling configuration updates. Not all syntax error can be caught
  51. at the module-CC layer, so xfrout needs to (explicitly or implicitly)
  52. validate the given configuration data itself. When it finds an error
  53. it raises this exception (either directly or by converting an exception
  54. from other modules) as a unified error in configuration.
  55. """
  56. pass
  57. def init_paths():
  58. global SPECFILE_PATH
  59. global AUTH_SPECFILE_PATH
  60. global UNIX_SOCKET_FILE
  61. if "B10_FROM_BUILD" in os.environ:
  62. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/xfrout"
  63. AUTH_SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/auth"
  64. if "B10_FROM_SOURCE_LOCALSTATEDIR" in os.environ:
  65. UNIX_SOCKET_FILE = os.environ["B10_FROM_SOURCE_LOCALSTATEDIR"] + \
  66. "/auth_xfrout_conn"
  67. else:
  68. UNIX_SOCKET_FILE = os.environ["B10_FROM_BUILD"] + "/auth_xfrout_conn"
  69. else:
  70. PREFIX = "@prefix@"
  71. DATAROOTDIR = "@datarootdir@"
  72. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  73. AUTH_SPECFILE_PATH = SPECFILE_PATH
  74. if "BIND10_XFROUT_SOCKET_FILE" in os.environ:
  75. UNIX_SOCKET_FILE = os.environ["BIND10_XFROUT_SOCKET_FILE"]
  76. else:
  77. UNIX_SOCKET_FILE = "@@LOCALSTATEDIR@@/auth_xfrout_conn"
  78. init_paths()
  79. SPECFILE_LOCATION = SPECFILE_PATH + "/xfrout.spec"
  80. AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + os.sep + "auth.spec"
  81. MAX_TRANSFERS_OUT = 10
  82. VERBOSE_MODE = False
  83. # tsig sign every N axfr packets.
  84. TSIG_SIGN_EVERY_NTH = 96
  85. XFROUT_MAX_MESSAGE_SIZE = 65535
  86. def get_rrset_len(rrset):
  87. """Returns the wire length of the given RRset"""
  88. bytes = bytearray()
  89. rrset.to_wire(bytes)
  90. return len(bytes)
  91. class XfroutSession():
  92. def __init__(self, sock_fd, request_data, server, tsig_key_ring, remote,
  93. default_acl, zone_config):
  94. self._sock_fd = sock_fd
  95. self._request_data = request_data
  96. self._server = server
  97. self._tsig_key_ring = tsig_key_ring
  98. self._tsig_ctx = None
  99. self._tsig_len = 0
  100. self._remote = remote
  101. self._acl = default_acl
  102. self._zone_config = zone_config
  103. self.handle()
  104. def create_tsig_ctx(self, tsig_record, tsig_key_ring):
  105. return TSIGContext(tsig_record.get_name(), tsig_record.get_rdata().get_algorithm(),
  106. tsig_key_ring)
  107. def handle(self):
  108. ''' Handle a xfrout query, send xfrout response '''
  109. try:
  110. self.dns_xfrout_start(self._sock_fd, self._request_data)
  111. #TODO, avoid catching all exceptions
  112. except Exception as e:
  113. logger.error(XFROUT_HANDLE_QUERY_ERROR, e)
  114. pass
  115. os.close(self._sock_fd)
  116. def _check_request_tsig(self, msg, request_data):
  117. ''' If request has a tsig record, perform tsig related checks '''
  118. tsig_record = msg.get_tsig_record()
  119. if tsig_record is not None:
  120. self._tsig_len = tsig_record.get_length()
  121. self._tsig_ctx = self.create_tsig_ctx(tsig_record, self._tsig_key_ring)
  122. tsig_error = self._tsig_ctx.verify(tsig_record, request_data)
  123. if tsig_error != TSIGError.NOERROR:
  124. return Rcode.NOTAUTH()
  125. return Rcode.NOERROR()
  126. def _parse_query_message(self, mdata):
  127. ''' parse query message to [socket,message]'''
  128. #TODO, need to add parseHeader() in case the message header is invalid
  129. try:
  130. msg = Message(Message.PARSE)
  131. Message.from_wire(msg, mdata)
  132. except Exception as err: # Exception is too broad
  133. logger.error(XFROUT_PARSE_QUERY_ERROR, err)
  134. return Rcode.FORMERR(), None
  135. # TSIG related checks
  136. rcode = self._check_request_tsig(msg, mdata)
  137. if rcode == Rcode.NOERROR():
  138. # ACL checks
  139. zone_name = msg.get_question()[0].get_name()
  140. zone_class = msg.get_question()[0].get_class()
  141. acl = self._get_transfer_acl(zone_name, zone_class)
  142. acl_result = acl.execute(
  143. isc.acl.dns.RequestContext(self._remote,
  144. msg.get_tsig_record()))
  145. if acl_result == DROP:
  146. logger.info(XFROUT_QUERY_DROPPED, zone_name, zone_class,
  147. self._remote[0], self._remote[1])
  148. return None, None
  149. elif acl_result == REJECT:
  150. logger.info(XFROUT_QUERY_REJECTED, zone_name, zone_class,
  151. self._remote[0], self._remote[1])
  152. return Rcode.REFUSED(), msg
  153. return rcode, msg
  154. def _get_transfer_acl(self, zone_name, zone_class):
  155. '''Return the ACL that should be applied for a given zone.
  156. The zone is identified by a tuple of name and RR class.
  157. If a per zone configuration for the zone exists and contains
  158. transfer_acl, that ACL will be used; otherwise, the default
  159. ACL will be used.
  160. '''
  161. # Internally zone names are managed in lower cased label characters,
  162. # so we first need to convert the name.
  163. zone_name_lower = Name(zone_name.to_text(), True)
  164. config_key = (zone_class.to_text(), zone_name_lower.to_text())
  165. if config_key in self._zone_config and \
  166. 'transfer_acl' in self._zone_config[config_key]:
  167. return self._zone_config[config_key]['transfer_acl']
  168. return self._acl
  169. def _get_query_zone_name(self, msg):
  170. question = msg.get_question()[0]
  171. return question.get_name().to_text()
  172. def _get_query_zone_class(self, msg):
  173. question = msg.get_question()[0]
  174. return question.get_class().to_text()
  175. def _send_data(self, sock_fd, data):
  176. size = len(data)
  177. total_count = 0
  178. while total_count < size:
  179. count = os.write(sock_fd, data[total_count:])
  180. total_count += count
  181. def _send_message(self, sock_fd, msg, tsig_ctx=None):
  182. render = MessageRenderer()
  183. # As defined in RFC5936 section3.4, perform case-preserving name
  184. # compression for AXFR message.
  185. render.set_compress_mode(MessageRenderer.CASE_SENSITIVE)
  186. render.set_length_limit(XFROUT_MAX_MESSAGE_SIZE)
  187. # XXX Currently, python wrapper doesn't accept 'None' parameter in this case,
  188. # we should remove the if statement and use a universal interface later.
  189. if tsig_ctx is not None:
  190. msg.to_wire(render, tsig_ctx)
  191. else:
  192. msg.to_wire(render)
  193. header_len = struct.pack('H', socket.htons(render.get_length()))
  194. self._send_data(sock_fd, header_len)
  195. self._send_data(sock_fd, render.get_data())
  196. def _reply_query_with_error_rcode(self, msg, sock_fd, rcode_):
  197. if not msg:
  198. return # query message is invalid. send nothing back.
  199. msg.make_response()
  200. msg.set_rcode(rcode_)
  201. self._send_message(sock_fd, msg, self._tsig_ctx)
  202. def _zone_has_soa(self, zone):
  203. '''Judge if the zone has an SOA record.'''
  204. # In some sense, the SOA defines a zone.
  205. # If the current name server has authority for the
  206. # specific zone, we need to judge if the zone has an SOA record;
  207. # if not, we consider the zone has incomplete data, so xfrout can't
  208. # serve for it.
  209. if sqlite3_ds.get_zone_soa(zone, self._server.get_db_file()):
  210. return True
  211. return False
  212. def _zone_exist(self, zonename):
  213. '''Judge if the zone is configured by config manager.'''
  214. # Currently, if we find the zone in datasource successfully, we
  215. # consider the zone is configured, and the current name server has
  216. # authority for the specific zone.
  217. # TODO: should get zone's configuration from cfgmgr or other place
  218. # in future.
  219. return sqlite3_ds.zone_exist(zonename, self._server.get_db_file())
  220. def _check_xfrout_available(self, zone_name):
  221. '''Check if xfr request can be responsed.
  222. TODO, Get zone's configuration from cfgmgr or some other place
  223. eg. check allow_transfer setting,
  224. '''
  225. # If the current name server does not have authority for the
  226. # zone, xfrout can't serve for it, return rcode NOTAUTH.
  227. if not self._zone_exist(zone_name):
  228. return Rcode.NOTAUTH()
  229. # If we are an authoritative name server for the zone, but fail
  230. # to find the zone's SOA record in datasource, xfrout can't
  231. # provide zone transfer for it.
  232. if not self._zone_has_soa(zone_name):
  233. return Rcode.SERVFAIL()
  234. #TODO, check allow_transfer
  235. if not self._server.increase_transfers_counter():
  236. return Rcode.REFUSED()
  237. return Rcode.NOERROR()
  238. def dns_xfrout_start(self, sock_fd, msg_query):
  239. rcode_, msg = self._parse_query_message(msg_query)
  240. #TODO. create query message and parse header
  241. if rcode_ is None: # Dropped by ACL
  242. return
  243. elif rcode_ == Rcode.NOTAUTH() or rcode_ == Rcode.REFUSED():
  244. return self._reply_query_with_error_rcode(msg, sock_fd, rcode_)
  245. elif rcode_ != Rcode.NOERROR():
  246. return self._reply_query_with_error_rcode(msg, sock_fd,
  247. Rcode.FORMERR())
  248. zone_name = self._get_query_zone_name(msg)
  249. zone_class_str = self._get_query_zone_class(msg)
  250. # TODO: should we not also include class in the check?
  251. rcode_ = self._check_xfrout_available(zone_name)
  252. if rcode_ != Rcode.NOERROR():
  253. logger.info(XFROUT_AXFR_TRANSFER_FAILED, zone_name,
  254. zone_class_str, rcode_.to_text())
  255. return self._reply_query_with_error_rcode(msg, sock_fd, rcode_)
  256. try:
  257. logger.info(XFROUT_AXFR_TRANSFER_STARTED, zone_name, zone_class_str)
  258. self._reply_xfrout_query(msg, sock_fd, zone_name)
  259. except Exception as err:
  260. logger.error(XFROUT_AXFR_TRANSFER_ERROR, zone_name,
  261. zone_class_str, str(err))
  262. pass
  263. logger.info(XFROUT_AXFR_TRANSFER_DONE, zone_name, zone_class_str)
  264. self._server.decrease_transfers_counter()
  265. return
  266. def _clear_message(self, msg):
  267. qid = msg.get_qid()
  268. opcode = msg.get_opcode()
  269. rcode = msg.get_rcode()
  270. msg.clear(Message.RENDER)
  271. msg.set_qid(qid)
  272. msg.set_opcode(opcode)
  273. msg.set_rcode(rcode)
  274. msg.set_header_flag(Message.HEADERFLAG_AA)
  275. msg.set_header_flag(Message.HEADERFLAG_QR)
  276. return msg
  277. def _create_rrset_from_db_record(self, record):
  278. '''Create one rrset from one record of datasource, if the schema of record is changed,
  279. This function should be updated first.
  280. '''
  281. rrtype_ = RRType(record[5])
  282. rdata_ = Rdata(rrtype_, RRClass("IN"), " ".join(record[7:]))
  283. rrset_ = RRset(Name(record[2]), RRClass("IN"), rrtype_, RRTTL( int(record[4])))
  284. rrset_.add_rdata(rdata_)
  285. return rrset_
  286. def _send_message_with_last_soa(self, msg, sock_fd, rrset_soa, message_upper_len,
  287. count_since_last_tsig_sign):
  288. '''Add the SOA record to the end of message. If it can't be
  289. added, a new message should be created to send out the last soa .
  290. '''
  291. rrset_len = get_rrset_len(rrset_soa)
  292. if (count_since_last_tsig_sign == TSIG_SIGN_EVERY_NTH and
  293. message_upper_len + rrset_len >= XFROUT_MAX_MESSAGE_SIZE):
  294. # If tsig context exist, sign the packet with serial number TSIG_SIGN_EVERY_NTH
  295. self._send_message(sock_fd, msg, self._tsig_ctx)
  296. msg = self._clear_message(msg)
  297. elif (count_since_last_tsig_sign != TSIG_SIGN_EVERY_NTH and
  298. message_upper_len + rrset_len + self._tsig_len >= XFROUT_MAX_MESSAGE_SIZE):
  299. self._send_message(sock_fd, msg)
  300. msg = self._clear_message(msg)
  301. # If tsig context exist, sign the last packet
  302. msg.add_rrset(Message.SECTION_ANSWER, rrset_soa)
  303. self._send_message(sock_fd, msg, self._tsig_ctx)
  304. def _reply_xfrout_query(self, msg, sock_fd, zone_name):
  305. #TODO, there should be a better way to insert rrset.
  306. count_since_last_tsig_sign = TSIG_SIGN_EVERY_NTH
  307. msg.make_response()
  308. msg.set_header_flag(Message.HEADERFLAG_AA)
  309. soa_record = sqlite3_ds.get_zone_soa(zone_name, self._server.get_db_file())
  310. rrset_soa = self._create_rrset_from_db_record(soa_record)
  311. msg.add_rrset(Message.SECTION_ANSWER, rrset_soa)
  312. message_upper_len = get_rrset_len(rrset_soa) + self._tsig_len
  313. for rr_data in sqlite3_ds.get_zone_datas(zone_name, self._server.get_db_file()):
  314. if self._server._shutdown_event.is_set(): # Check if xfrout is shutdown
  315. logger.info(XFROUT_STOPPING)
  316. return
  317. # TODO: RRType.SOA() ?
  318. if RRType(rr_data[5]) == RRType("SOA"): #ignore soa record
  319. continue
  320. rrset_ = self._create_rrset_from_db_record(rr_data)
  321. # We calculate the maximum size of the RRset (i.e. the
  322. # size without compression) and use that to see if we
  323. # may have reached the limit
  324. rrset_len = get_rrset_len(rrset_)
  325. if message_upper_len + rrset_len < XFROUT_MAX_MESSAGE_SIZE:
  326. msg.add_rrset(Message.SECTION_ANSWER, rrset_)
  327. message_upper_len += rrset_len
  328. continue
  329. # If tsig context exist, sign every N packets
  330. if count_since_last_tsig_sign == TSIG_SIGN_EVERY_NTH:
  331. count_since_last_tsig_sign = 0
  332. self._send_message(sock_fd, msg, self._tsig_ctx)
  333. else:
  334. self._send_message(sock_fd, msg)
  335. count_since_last_tsig_sign += 1
  336. msg = self._clear_message(msg)
  337. msg.add_rrset(Message.SECTION_ANSWER, rrset_) # Add the rrset to the new message
  338. # Reserve tsig space for signed packet
  339. if count_since_last_tsig_sign == TSIG_SIGN_EVERY_NTH:
  340. message_upper_len = rrset_len + self._tsig_len
  341. else:
  342. message_upper_len = rrset_len
  343. self._send_message_with_last_soa(msg, sock_fd, rrset_soa, message_upper_len,
  344. count_since_last_tsig_sign)
  345. class UnixSockServer(socketserver_mixin.NoPollMixIn,
  346. ThreadingUnixStreamServer):
  347. '''The unix domain socket server which accept xfr query sent from auth server.'''
  348. def __init__(self, sock_file, handle_class, shutdown_event, config_data,
  349. cc):
  350. self._remove_unused_sock_file(sock_file)
  351. self._sock_file = sock_file
  352. socketserver_mixin.NoPollMixIn.__init__(self)
  353. ThreadingUnixStreamServer.__init__(self, sock_file, handle_class)
  354. self._shutdown_event = shutdown_event
  355. self._write_sock, self._read_sock = socket.socketpair()
  356. self._common_init()
  357. self._cc = cc
  358. self.update_config_data(config_data)
  359. def _common_init(self):
  360. self._lock = threading.Lock()
  361. self._transfers_counter = 0
  362. # These default values will probably get overwritten by the (same)
  363. # default value from the spec file. These are here just to make
  364. # sure and to make the default values in tests consistent.
  365. self._acl = REQUEST_LOADER.load('[{"action": "ACCEPT"}]')
  366. self._zone_config = {}
  367. def _receive_query_message(self, sock):
  368. ''' receive request message from sock'''
  369. # receive data length
  370. data_len = sock.recv(2)
  371. if not data_len:
  372. return None
  373. msg_len = struct.unpack('!H', data_len)[0]
  374. # receive data
  375. recv_size = 0
  376. msgdata = b''
  377. while recv_size < msg_len:
  378. data = sock.recv(msg_len - recv_size)
  379. if not data:
  380. return None
  381. recv_size += len(data)
  382. msgdata += data
  383. return msgdata
  384. def handle_request(self):
  385. ''' Enable server handle a request until shutdown or auth is closed.'''
  386. try:
  387. request, client_address = self.get_request()
  388. except socket.error:
  389. logger.error(XFROUT_FETCH_REQUEST_ERROR)
  390. return
  391. # Check self._shutdown_event to ensure the real shutdown comes.
  392. # Linux could trigger a spurious readable event on the _read_sock
  393. # due to a bug, so we need perform a double check.
  394. while not self._shutdown_event.is_set(): # Check if xfrout is shutdown
  395. try:
  396. (rlist, wlist, xlist) = select.select([self._read_sock, request], [], [])
  397. except select.error as e:
  398. if e.args[0] == errno.EINTR:
  399. (rlist, wlist, xlist) = ([], [], [])
  400. continue
  401. else:
  402. logger.error(XFROUT_SOCKET_SELECT_ERROR, str(e))
  403. break
  404. # self.server._shutdown_event will be set by now, if it is not a false
  405. # alarm
  406. if self._read_sock in rlist:
  407. continue
  408. try:
  409. self.process_request(request)
  410. except Exception as pre:
  411. log.error(XFROUT_PROCESS_REQUEST_ERROR, str(pre))
  412. break
  413. def _handle_request_noblock(self):
  414. """Override the function _handle_request_noblock(), it creates a new
  415. thread to handle requests for each auth"""
  416. td = threading.Thread(target=self.handle_request)
  417. td.setDaemon(True)
  418. td.start()
  419. def process_request(self, request):
  420. """Receive socket fd and query message from auth, then
  421. start a new thread to process the request."""
  422. sock_fd = recv_fd(request.fileno())
  423. if sock_fd < 0:
  424. # This may happen when one xfrout process try to connect to
  425. # xfrout unix socket server, to check whether there is another
  426. # xfrout running.
  427. if sock_fd == FD_COMM_ERROR:
  428. logger.error(XFROUT_RECEIVE_FILE_DESCRIPTOR_ERROR)
  429. return
  430. # receive request msg
  431. request_data = self._receive_query_message(request)
  432. if not request_data:
  433. return
  434. t = threading.Thread(target=self.finish_request,
  435. args = (sock_fd, request_data))
  436. if self.daemon_threads:
  437. t.daemon = True
  438. t.start()
  439. def _guess_remote(self, sock_fd):
  440. """
  441. Guess remote address and port of the socket. The sock_fd must be a
  442. socket
  443. """
  444. # This uses a trick. If the socket is IPv4 in reality and we pretend
  445. # it to be IPv6, it returns IPv4 address anyway. This doesn't seem
  446. # to care about the SOCK_STREAM parameter at all (which it really is,
  447. # except for testing)
  448. if socket.has_ipv6:
  449. sock = socket.fromfd(sock_fd, socket.AF_INET6, socket.SOCK_STREAM)
  450. else:
  451. # To make it work even on hosts without IPv6 support
  452. # (Any idea how to simulate this in test?)
  453. sock = socket.fromfd(sock_fd, socket.AF_INET, socket.SOCK_STREAM)
  454. return sock.getpeername()
  455. def finish_request(self, sock_fd, request_data):
  456. '''Finish one request by instantiating RequestHandlerClass.
  457. This method creates a XfroutSession object.
  458. '''
  459. self.RequestHandlerClass(sock_fd, request_data, self,
  460. self.tsig_key_ring,
  461. self._guess_remote(sock_fd), self._acl,
  462. self._zone_config)
  463. def _remove_unused_sock_file(self, sock_file):
  464. '''Try to remove the socket file. If the file is being used
  465. by one running xfrout process, exit from python.
  466. If it's not a socket file or nobody is listening
  467. , it will be removed. If it can't be removed, exit from python. '''
  468. if self._sock_file_in_use(sock_file):
  469. logger.error(XFROUT_UNIX_SOCKET_FILE_IN_USE, sock_file)
  470. sys.exit(0)
  471. else:
  472. if not os.path.exists(sock_file):
  473. return
  474. try:
  475. os.unlink(sock_file)
  476. except OSError as err:
  477. logger.error(XFROUT_REMOVE_OLD_UNIX_SOCKET_FILE_ERROR, sock_file, str(err))
  478. sys.exit(0)
  479. def _sock_file_in_use(self, sock_file):
  480. '''Check whether the socket file 'sock_file' exists and
  481. is being used by one running xfrout process. If it is,
  482. return True, or else return False. '''
  483. try:
  484. sock = socket.socket(socket.AF_UNIX)
  485. sock.connect(sock_file)
  486. except socket.error as err:
  487. return False
  488. else:
  489. return True
  490. def shutdown(self):
  491. self._write_sock.send(b"shutdown") #terminate the xfrout session thread
  492. super().shutdown() # call the shutdown() of class socketserver_mixin.NoPollMixIn
  493. try:
  494. os.unlink(self._sock_file)
  495. except Exception as e:
  496. logger.error(XFROUT_REMOVE_UNIX_SOCKET_FILE_ERROR, self._sock_file, str(e))
  497. pass
  498. def update_config_data(self, new_config):
  499. '''Apply the new config setting of xfrout module.
  500. Note: this method does not provide strong exception guarantee;
  501. if an exception is raised in the middle of parsing and building the
  502. given config data, the incomplete set of new configuration will
  503. remain. This should be fixed.
  504. '''
  505. logger.info(XFROUT_NEW_CONFIG)
  506. if 'transfer_acl' in new_config:
  507. try:
  508. self._acl = REQUEST_LOADER.load(new_config['transfer_acl'])
  509. except LoaderError as e:
  510. raise XfroutConfigError('Failed to parse transfer_acl: ' +
  511. str(e))
  512. zone_config = new_config.get('zone_config')
  513. if zone_config is not None:
  514. self._zone_config = self.__create_zone_config(zone_config)
  515. self._lock.acquire()
  516. self._max_transfers_out = new_config.get('transfers_out')
  517. self.set_tsig_key_ring(new_config.get('tsig_key_ring'))
  518. self._lock.release()
  519. logger.info(XFROUT_NEW_CONFIG_DONE)
  520. def __create_zone_config(self, zone_config_list):
  521. new_config = {}
  522. for zconf in zone_config_list:
  523. # convert the class, origin (name) pair. First build pydnspp
  524. # object to reject invalid input.
  525. zclass_str = zconf.get('class')
  526. if zclass_str is None:
  527. #zclass_str = 'IN' # temporary
  528. zclass_str = self._cc.get_default_value('zone_config/class')
  529. zclass = RRClass(zclass_str)
  530. zorigin = Name(zconf['origin'], True)
  531. config_key = (zclass.to_text(), zorigin.to_text())
  532. # reject duplicate config
  533. if config_key in new_config:
  534. raise XfroutConfigError('Duplicaet zone_config for ' +
  535. str(zorigin) + '/' + str(zclass))
  536. # create a new config entry, build any given (and known) config
  537. new_config[config_key] = {}
  538. if 'transfer_acl' in zconf:
  539. try:
  540. new_config[config_key]['transfer_acl'] = \
  541. REQUEST_LOADER.load(zconf['transfer_acl'])
  542. except LoaderError as e:
  543. raise XfroutConfigError('Failed to parse transfer_acl ' +
  544. 'for ' + zorigin.to_text() + '/' +
  545. zclass_str + ': ' + str(e))
  546. return new_config
  547. def set_tsig_key_ring(self, key_list):
  548. """Set the tsig_key_ring , given a TSIG key string list representation. """
  549. # XXX add values to configure zones/tsig options
  550. self.tsig_key_ring = TSIGKeyRing()
  551. # If key string list is empty, create a empty tsig_key_ring
  552. if not key_list:
  553. return
  554. for key_item in key_list:
  555. try:
  556. self.tsig_key_ring.add(TSIGKey(key_item))
  557. except InvalidParameter as ipe:
  558. logger.error(XFROUT_BAD_TSIG_KEY_STRING, str(key_item))
  559. def get_db_file(self):
  560. file, is_default = self._cc.get_remote_config_value("Auth", "database_file")
  561. # this too should be unnecessary, but currently the
  562. # 'from build' override isn't stored in the config
  563. # (and we don't have indirect python access to datasources yet)
  564. if is_default and "B10_FROM_BUILD" in os.environ:
  565. file = os.environ["B10_FROM_BUILD"] + os.sep + "bind10_zones.sqlite3"
  566. return file
  567. def increase_transfers_counter(self):
  568. '''Return False, if counter + 1 > max_transfers_out, or else
  569. return True
  570. '''
  571. ret = False
  572. self._lock.acquire()
  573. if self._transfers_counter < self._max_transfers_out:
  574. self._transfers_counter += 1
  575. ret = True
  576. self._lock.release()
  577. return ret
  578. def decrease_transfers_counter(self):
  579. self._lock.acquire()
  580. self._transfers_counter -= 1
  581. self._lock.release()
  582. class XfroutServer:
  583. def __init__(self):
  584. self._unix_socket_server = None
  585. self._listen_sock_file = UNIX_SOCKET_FILE
  586. self._shutdown_event = threading.Event()
  587. self._cc = isc.config.ModuleCCSession(SPECFILE_LOCATION, self.config_handler, self.command_handler)
  588. self._config_data = self._cc.get_full_config()
  589. self._cc.start()
  590. self._cc.add_remote_config(AUTH_SPECFILE_LOCATION);
  591. self._start_xfr_query_listener()
  592. self._start_notifier()
  593. def _start_xfr_query_listener(self):
  594. '''Start a new thread to accept xfr query. '''
  595. self._unix_socket_server = UnixSockServer(self._listen_sock_file,
  596. XfroutSession,
  597. self._shutdown_event,
  598. self._config_data,
  599. self._cc)
  600. listener = threading.Thread(target=self._unix_socket_server.serve_forever)
  601. listener.start()
  602. def _start_notifier(self):
  603. datasrc = self._unix_socket_server.get_db_file()
  604. self._notifier = notify_out.NotifyOut(datasrc)
  605. self._notifier.dispatcher()
  606. def send_notify(self, zone_name, zone_class):
  607. self._notifier.send_notify(zone_name, zone_class)
  608. def config_handler(self, new_config):
  609. '''Update config data. TODO. Do error check'''
  610. answer = create_answer(0)
  611. for key in new_config:
  612. if key not in self._config_data:
  613. answer = create_answer(1, "Unknown config data: " + str(key))
  614. continue
  615. self._config_data[key] = new_config[key]
  616. if self._unix_socket_server:
  617. try:
  618. self._unix_socket_server.update_config_data(self._config_data)
  619. except Exception as e:
  620. answer = create_answer(1,
  621. "Failed to handle new configuration: " +
  622. str(e))
  623. return answer
  624. def shutdown(self):
  625. ''' shutdown the xfrout process. The thread which is doing zone transfer-out should be
  626. terminated.
  627. '''
  628. global xfrout_server
  629. xfrout_server = None #Avoid shutdown is called twice
  630. self._shutdown_event.set()
  631. self._notifier.shutdown()
  632. if self._unix_socket_server:
  633. self._unix_socket_server.shutdown()
  634. # Wait for all threads to terminate
  635. main_thread = threading.currentThread()
  636. for th in threading.enumerate():
  637. if th is main_thread:
  638. continue
  639. th.join()
  640. def command_handler(self, cmd, args):
  641. if cmd == "shutdown":
  642. logger.info(XFROUT_RECEIVED_SHUTDOWN_COMMAND)
  643. self.shutdown()
  644. answer = create_answer(0)
  645. elif cmd == notify_out.ZONE_NEW_DATA_READY_CMD:
  646. zone_name = args.get('zone_name')
  647. zone_class = args.get('zone_class')
  648. if zone_name and zone_class:
  649. logger.info(XFROUT_NOTIFY_COMMAND, zone_name, zone_class)
  650. self.send_notify(zone_name, zone_class)
  651. answer = create_answer(0)
  652. else:
  653. answer = create_answer(1, "Bad command parameter:" + str(args))
  654. else:
  655. answer = create_answer(1, "Unknown command:" + str(cmd))
  656. return answer
  657. def run(self):
  658. '''Get and process all commands sent from cfgmgr or other modules. '''
  659. while not self._shutdown_event.is_set():
  660. self._cc.check_command(False)
  661. xfrout_server = None
  662. def signal_handler(signal, frame):
  663. if xfrout_server:
  664. xfrout_server.shutdown()
  665. sys.exit(0)
  666. def set_signal_handler():
  667. signal.signal(signal.SIGTERM, signal_handler)
  668. signal.signal(signal.SIGINT, signal_handler)
  669. def set_cmd_options(parser):
  670. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  671. help="display more about what is going on")
  672. if '__main__' == __name__:
  673. try:
  674. parser = OptionParser()
  675. set_cmd_options(parser)
  676. (options, args) = parser.parse_args()
  677. VERBOSE_MODE = options.verbose
  678. set_signal_handler()
  679. xfrout_server = XfroutServer()
  680. xfrout_server.run()
  681. except KeyboardInterrupt:
  682. logger.INFO(XFROUT_STOPPED_BY_KEYBOARD)
  683. except SessionError as e:
  684. logger.error(XFROUT_CC_SESSION_ERROR, str(e))
  685. except ModuleCCSessionError as e:
  686. logger.error(XFROUT_MODULECC_SESSION_ERROR, str(e))
  687. except XfroutConfigError as e:
  688. logger.error(XFROUT_CONFIG_ERROR, str(e))
  689. except SessionTimeout as e:
  690. logger.error(XFROUT_CC_SESSION_TIMEOUT_ERROR)
  691. if xfrout_server:
  692. xfrout_server.shutdown()