xfrin.py.in 25 KB

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