xfrout.py.in 19 KB

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