xfrout.py.in 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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.log.log import *
  27. from isc.cc import SessionError, SessionTimeout
  28. from isc.notify import notify_out
  29. import isc.utils.process
  30. import socket
  31. import select
  32. import errno
  33. from optparse import OptionParser, OptionValueError
  34. try:
  35. from libxfr_python import *
  36. from pydnspp import *
  37. except ImportError as e:
  38. # C++ loadable module may not be installed; even so the xfrout process
  39. # must keep running, so we warn about it and move forward.
  40. sys.stderr.write('[b10-xfrout] failed to import DNS or XFR module: %s\n' % str(e))
  41. isc.utils.process.rename()
  42. if "B10_FROM_BUILD" in os.environ:
  43. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/xfrout"
  44. AUTH_SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/auth"
  45. UNIX_SOCKET_FILE= os.environ["B10_FROM_BUILD"] + "/auth_xfrout_conn"
  46. else:
  47. PREFIX = "@prefix@"
  48. DATAROOTDIR = "@datarootdir@"
  49. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  50. AUTH_SPECFILE_PATH = SPECFILE_PATH
  51. UNIX_SOCKET_FILE = "@@LOCALSTATEDIR@@/auth_xfrout_conn"
  52. SPECFILE_LOCATION = SPECFILE_PATH + "/xfrout.spec"
  53. AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + os.sep + "auth.spec"
  54. MAX_TRANSFERS_OUT = 10
  55. VERBOSE_MODE = False
  56. XFROUT_MAX_MESSAGE_SIZE = 65535
  57. def get_rrset_len(rrset):
  58. """Returns the wire length of the given RRset"""
  59. bytes = bytearray()
  60. rrset.to_wire(bytes)
  61. return len(bytes)
  62. class XfroutSession(BaseRequestHandler):
  63. def __init__(self, request, client_address, server, log):
  64. # The initializer for the superclass may call functions
  65. # that need _log to be set, so we set it first
  66. self._log = log
  67. BaseRequestHandler.__init__(self, request, client_address, server)
  68. def handle(self):
  69. fd = recv_fd(self.request.fileno())
  70. if fd < 0:
  71. # This may happen when one xfrout process try to connect to
  72. # xfrout unix socket server, to check whether there is another
  73. # xfrout running.
  74. self._log.log_message("error", "Failed to receive the file descriptor for XFR connection")
  75. return
  76. data_len = self.request.recv(2)
  77. msg_len = struct.unpack('!H', data_len)[0]
  78. msgdata = self.request.recv(msg_len)
  79. sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
  80. try:
  81. self.dns_xfrout_start(sock, msgdata)
  82. #TODO, avoid catching all exceptions
  83. except Exception as e:
  84. self._log.log_message("error", str(e))
  85. try:
  86. sock.shutdown(socket.SHUT_RDWR)
  87. except socket.error:
  88. # Avoid socket error caused by shutting down
  89. # one non-connected socket.
  90. pass
  91. sock.close()
  92. os.close(fd)
  93. pass
  94. def _parse_query_message(self, mdata):
  95. ''' parse query message to [socket,message]'''
  96. #TODO, need to add parseHeader() in case the message header is invalid
  97. try:
  98. msg = Message(Message.PARSE)
  99. Message.from_wire(msg, mdata)
  100. except Exception as err:
  101. self._log.log_message("error", str(err))
  102. return Rcode.FORMERR(), None
  103. return Rcode.NOERROR(), msg
  104. def _get_query_zone_name(self, msg):
  105. question = msg.get_question()[0]
  106. return question.get_name().to_text()
  107. def _send_data(self, sock, data):
  108. size = len(data)
  109. total_count = 0
  110. while total_count < size:
  111. count = sock.send(data[total_count:])
  112. total_count += count
  113. def _send_message(self, sock, msg):
  114. render = MessageRenderer()
  115. render.set_length_limit(XFROUT_MAX_MESSAGE_SIZE)
  116. msg.to_wire(render)
  117. header_len = struct.pack('H', socket.htons(render.get_length()))
  118. self._send_data(sock, header_len)
  119. self._send_data(sock, render.get_data())
  120. def _reply_query_with_error_rcode(self, msg, sock, rcode_):
  121. msg.make_response()
  122. msg.set_rcode(rcode_)
  123. self._send_message(sock, msg)
  124. def _reply_query_with_format_error(self, msg, sock):
  125. '''query message format isn't legal.'''
  126. if not msg:
  127. return # query message is invalid. send nothing back.
  128. msg.make_response()
  129. msg.set_rcode(Rcode.FORMERR())
  130. self._send_message(sock, msg)
  131. def _zone_is_empty(self, zone):
  132. if sqlite3_ds.get_zone_soa(zone, self.server.get_db_file()):
  133. return False
  134. return True
  135. def _zone_exist(self, zonename):
  136. # Find zone in datasource, should this works? maybe should ask
  137. # config manager.
  138. soa = sqlite3_ds.get_zone_soa(zonename, self.server.get_db_file())
  139. if soa:
  140. return True
  141. return False
  142. def _check_xfrout_available(self, zone_name):
  143. '''Check if xfr request can be responsed.
  144. TODO, Get zone's configuration from cfgmgr or some other place
  145. eg. check allow_transfer setting,
  146. '''
  147. if not self._zone_exist(zone_name):
  148. return Rcode.NOTAUTH()
  149. if self._zone_is_empty(zone_name):
  150. return Rcode.SERVFAIL()
  151. #TODO, check allow_transfer
  152. if not self.server.increase_transfers_counter():
  153. return Rcode.REFUSED()
  154. return Rcode.NOERROR()
  155. def dns_xfrout_start(self, sock, msg_query):
  156. rcode_, msg = self._parse_query_message(msg_query)
  157. #TODO. create query message and parse header
  158. if rcode_ != Rcode.NOERROR():
  159. return self._reply_query_with_format_error(msg, sock)
  160. zone_name = self._get_query_zone_name(msg)
  161. rcode_ = self._check_xfrout_available(zone_name)
  162. if rcode_ != Rcode.NOERROR():
  163. self._log.log_message("info", "transfer of '%s/IN' failed: %s",
  164. zone_name, rcode_.to_text())
  165. return self. _reply_query_with_error_rcode(msg, sock, rcode_)
  166. try:
  167. self._log.log_message("info", "transfer of '%s/IN': AXFR started" % zone_name)
  168. self._reply_xfrout_query(msg, sock, zone_name)
  169. self._log.log_message("info", "transfer of '%s/IN': AXFR end" % zone_name)
  170. except Exception as err:
  171. self._log.log_message("error", str(err))
  172. self.server.decrease_transfers_counter()
  173. return
  174. def _clear_message(self, msg):
  175. qid = msg.get_qid()
  176. opcode = msg.get_opcode()
  177. rcode = msg.get_rcode()
  178. msg.clear(Message.RENDER)
  179. msg.set_qid(qid)
  180. msg.set_opcode(opcode)
  181. msg.set_rcode(rcode)
  182. msg.set_header_flag(MessageFlag.AA())
  183. msg.set_header_flag(MessageFlag.QR())
  184. return msg
  185. def _create_rrset_from_db_record(self, record):
  186. '''Create one rrset from one record of datasource, if the schema of record is changed,
  187. This function should be updated first.
  188. '''
  189. rrtype_ = RRType(record[5])
  190. rdata_ = Rdata(rrtype_, RRClass("IN"), " ".join(record[7:]))
  191. rrset_ = RRset(Name(record[2]), RRClass("IN"), rrtype_, RRTTL( int(record[4])))
  192. rrset_.add_rdata(rdata_)
  193. return rrset_
  194. def _send_message_with_last_soa(self, msg, sock, rrset_soa, message_upper_len):
  195. '''Add the SOA record to the end of message. If it can't be
  196. added, a new message should be created to send out the last soa .
  197. '''
  198. rrset_len = get_rrset_len(rrset_soa)
  199. if message_upper_len + rrset_len < XFROUT_MAX_MESSAGE_SIZE:
  200. msg.add_rrset(Section.ANSWER(), rrset_soa)
  201. else:
  202. self._send_message(sock, msg)
  203. msg = self._clear_message(msg)
  204. msg.add_rrset(Section.ANSWER(), rrset_soa)
  205. self._send_message(sock, msg)
  206. def _reply_xfrout_query(self, msg, sock, zone_name):
  207. #TODO, there should be a better way to insert rrset.
  208. msg.make_response()
  209. msg.set_header_flag(MessageFlag.AA())
  210. soa_record = sqlite3_ds.get_zone_soa(zone_name, self.server.get_db_file())
  211. rrset_soa = self._create_rrset_from_db_record(soa_record)
  212. msg.add_rrset(Section.ANSWER(), rrset_soa)
  213. message_upper_len = get_rrset_len(rrset_soa)
  214. for rr_data in sqlite3_ds.get_zone_datas(zone_name, self.server.get_db_file()):
  215. if self.server._shutdown_event.is_set(): # Check if xfrout is shutdown
  216. self._log.log_message("error", "shutdown!")
  217. # TODO: RRType.SOA() ?
  218. if RRType(rr_data[5]) == RRType("SOA"): #ignore soa record
  219. continue
  220. rrset_ = self._create_rrset_from_db_record(rr_data)
  221. # We calculate the maximum size of the RRset (i.e. the
  222. # size without compression) and use that to see if we
  223. # may have reached the limit
  224. rrset_len = get_rrset_len(rrset_)
  225. if message_upper_len + rrset_len < XFROUT_MAX_MESSAGE_SIZE:
  226. msg.add_rrset(Section.ANSWER(), rrset_)
  227. message_upper_len += rrset_len
  228. continue
  229. self._send_message(sock, msg)
  230. msg = self._clear_message(msg)
  231. msg.add_rrset(Section.ANSWER(), rrset_) # Add the rrset to the new message
  232. message_upper_len = rrset_len
  233. self._send_message_with_last_soa(msg, sock, rrset_soa, message_upper_len)
  234. class UnixSockServer(ThreadingUnixStreamServer):
  235. '''The unix domain socket server which accept xfr query sent from auth server.'''
  236. def __init__(self, sock_file, handle_class, shutdown_event, config_data, cc, log):
  237. self._remove_unused_sock_file(sock_file)
  238. self._sock_file = sock_file
  239. ThreadingUnixStreamServer.__init__(self, sock_file, handle_class)
  240. self._lock = threading.Lock()
  241. self._transfers_counter = 0
  242. self._shutdown_event = shutdown_event
  243. self._log = log
  244. self.update_config_data(config_data)
  245. self._cc = cc
  246. def finish_request(self, request, client_address):
  247. '''Finish one request by instantiating RequestHandlerClass.'''
  248. self.RequestHandlerClass(request, client_address, self, self._log)
  249. def _remove_unused_sock_file(self, sock_file):
  250. '''Try to remove the socket file. If the file is being used
  251. by one running xfrout process, exit from python.
  252. If it's not a socket file or nobody is listening
  253. , it will be removed. If it can't be removed, exit from python. '''
  254. if self._sock_file_in_use(sock_file):
  255. sys.stderr.write("[b10-xfrout] Fail to start xfrout process, unix socket"
  256. " file '%s' is being used by another xfrout process\n" % sock_file)
  257. sys.exit(0)
  258. else:
  259. if not os.path.exists(sock_file):
  260. return
  261. try:
  262. os.unlink(sock_file)
  263. except OSError as err:
  264. sys.stderr.write('[b10-xfrout] Fail to remove file %s: %s\n' % (sock_file, err))
  265. sys.exit(0)
  266. def _sock_file_in_use(self, sock_file):
  267. '''Check whether the socket file 'sock_file' exists and
  268. is being used by one running xfrout process. If it is,
  269. return True, or else return False. '''
  270. try:
  271. sock = socket.socket(socket.AF_UNIX)
  272. sock.connect(sock_file)
  273. except socket.error as err:
  274. return False
  275. else:
  276. return True
  277. def shutdown(self):
  278. ThreadingUnixStreamServer.shutdown(self)
  279. try:
  280. os.unlink(self._sock_file)
  281. except Exception as e:
  282. self._log.log_message("error", str(e))
  283. def update_config_data(self, new_config):
  284. '''Apply the new config setting of xfrout module. '''
  285. self._log.log_message('info', 'update config data start.')
  286. self._lock.acquire()
  287. self._max_transfers_out = new_config.get('transfers_out')
  288. self._log.log_message('info', 'max transfer out : %d', self._max_transfers_out)
  289. self._lock.release()
  290. self._log.log_message('info', 'update config data complete.')
  291. def get_db_file(self):
  292. file, is_default = self._cc.get_remote_config_value("Auth", "database_file")
  293. # this too should be unnecessary, but currently the
  294. # 'from build' override isn't stored in the config
  295. # (and we don't have indirect python access to datasources yet)
  296. if is_default and "B10_FROM_BUILD" in os.environ:
  297. file = os.environ["B10_FROM_BUILD"] + os.sep + "bind10_zones.sqlite3"
  298. return file
  299. def increase_transfers_counter(self):
  300. '''Return False, if counter + 1 > max_transfers_out, or else
  301. return True
  302. '''
  303. ret = False
  304. self._lock.acquire()
  305. if self._transfers_counter < self._max_transfers_out:
  306. self._transfers_counter += 1
  307. ret = True
  308. self._lock.release()
  309. return ret
  310. def decrease_transfers_counter(self):
  311. self._lock.acquire()
  312. self._transfers_counter -= 1
  313. self._lock.release()
  314. def listen_on_xfr_query(unix_socket_server):
  315. '''Listen xfr query in one single thread. Polls for shutdown
  316. every 0.1 seconds, is there a better time?
  317. '''
  318. while True:
  319. try:
  320. unix_socket_server.serve_forever(poll_interval = 0.1)
  321. except select.error as err:
  322. # serve_forever() calls select.select(), which can be
  323. # interrupted.
  324. # If it is interrupted, it raises select.error with the
  325. # errno set to EINTR. We ignore this case, and let the
  326. # normal program flow continue by trying serve_forever()
  327. # again.
  328. if err.args[0] != errno.EINTR: raise
  329. class XfroutServer:
  330. def __init__(self):
  331. self._unix_socket_server = None
  332. self._log = None
  333. self._listen_sock_file = UNIX_SOCKET_FILE
  334. self._shutdown_event = threading.Event()
  335. self._cc = isc.config.ModuleCCSession(SPECFILE_LOCATION, self.config_handler, self.command_handler)
  336. self._config_data = self._cc.get_full_config()
  337. self._cc.start()
  338. self._cc.add_remote_config(AUTH_SPECFILE_LOCATION);
  339. self._log = isc.log.NSLogger(self._config_data.get('log_name'), self._config_data.get('log_file'),
  340. self._config_data.get('log_severity'), self._config_data.get('log_versions'),
  341. self._config_data.get('log_max_bytes'), True)
  342. self._start_xfr_query_listener()
  343. self._start_notifier()
  344. def _start_xfr_query_listener(self):
  345. '''Start a new thread to accept xfr query. '''
  346. self._unix_socket_server = UnixSockServer(self._listen_sock_file, XfroutSession,
  347. self._shutdown_event, self._config_data,
  348. self._cc, self._log);
  349. listener = threading.Thread(target = listen_on_xfr_query, args = (self._unix_socket_server,))
  350. listener.start()
  351. def _start_notifier(self):
  352. datasrc = self._unix_socket_server.get_db_file()
  353. self._notifier = notify_out.NotifyOut(datasrc, self._log)
  354. td = threading.Thread(target = notify_out.dispatcher, args = (self._notifier,))
  355. td.daemon = True
  356. td.start()
  357. def send_notify(self, zone_name, zone_class):
  358. self._notifier.send_notify(zone_name, zone_class)
  359. def config_handler(self, new_config):
  360. '''Update config data. TODO. Do error check'''
  361. answer = create_answer(0)
  362. for key in new_config:
  363. if key not in self._config_data:
  364. answer = create_answer(1, "Unknown config data: " + str(key))
  365. continue
  366. self._config_data[key] = new_config[key]
  367. if self._log:
  368. self._log.update_config(new_config)
  369. if self._unix_socket_server:
  370. self._unix_socket_server.update_config_data(self._config_data)
  371. return answer
  372. def shutdown(self):
  373. ''' shutdown the xfrout process. The thread which is doing zone transfer-out should be
  374. terminated.
  375. '''
  376. global xfrout_server
  377. xfrout_server = None #Avoid shutdown is called twice
  378. self._shutdown_event.set()
  379. if self._unix_socket_server:
  380. self._unix_socket_server.shutdown()
  381. main_thread = threading.currentThread()
  382. for th in threading.enumerate():
  383. if th is main_thread:
  384. continue
  385. th.join()
  386. def command_handler(self, cmd, args):
  387. if cmd == "shutdown":
  388. self._log.log_message("info", "Received shutdown command.")
  389. self.shutdown()
  390. answer = create_answer(0)
  391. elif cmd == notify_out.ZONE_NEW_DATA_READY_CMD:
  392. zone_name = args.get('zone_name')
  393. zone_class = args.get('zone_class')
  394. if zone_name and zone_class:
  395. self._log.log_message("info", "zone '%s/%s': receive notify others command" \
  396. % (zone_name, zone_class))
  397. self.send_notify(zone_name, zone_class)
  398. answer = create_answer(0)
  399. else:
  400. answer = create_answer(1, "Bad command parameter:" + str(args))
  401. else:
  402. answer = create_answer(1, "Unknown command:" + str(cmd))
  403. return answer
  404. def run(self):
  405. '''Get and process all commands sent from cfgmgr or other modules. '''
  406. while not self._shutdown_event.is_set():
  407. self._cc.check_command()
  408. xfrout_server = None
  409. def signal_handler(signal, frame):
  410. if xfrout_server:
  411. xfrout_server.shutdown()
  412. sys.exit(0)
  413. def set_signal_handler():
  414. signal.signal(signal.SIGTERM, signal_handler)
  415. signal.signal(signal.SIGINT, signal_handler)
  416. def set_cmd_options(parser):
  417. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  418. help="display more about what is going on")
  419. if '__main__' == __name__:
  420. try:
  421. parser = OptionParser()
  422. set_cmd_options(parser)
  423. (options, args) = parser.parse_args()
  424. VERBOSE_MODE = options.verbose
  425. set_signal_handler()
  426. xfrout_server = XfroutServer()
  427. xfrout_server.run()
  428. except KeyboardInterrupt:
  429. sys.stderr.write("[b10-xfrout] exit xfrout process\n")
  430. except SessionError as e:
  431. sys.stderr.write("[b10-xfrout] Error creating xfrout, "
  432. "is the command channel daemon running?\n")
  433. except SessionTimeout as e:
  434. sys.stderr.write("[b10-xfrout] Error creating xfrout, "
  435. "is the configuration manager running?\n")
  436. except ModuleCCSessionError as e:
  437. sys.stderr.write("[b10-xfrout] exit xfrout process:%s\n" % str(e))
  438. if xfrout_server:
  439. xfrout_server.shutdown()