xfrin.py.in 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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 os
  18. import signal
  19. import isc
  20. import asyncore
  21. import struct
  22. import threading
  23. import socket
  24. import random
  25. from optparse import OptionParser, OptionValueError
  26. from isc.config.ccsession import *
  27. from isc.notify import notify_out
  28. import isc.util.process
  29. import isc.net.parse
  30. try:
  31. from pydnspp import *
  32. except ImportError as e:
  33. # C++ loadable module may not be installed; even so the xfrin process
  34. # must keep running, so we warn about it and move forward.
  35. sys.stderr.write('[b10-xfrin] failed to import DNS module: %s\n' % str(e))
  36. isc.util.process.rename()
  37. # If B10_FROM_BUILD is set in the environment, we use data files
  38. # from a directory relative to that, otherwise we use the ones
  39. # installed on the system
  40. if "B10_FROM_BUILD" in os.environ:
  41. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/xfrin"
  42. AUTH_SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/auth"
  43. else:
  44. PREFIX = "@prefix@"
  45. DATAROOTDIR = "@datarootdir@"
  46. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  47. AUTH_SPECFILE_PATH = SPECFILE_PATH
  48. SPECFILE_LOCATION = SPECFILE_PATH + "/xfrin.spec"
  49. AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + "/auth.spec"
  50. XFROUT_MODULE_NAME = 'Xfrout'
  51. ZONE_MANAGER_MODULE_NAME = 'Zonemgr'
  52. REFRESH_FROM_ZONEMGR = 'refresh_from_zonemgr'
  53. ZONE_XFRIN_FAILED = 'zone_xfrin_failed'
  54. __version__ = 'BIND10'
  55. # define xfrin rcode
  56. XFRIN_OK = 0
  57. XFRIN_FAIL = 1
  58. DEFAULT_MASTER_PORT = '53'
  59. DEFAULT_MASTER = '127.0.0.1'
  60. def log_error(msg):
  61. sys.stderr.write("[b10-xfrin] %s\n" % str(msg))
  62. class XfrinException(Exception):
  63. pass
  64. class XfrinConnection(asyncore.dispatcher):
  65. '''Do xfrin in this class. '''
  66. def __init__(self,
  67. sock_map, zone_name, rrclass, db_file, shutdown_event,
  68. master_addrinfo, verbose = False, idle_timeout = 60):
  69. ''' idle_timeout: max idle time for read data from socket.
  70. db_file: specify the data source file.
  71. check_soa: when it's true, check soa first before sending xfr query
  72. '''
  73. asyncore.dispatcher.__init__(self, map=sock_map)
  74. self.create_socket(master_addrinfo[0], master_addrinfo[1])
  75. self._zone_name = zone_name
  76. self._sock_map = sock_map
  77. self._rrclass = rrclass
  78. self._db_file = db_file
  79. self._soa_rr_count = 0
  80. self._idle_timeout = idle_timeout
  81. self.setblocking(1)
  82. self._shutdown_event = shutdown_event
  83. self._verbose = verbose
  84. self._master_address = master_addrinfo[2]
  85. def connect_to_master(self):
  86. '''Connect to master in TCP.'''
  87. try:
  88. self.connect(self._master_address)
  89. return True
  90. except socket.error as e:
  91. self.log_msg('Failed to connect:(%s), %s' % (self._master_address,
  92. str(e)))
  93. return False
  94. def _create_query(self, query_type):
  95. '''Create dns query message. '''
  96. msg = Message(Message.RENDER)
  97. query_id = random.randint(0, 0xFFFF)
  98. self._query_id = query_id
  99. msg.set_qid(query_id)
  100. msg.set_opcode(Opcode.QUERY())
  101. msg.set_rcode(Rcode.NOERROR())
  102. query_question = Question(Name(self._zone_name), self._rrclass, query_type)
  103. msg.add_question(query_question)
  104. return msg
  105. def _send_data(self, data):
  106. size = len(data)
  107. total_count = 0
  108. while total_count < size:
  109. count = self.send(data[total_count:])
  110. total_count += count
  111. def _send_query(self, query_type):
  112. '''Send query message over TCP. '''
  113. msg = self._create_query(query_type)
  114. render = MessageRenderer()
  115. msg.to_wire(render)
  116. header_len = struct.pack('H', socket.htons(render.get_length()))
  117. self._send_data(header_len)
  118. self._send_data(render.get_data())
  119. def _asyncore_loop(self):
  120. '''
  121. This method is a trivial wrapper for asyncore.loop(). It's extracted from
  122. _get_request_response so that we can test the rest of the code without
  123. involving actual communication with a remote server.'''
  124. asyncore.loop(self._idle_timeout, map=self._sock_map, count=1)
  125. def _get_request_response(self, size):
  126. recv_size = 0
  127. data = b''
  128. while recv_size < size:
  129. self._recv_time_out = True
  130. self._need_recv_size = size - recv_size
  131. self._asyncore_loop()
  132. if self._recv_time_out:
  133. raise XfrinException('receive data from socket time out.')
  134. recv_size += self._recvd_size
  135. data += self._recvd_data
  136. return data
  137. def _check_soa_serial(self):
  138. ''' Compare the soa serial, if soa serial in master is less than
  139. the soa serial in local, Finish xfrin.
  140. False: soa serial in master is less or equal to the local one.
  141. True: soa serial in master is bigger
  142. '''
  143. self._send_query(RRType("SOA"))
  144. data_len = self._get_request_response(2)
  145. msg_len = socket.htons(struct.unpack('H', data_len)[0])
  146. soa_response = self._get_request_response(msg_len)
  147. msg = Message(Message.PARSE)
  148. msg.from_wire(soa_response)
  149. # perform some minimal level validation. It's an open issue how
  150. # strict we should be (see the comment in _check_response_header())
  151. self._check_response_header(msg)
  152. # TODO, need select soa record from data source then compare the two
  153. # serial, current just return OK, since this function hasn't been used
  154. # now.
  155. return XFRIN_OK
  156. def do_xfrin(self, check_soa, ixfr_first = False):
  157. '''Do xfr by sending xfr request and parsing response. '''
  158. try:
  159. ret = XFRIN_OK
  160. if check_soa:
  161. logstr = 'SOA check for \'%s\' ' % self._zone_name
  162. ret = self._check_soa_serial()
  163. logstr = 'transfer of \'%s\': AXFR ' % self._zone_name
  164. if ret == XFRIN_OK:
  165. self.log_msg(logstr + 'started')
  166. # TODO: .AXFR() RRType.AXFR()
  167. self._send_query(RRType(252))
  168. isc.datasrc.sqlite3_ds.load(self._db_file, self._zone_name,
  169. self._handle_xfrin_response)
  170. self.log_msg(logstr + 'succeeded')
  171. except XfrinException as e:
  172. self.log_msg(e)
  173. self.log_msg(logstr + 'failed')
  174. ret = XFRIN_FAIL
  175. #TODO, recover data source.
  176. except isc.datasrc.sqlite3_ds.Sqlite3DSError as e:
  177. self.log_msg(e)
  178. self.log_msg(logstr + 'failed')
  179. ret = XFRIN_FAIL
  180. except UserWarning as e:
  181. # XXX: this is an exception from our C++ library via the
  182. # Boost.Python binding. It would be better to have more more
  183. # specific exceptions, but at this moment this is the finest
  184. # granularity.
  185. self.log_msg(e)
  186. self.log_msg(logstr + 'failed')
  187. ret = XFRIN_FAIL
  188. finally:
  189. self.close()
  190. return ret
  191. def _check_response_header(self, msg):
  192. '''Perform minimal validation on responses'''
  193. # It's not clear how strict we should be about response validation.
  194. # BIND 9 ignores some cases where it would normally be considered a
  195. # bogus response. For example, it accepts a response even if its
  196. # opcode doesn't match that of the corresponding request.
  197. # According to an original developer of BIND 9 some of the missing
  198. # checks are deliberate to be kind to old implementations that would
  199. # cause interoperability trouble with stricter checks.
  200. msg_rcode = msg.get_rcode()
  201. if msg_rcode != Rcode.NOERROR():
  202. raise XfrinException('error response: %s' % msg_rcode.to_text())
  203. if not msg.get_header_flag(Message.HEADERFLAG_QR):
  204. raise XfrinException('response is not a response ')
  205. if msg.get_qid() != self._query_id:
  206. raise XfrinException('bad query id')
  207. def _check_response_status(self, msg):
  208. '''Check validation of xfr response. '''
  209. self._check_response_header(msg)
  210. if msg.get_rr_count(Message.SECTION_ANSWER) == 0:
  211. raise XfrinException('answer section is empty')
  212. if msg.get_rr_count(Message.SECTION_QUESTION) > 1:
  213. raise XfrinException('query section count greater than 1')
  214. def _handle_answer_section(self, answer_section):
  215. '''Return a generator for the reponse in one tcp package to a zone transfer.'''
  216. for rrset in answer_section:
  217. rrset_name = rrset.get_name().to_text()
  218. rrset_ttl = int(rrset.get_ttl().to_text())
  219. rrset_class = rrset.get_class().to_text()
  220. rrset_type = rrset.get_type().to_text()
  221. for rdata in rrset.get_rdata():
  222. # Count the soa record count
  223. if rrset.get_type() == RRType("SOA"):
  224. self._soa_rr_count += 1
  225. # XXX: the current DNS message parser can't preserve the
  226. # RR order or separete the beginning and ending SOA RRs.
  227. # As a short term workaround, we simply ignore the second
  228. # SOA, and ignore the erroneous case where the transfer
  229. # session doesn't end with an SOA.
  230. if (self._soa_rr_count == 2):
  231. # Avoid inserting soa record twice
  232. break
  233. rdata_text = rdata.to_text()
  234. yield (rrset_name, rrset_ttl, rrset_class, rrset_type,
  235. rdata_text)
  236. def _handle_xfrin_response(self):
  237. '''Return a generator for the response to a zone transfer. '''
  238. while True:
  239. data_len = self._get_request_response(2)
  240. msg_len = socket.htons(struct.unpack('H', data_len)[0])
  241. recvdata = self._get_request_response(msg_len)
  242. msg = Message(Message.PARSE)
  243. msg.from_wire(recvdata)
  244. self._check_response_status(msg)
  245. answer_section = msg.get_section(Message.SECTION_ANSWER)
  246. for rr in self._handle_answer_section(answer_section):
  247. yield rr
  248. if self._soa_rr_count == 2:
  249. break
  250. if self._shutdown_event.is_set():
  251. raise XfrinException('xfrin is forced to stop')
  252. def handle_read(self):
  253. '''Read query's response from socket. '''
  254. self._recvd_data = self.recv(self._need_recv_size)
  255. self._recvd_size = len(self._recvd_data)
  256. self._recv_time_out = False
  257. def writable(self):
  258. '''Ignore the writable socket. '''
  259. return False
  260. def log_info(self, msg, type='info'):
  261. # Overwrite the log function, log nothing
  262. pass
  263. def log_msg(self, msg):
  264. if self._verbose:
  265. sys.stdout.write('[b10-xfrin] %s\n' % str(msg))
  266. def process_xfrin(server, xfrin_recorder, zone_name, rrclass, db_file,
  267. shutdown_event, master_addrinfo, check_soa, verbose):
  268. xfrin_recorder.increment(zone_name)
  269. sock_map = {}
  270. conn = XfrinConnection(sock_map, zone_name, rrclass, db_file,
  271. shutdown_event, master_addrinfo, verbose)
  272. ret = XFRIN_FAIL
  273. if conn.connect_to_master():
  274. ret = conn.do_xfrin(check_soa)
  275. # Publish the zone transfer result news, so zonemgr can reset the
  276. # zone timer, and xfrout can notify the zone's slaves if the result
  277. # is success.
  278. server.publish_xfrin_news(zone_name, rrclass, ret)
  279. xfrin_recorder.decrement(zone_name)
  280. class XfrinRecorder:
  281. def __init__(self):
  282. self._lock = threading.Lock()
  283. self._zones = []
  284. def increment(self, zone_name):
  285. self._lock.acquire()
  286. self._zones.append(zone_name)
  287. self._lock.release()
  288. def decrement(self, zone_name):
  289. self._lock.acquire()
  290. if zone_name in self._zones:
  291. self._zones.remove(zone_name)
  292. self._lock.release()
  293. def xfrin_in_progress(self, zone_name):
  294. self._lock.acquire()
  295. ret = zone_name in self._zones
  296. self._lock.release()
  297. return ret
  298. def count(self):
  299. self._lock.acquire()
  300. ret = len(self._zones)
  301. self._lock.release()
  302. return ret
  303. class Xfrin:
  304. def __init__(self, verbose = False):
  305. self._max_transfers_in = 10
  306. #TODO, this is the temp way to set the zone's master.
  307. self._master_addr = DEFAULT_MASTER
  308. self._master_port = DEFAULT_MASTER_PORT
  309. self._cc_setup()
  310. self.recorder = XfrinRecorder()
  311. self._shutdown_event = threading.Event()
  312. self._verbose = verbose
  313. def _cc_setup(self):
  314. '''This method is used only as part of initialization, but is
  315. implemented separately for convenience of unit tests; by letting
  316. the test code override this method we can test most of this class
  317. without requiring a command channel.'''
  318. # Create one session for sending command to other modules, because the
  319. # listening session will block the send operation.
  320. self._send_cc_session = isc.cc.Session()
  321. self._module_cc = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  322. self.config_handler,
  323. self.command_handler)
  324. self._module_cc.start()
  325. config_data = self._module_cc.get_full_config()
  326. self._max_transfers_in = config_data.get("transfers_in")
  327. self._master_addr = config_data.get('master_addr') or self._master_addr
  328. self._master_port = config_data.get('master_port') or self._master_port
  329. def _cc_check_command(self):
  330. '''This is a straightforward wrapper for cc.check_command,
  331. but provided as a separate method for the convenience
  332. of unit tests.'''
  333. self._module_cc.check_command(False)
  334. def config_handler(self, new_config):
  335. self._max_transfers_in = new_config.get("transfers_in") or self._max_transfers_in
  336. if ('master_addr' in new_config) or ('master_port' in new_config):
  337. # User should change the port and address together.
  338. try:
  339. addr = new_config.get('master_addr') or self._master_addr
  340. port = new_config.get('master_port') or self._master_port
  341. isc.net.parse.addr_parse(addr)
  342. isc.net.parse.port_parse(port)
  343. self._master_addr = addr
  344. self._master_port = port
  345. except ValueError:
  346. errmsg = "bad format for zone's master: " + str(new_config)
  347. log_error(errmsg)
  348. return create_answer(1, errmsg)
  349. return create_answer(0)
  350. def shutdown(self):
  351. ''' shutdown the xfrin process. the thread which is doing xfrin should be
  352. terminated.
  353. '''
  354. self._shutdown_event.set()
  355. main_thread = threading.currentThread()
  356. for th in threading.enumerate():
  357. if th is main_thread:
  358. continue
  359. th.join()
  360. def command_handler(self, command, args):
  361. answer = create_answer(0)
  362. try:
  363. if command == 'shutdown':
  364. self._shutdown_event.set()
  365. elif command == 'notify' or command == REFRESH_FROM_ZONEMGR:
  366. # Xfrin receives the refresh/notify command from zone manager.
  367. # notify command maybe has the parameters which
  368. # specify the notifyfrom address and port, according the RFC1996, zone
  369. # transfer should starts first from the notifyfrom, but now, let 'TODO' it.
  370. (zone_name, rrclass) = self._parse_zone_name_and_class(args)
  371. (master_addr) = build_addr_info(self._master_addr, self._master_port)
  372. ret = self.xfrin_start(zone_name,
  373. rrclass,
  374. self._get_db_file(),
  375. master_addr,
  376. True)
  377. answer = create_answer(ret[0], ret[1])
  378. elif command == 'retransfer' or command == 'refresh':
  379. # Xfrin receives the retransfer/refresh from cmdctl(sent by bindctl).
  380. # If the command has specified master address, do transfer from the
  381. # master address, or else do transfer from the configured masters.
  382. (zone_name, rrclass) = self._parse_zone_name_and_class(args)
  383. master_addr = self._parse_master_and_port(args)
  384. db_file = args.get('db_file') or self._get_db_file()
  385. ret = self.xfrin_start(zone_name,
  386. rrclass,
  387. db_file,
  388. master_addr,
  389. (False if command == 'retransfer' else True))
  390. answer = create_answer(ret[0], ret[1])
  391. else:
  392. answer = create_answer(1, 'unknown command: ' + command)
  393. except XfrinException as err:
  394. log_error('error happened for command: %s, %s' % (command, str(err)) )
  395. answer = create_answer(1, str(err))
  396. return answer
  397. def _parse_zone_name_and_class(self, args):
  398. zone_name = args.get('zone_name')
  399. if not zone_name:
  400. raise XfrinException('zone name should be provided')
  401. rrclass = args.get('zone_class')
  402. if not rrclass:
  403. rrclass = RRClass.IN()
  404. else:
  405. try:
  406. rrclass = RRClass(rrclass)
  407. except InvalidRRClass as e:
  408. raise XfrinException('invalid RRClass: ' + rrclass)
  409. return zone_name, rrclass
  410. def _parse_master_and_port(self, args):
  411. port = args.get('port') or self._master_port
  412. master = args.get('master') or self._master_addr
  413. return build_addr_info(master, port)
  414. def _get_db_file(self):
  415. #TODO, the db file path should be got in auth server's configuration
  416. # if we need access to this configuration more often, we
  417. # should add it on start, and not remove it here
  418. # (or, if we have writable ds, we might not need this in
  419. # the first place)
  420. self._module_cc.add_remote_config(AUTH_SPECFILE_LOCATION)
  421. db_file, is_default = self._module_cc.get_remote_config_value("Auth", "database_file")
  422. if is_default and "B10_FROM_BUILD" in os.environ:
  423. # this too should be unnecessary, but currently the
  424. # 'from build' override isn't stored in the config
  425. # (and we don't have writable datasources yet)
  426. db_file = os.environ["B10_FROM_BUILD"] + os.sep + "bind10_zones.sqlite3"
  427. self._module_cc.remove_remote_config(AUTH_SPECFILE_LOCATION)
  428. return db_file
  429. def publish_xfrin_news(self, zone_name, zone_class, xfr_result):
  430. '''Send command to xfrout/zone manager module.
  431. If xfrin has finished successfully for one zone, tell the good
  432. news(command: zone_new_data_ready) to zone manager and xfrout.
  433. if xfrin failed, just tell the bad news to zone manager, so that
  434. it can reset the refresh timer for that zone. '''
  435. param = {'zone_name': zone_name, 'zone_class': zone_class.to_text()}
  436. if xfr_result == XFRIN_OK:
  437. msg = create_command(notify_out.ZONE_NEW_DATA_READY_CMD, param)
  438. # catch the exception, in case msgq has been killed.
  439. try:
  440. seq = self._send_cc_session.group_sendmsg(msg,
  441. XFROUT_MODULE_NAME)
  442. try:
  443. answer, env = self._send_cc_session.group_recvmsg(False,
  444. seq)
  445. except isc.cc.session.SessionTimeout:
  446. pass # for now we just ignore the failure
  447. seq = self._send_cc_session.group_sendmsg(msg, ZONE_MANAGER_MODULE_NAME)
  448. try:
  449. answer, env = self._send_cc_session.group_recvmsg(False,
  450. seq)
  451. except isc.cc.session.SessionTimeout:
  452. pass # for now we just ignore the failure
  453. except socket.error as err:
  454. log_error("Fail to send message to %s and %s, msgq may has been killed"
  455. % (XFROUT_MODULE_NAME, ZONE_MANAGER_MODULE_NAME))
  456. else:
  457. msg = create_command(ZONE_XFRIN_FAILED, param)
  458. # catch the exception, in case msgq has been killed.
  459. try:
  460. seq = self._send_cc_session.group_sendmsg(msg, ZONE_MANAGER_MODULE_NAME)
  461. try:
  462. answer, env = self._send_cc_session.group_recvmsg(False,
  463. seq)
  464. except isc.cc.session.SessionTimeout:
  465. pass # for now we just ignore the failure
  466. except socket.error as err:
  467. log_error("Fail to send message to %s, msgq may has been killed"
  468. % ZONE_MANAGER_MODULE_NAME)
  469. def startup(self):
  470. while not self._shutdown_event.is_set():
  471. self._cc_check_command()
  472. def xfrin_start(self, zone_name, rrclass, db_file, master_addrinfo,
  473. check_soa = True):
  474. if "pydnspp" not in sys.modules:
  475. return (1, "xfrin failed, can't load dns message python library: 'pydnspp'")
  476. # check max_transfer_in, else return quota error
  477. if self.recorder.count() >= self._max_transfers_in:
  478. return (1, 'xfrin quota error')
  479. if self.recorder.xfrin_in_progress(zone_name):
  480. return (1, 'zone xfrin is in progress')
  481. xfrin_thread = threading.Thread(target = process_xfrin,
  482. args = (self,
  483. self.recorder,
  484. zone_name, rrclass,
  485. db_file,
  486. self._shutdown_event,
  487. master_addrinfo, check_soa,
  488. self._verbose))
  489. xfrin_thread.start()
  490. return (0, 'zone xfrin is started')
  491. xfrind = None
  492. def signal_handler(signal, frame):
  493. if xfrind:
  494. xfrind.shutdown()
  495. sys.exit(0)
  496. def set_signal_handler():
  497. signal.signal(signal.SIGTERM, signal_handler)
  498. signal.signal(signal.SIGINT, signal_handler)
  499. def build_addr_info(addrstr, portstr):
  500. """
  501. Return tuple (family, socktype, sockaddr) for given address and port.
  502. IPv4 and IPv6 are the only supported addresses now, so sockaddr will be
  503. (address, port). The socktype is socket.SOCK_STREAM for now.
  504. """
  505. try:
  506. port = isc.net.parse.port_parse(portstr)
  507. addr = isc.net.parse.addr_parse(addrstr)
  508. return (addr.family, socket.SOCK_STREAM, (addrstr, port))
  509. except ValueError as err:
  510. raise XfrinException("failed to resolve master address/port=%s/%s: %s" %
  511. (addrstr, portstr, str(err)))
  512. def set_cmd_options(parser):
  513. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  514. help="display more about what is going on")
  515. def main(xfrin_class, use_signal = True):
  516. """The main loop of the Xfrin daemon.
  517. @param xfrin_class: A class of the Xfrin object. This is normally Xfrin,
  518. but can be a subclass of it for customization.
  519. @param use_signal: True if this process should catch signals. This is
  520. normally True, but may be disabled when this function is called in a
  521. testing context."""
  522. global xfrind
  523. try:
  524. parser = OptionParser(version = __version__)
  525. set_cmd_options(parser)
  526. (options, args) = parser.parse_args()
  527. if use_signal:
  528. set_signal_handler()
  529. xfrind = xfrin_class(verbose = options.verbose)
  530. xfrind.startup()
  531. except KeyboardInterrupt:
  532. log_error("exit b10-xfrin")
  533. except isc.cc.session.SessionError as e:
  534. log_error(str(e))
  535. log_error('Error happened! is the command channel daemon running?')
  536. except Exception as e:
  537. log_error(str(e))
  538. if xfrind:
  539. xfrind.shutdown()
  540. if __name__ == '__main__':
  541. main(Xfrin)