ddns.py.in 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. #!@PYTHON@
  2. # Copyright (C) 2011 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. from isc.acl.dns import REQUEST_LOADER
  19. import bind10_config
  20. from isc.dns import *
  21. import isc.ddns.session
  22. from isc.ddns.zone_config import ZoneConfig
  23. from isc.ddns.logger import ClientFormatter, ZoneFormatter
  24. from isc.config.ccsession import *
  25. from isc.config.module_spec import ModuleSpecError
  26. from isc.cc import SessionError, SessionTimeout, ProtocolError
  27. import isc.util.process
  28. import isc.util.cio.socketsession
  29. import isc.server_common.tsig_keyring
  30. from isc.server_common.dns_tcp import DNSTCPContext
  31. from isc.datasrc import DataSourceClient
  32. from isc.server_common.auth_command import AUTH_LOADZONE_COMMAND, \
  33. auth_loadzone_params
  34. import select
  35. import time
  36. import errno
  37. from isc.log_messages.ddns_messages import *
  38. from optparse import OptionParser, OptionValueError
  39. import os
  40. import os.path
  41. import signal
  42. import socket
  43. isc.log.init("b10-ddns", buffer=True)
  44. logger = isc.log.Logger("ddns")
  45. TRACE_BASIC = logger.DBGLVL_TRACE_BASIC
  46. # Well known path settings. We need to define
  47. # SPECFILE_LOCATION: ddns configuration spec file
  48. # SOCKET_FILE: Unix domain socket file to communicate with b10-auth
  49. # AUTH_SPECFILE_LOCATION: b10-auth configuration spec file (tentatively
  50. # necessarily for sqlite3-only-and-older-datasrc-API stuff). This should be
  51. # gone once we migrate to the new API and start using generalized config.
  52. #
  53. # If B10_FROM_SOURCE is set in the environment, we use data files
  54. # from a directory relative to that, otherwise we use the ones
  55. # installed on the system
  56. if "B10_FROM_SOURCE" in os.environ:
  57. SPECFILE_PATH = os.environ["B10_FROM_SOURCE"] + "/src/bin/ddns"
  58. else:
  59. PREFIX = "@prefix@"
  60. DATAROOTDIR = "@datarootdir@"
  61. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR)
  62. SPECFILE_PATH = SPECFILE_PATH.replace("${prefix}", PREFIX)
  63. if "B10_FROM_BUILD" in os.environ:
  64. if "B10_FROM_SOURCE_LOCALSTATEDIR" in os.environ:
  65. SOCKET_FILE_PATH = os.environ["B10_FROM_SOURCE_LOCALSTATEDIR"]
  66. else:
  67. SOCKET_FILE_PATH = os.environ["B10_FROM_BUILD"]
  68. else:
  69. SOCKET_FILE_PATH = bind10_config.DATA_PATH
  70. SPECFILE_LOCATION = SPECFILE_PATH + "/ddns.spec"
  71. SOCKET_FILE = SOCKET_FILE_PATH + '/ddns_socket'
  72. # Cooperating or dependency modules
  73. AUTH_MODULE_NAME = 'Auth'
  74. XFROUT_MODULE_NAME = 'Xfrout'
  75. ZONEMGR_MODULE_NAME = 'Zonemgr'
  76. isc.util.process.rename()
  77. class DDNSConfigError(Exception):
  78. '''An exception indicating an error in updating ddns configuration.
  79. This exception is raised when the ddns process encounters an error in
  80. handling configuration updates. Not all syntax error can be caught
  81. at the module-CC layer, so ddns needs to (explicitly or implicitly)
  82. validate the given configuration data itself. When it finds an error
  83. it raises this exception (either directly or by converting an exception
  84. from other modules) as a unified error in configuration.
  85. '''
  86. pass
  87. class DDNSSessionError(Exception):
  88. '''An exception raised for some unexpected events during a ddns session.
  89. '''
  90. pass
  91. class DDNSSession:
  92. '''Class to handle one DDNS update'''
  93. def __init__(self):
  94. '''Initialize a DDNS Session'''
  95. pass
  96. def clear_socket():
  97. '''
  98. Removes the socket file, if it exists.
  99. '''
  100. if os.path.exists(SOCKET_FILE):
  101. os.remove(SOCKET_FILE)
  102. def get_datasrc_client(cc_session):
  103. '''Return data source client for update requests.
  104. This is supposed to have a very short lifetime and should soon be replaced
  105. with generic data source configuration framework. Based on that
  106. observation we simply hardcode everything except the SQLite3 database file,
  107. which will be retrieved from the auth server configuration (this behavior
  108. will also be deprecated). When something goes wrong with it this function
  109. still returns a dummy client so that the caller doesn't have to bother
  110. to handle the error (which would also have to be replaced anyway).
  111. The caller will subsequently call its find_zone method via an update
  112. session object, which will result in an exception, and then result in
  113. a SERVFAIL response.
  114. Once we are ready for introducing the general framework, the whole
  115. function will simply be removed.
  116. '''
  117. HARDCODED_DATASRC_CLASS = RRClass.IN
  118. file, is_default = cc_session.get_remote_config_value("Auth",
  119. "database_file")
  120. # See xfrout.py:get_db_file() for this trick:
  121. if is_default and "B10_FROM_BUILD" in os.environ:
  122. file = os.environ["B10_FROM_BUILD"] + "/bind10_zones.sqlite3"
  123. datasrc_config = '{ "database_file": "' + file + '"}'
  124. try:
  125. return (HARDCODED_DATASRC_CLASS,
  126. DataSourceClient('sqlite3', datasrc_config), file)
  127. except isc.datasrc.Error as ex:
  128. class DummyDataSourceClient:
  129. def __init__(self, ex):
  130. self.__ex = ex
  131. def find_zone(self, zone_name):
  132. raise isc.datasrc.Error(self.__ex)
  133. return (HARDCODED_DATASRC_CLASS, DummyDataSourceClient(ex), file)
  134. def add_pause(sec):
  135. '''Pause a specified period for inter module synchronization.
  136. This is a trivial wrapper of time.sleep, but defined as a separate function
  137. so tests can customize it.
  138. '''
  139. time.sleep(sec)
  140. class DDNSServer:
  141. # The number of TCP clients that can be handled by the server at the same
  142. # time (this should be configurable parameter).
  143. TCP_CLIENTS = 10
  144. def __init__(self, cc_session=None):
  145. '''
  146. Initialize the DDNS Server.
  147. This sets up a ModuleCCSession for the BIND 10 system.
  148. Parameters:
  149. cc_session: If None (default), a new ModuleCCSession will be set up.
  150. If specified, the given session will be used. This is
  151. mainly used for testing.
  152. '''
  153. if cc_session is not None:
  154. self._cc = cc_session
  155. else:
  156. self._cc = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  157. self.config_handler,
  158. self.command_handler)
  159. # Initialize configuration with defaults. Right now 'zones' is the
  160. # only configuration, so we simply directly set it here.
  161. self._config_data = self._cc.get_full_config()
  162. self._zone_config = self.__update_zone_config(
  163. self._cc.get_default_value('zones'))
  164. self._cc.start()
  165. # Internal attributes derived from other modules. They will be
  166. # initialized via dd_remote_xxx below and will be kept updated
  167. # through their callbacks. They are defined as 'protected' so tests
  168. # can examine them; but they are essentially private to the class.
  169. #
  170. # Datasource client used for handling update requests: when set,
  171. # should a tuple of RRClass and DataSourceClient. Constructed and
  172. # maintained based on auth configuration.
  173. self._datasrc_info = None
  174. # A set of secondary zones, retrieved from zonemgr configuration.
  175. self._secondary_zones = None
  176. # Get necessary configurations from remote modules.
  177. for mod in [(AUTH_MODULE_NAME, self.__auth_config_handler),
  178. (ZONEMGR_MODULE_NAME, self.__zonemgr_config_handler)]:
  179. self.__add_remote_module(mod[0], mod[1])
  180. # This should succeed as long as cfgmgr is up.
  181. isc.server_common.tsig_keyring.init_keyring(self._cc)
  182. self._shutdown = False
  183. # List of the session receivers where we get the requests
  184. self._socksession_receivers = {}
  185. clear_socket()
  186. self._listen_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  187. self._listen_socket.bind(SOCKET_FILE)
  188. self._listen_socket.listen(16)
  189. # Create reusable resources
  190. self.__request_msg = Message(Message.PARSE)
  191. self.__response_renderer = MessageRenderer()
  192. # The following attribute(s) are essentially private, but defined as
  193. # "protected" so that test code can customize/inspect them.
  194. # They should not be overridden/referenced for any other purposes.
  195. #
  196. # DDNS Protocol handling class.
  197. self._UpdateSessionClass = isc.ddns.session.UpdateSession
  198. # Outstanding TCP context: fileno=>(context_obj, dst)
  199. self._tcp_ctxs = {}
  200. # Notify Auth server that DDNS update messages can now be forwarded
  201. self.__notify_start_forwarder()
  202. class InternalError(Exception):
  203. '''Exception for internal errors in an update session.
  204. This exception is expected to be caught within the server class,
  205. only used for controling the code flow.
  206. '''
  207. pass
  208. def config_handler(self, new_config):
  209. '''Update config data.'''
  210. try:
  211. if 'zones' in new_config:
  212. self._zone_config = \
  213. self.__update_zone_config(new_config['zones'])
  214. return create_answer(0)
  215. except Exception as ex:
  216. # We catch any exception here. That includes any syntax error
  217. # against the configuration spec. The config interface is too
  218. # complicated and it's not clear how much validation is performed
  219. # there, so, while assuming it's unlikely to happen, we act
  220. # proactively.
  221. logger.error(DDNS_CONFIG_HANDLER_ERROR, ex)
  222. return create_answer(1, "Failed to handle new configuration: " +
  223. str(ex))
  224. def __update_zone_config(self, new_zones_config):
  225. '''Handle zones configuration update.'''
  226. new_zones = {}
  227. for zone_config in new_zones_config:
  228. origin = Name(zone_config['origin'])
  229. rrclass = RRClass(zone_config['class'])
  230. update_acl = zone_config['update_acl']
  231. new_zones[(origin, rrclass)] = REQUEST_LOADER.load(update_acl)
  232. return new_zones
  233. def command_handler(self, cmd, args):
  234. '''
  235. Handle a CC session command, as sent from bindctl or other
  236. BIND 10 modules.
  237. '''
  238. # TODO: Handle exceptions and turn them to an error response
  239. if cmd == "shutdown":
  240. logger.info(DDNS_RECEIVED_SHUTDOWN_COMMAND)
  241. self.trigger_shutdown()
  242. answer = create_answer(0)
  243. elif cmd == "auth_started":
  244. self.__notify_start_forwarder()
  245. answer = None
  246. else:
  247. answer = create_answer(1, "Unknown command: " + str(cmd))
  248. return answer
  249. def __add_remote_module(self, mod_name, callback):
  250. '''Register interest in other module's config with a callback.'''
  251. # Due to startup timing, add_remote_config can fail. We could make it
  252. # more sophisticated, but for now we simply retry a few times, each
  253. # separated by a short period (3 times and 1 sec, arbitrary chosen,
  254. # and hardcoded for now). In practice this should be more than
  255. # sufficient, but if it turns out to be a bigger problem we can
  256. # consider more elegant solutions.
  257. for n_try in range(0, 3):
  258. try:
  259. # by_name() version can fail with ModuleSpecError in getting
  260. # the module spec because cfgmgr returns a "successful" answer
  261. # with empty data if it cannot find the specified module.
  262. # This seems to be a deviant behavior (see Trac #2039), but
  263. # we need to deal with it.
  264. self._cc.add_remote_config_by_name(mod_name, callback)
  265. return
  266. except (ModuleSpecError, ModuleCCSessionError) as ex:
  267. logger.warn(DDNS_GET_REMOTE_CONFIG_FAIL, mod_name, n_try + 1,
  268. ex)
  269. last_ex = ex
  270. add_pause(1)
  271. raise last_ex
  272. def __auth_config_handler(self, new_config, module_config):
  273. logger.info(DDNS_RECEIVED_AUTH_UPDATE)
  274. # If we've got the config before and the new config doesn't update
  275. # the DB file, there's nothing we should do with it.
  276. # Note: there seems to be a bug either in bindctl or cfgmgr, and
  277. # new_config can contain 'database_file' even if it's not really
  278. # updated. We still perform the check so we can avoid redundant
  279. # resetting when the bug is fixed. The redundant reset itself is not
  280. # good, but such configuration update should not happen so often and
  281. # it should be acceptable in practice.
  282. if self._datasrc_info is not None and \
  283. not 'database_file' in new_config:
  284. return
  285. rrclass, client, db_file = get_datasrc_client(self._cc)
  286. self._datasrc_info = (rrclass, client)
  287. logger.info(DDNS_AUTH_DBFILE_UPDATE, db_file)
  288. def __zonemgr_config_handler(self, new_config, module_config):
  289. logger.info(DDNS_RECEIVED_ZONEMGR_UPDATE)
  290. # If we've got the config before and the new config doesn't update
  291. # the secondary zone list, there's nothing we should do with it.
  292. # (Same note as that for auth's config applies)
  293. if self._secondary_zones is not None and \
  294. not 'secondary_zones' in new_config:
  295. return
  296. # Get the latest secondary zones. Use get_remote_config_value() so
  297. # it can work for both the initial default case and updates.
  298. sec_zones, _ = self._cc.get_remote_config_value(ZONEMGR_MODULE_NAME,
  299. 'secondary_zones')
  300. new_secondary_zones = set()
  301. try:
  302. # Parse the new config and build a new list of secondary zones.
  303. # Unfortunately, in the current implementation, even an observer
  304. # module needs to perform full validation. This should be changed
  305. # so that only post-validation (done by the main module) config is
  306. # delivered to observer modules, but until it's supported we need
  307. # to protect ourselves.
  308. for zone_spec in sec_zones:
  309. zname = Name(zone_spec['name'])
  310. # class has the default value in case it's unspecified.
  311. # ideally this should be merged within the config module, but
  312. # the current implementation doesn't esnure that, so we need to
  313. # subsitute it ourselves.
  314. if 'class' in zone_spec:
  315. zclass = RRClass(zone_spec['class'])
  316. else:
  317. zclass = RRClass(module_config.get_default_value(
  318. 'secondary_zones/class'))
  319. new_secondary_zones.add((zname, zclass))
  320. self._secondary_zones = new_secondary_zones
  321. logger.info(DDNS_SECONDARY_ZONES_UPDATE, len(self._secondary_zones))
  322. except Exception as ex:
  323. logger.error(DDNS_SECONDARY_ZONES_UPDATE_FAIL, ex)
  324. def trigger_shutdown(self):
  325. '''Initiate a shutdown sequence.
  326. This method is expected to be called in various ways including
  327. in the middle of a signal handler, and is designed to be as simple
  328. as possible to minimize side effects. Actual shutdown will take
  329. place in a normal control flow.
  330. '''
  331. logger.info(DDNS_SHUTDOWN)
  332. self._shutdown = True
  333. def shutdown_cleanup(self):
  334. '''
  335. Perform any cleanup that is necessary when shutting down the server.
  336. Do NOT call this to initialize shutdown, use trigger_shutdown().
  337. '''
  338. # tell Auth not to forward UPDATE messages anymore
  339. self.__notify_stop_forwarder()
  340. # tell the ModuleCCSession to send a message that this module is
  341. # stopping.
  342. self._cc.send_stopping()
  343. # make sure any open socket is explicitly closed, per Python
  344. # convention.
  345. self._listen_socket.close()
  346. def accept(self):
  347. """
  348. Accept another connection and create the session receiver.
  349. """
  350. try:
  351. (sock, remote_addr) = self._listen_socket.accept()
  352. fileno = sock.fileno()
  353. logger.debug(TRACE_BASIC, DDNS_NEW_CONN, fileno,
  354. remote_addr if remote_addr else '<anonymous address>')
  355. receiver = isc.util.cio.socketsession.SocketSessionReceiver(sock)
  356. self._socksession_receivers[fileno] = (sock, receiver)
  357. except (socket.error, isc.util.cio.socketsession.SocketSessionError) \
  358. as e:
  359. # These exceptions mean the connection didn't work, but we can
  360. # continue with the rest
  361. logger.error(DDNS_ACCEPT_FAILURE, e)
  362. def __check_request_tsig(self, msg, req_data):
  363. '''TSIG checker for update requests.
  364. This is a helper method for handle_request() below. It examines
  365. the given update request message to see if it contains a TSIG RR,
  366. and verifies the signature if it does. It returs the TSIG context
  367. used for the verification, or None if the request doesn't contain
  368. a TSIG. If the verification fails it simply raises an exception
  369. as handle_request() assumes it should succeed.
  370. '''
  371. tsig_record = msg.get_tsig_record()
  372. if tsig_record is None:
  373. return None
  374. tsig_ctx = TSIGContext(tsig_record.get_name(),
  375. tsig_record.get_rdata().get_algorithm(),
  376. isc.server_common.tsig_keyring.get_keyring())
  377. tsig_error = tsig_ctx.verify(tsig_record, req_data)
  378. if tsig_error != TSIGError.NOERROR:
  379. raise self.InternalError("Failed to verify request's TSIG: " +
  380. str(tsig_error))
  381. return tsig_ctx
  382. def handle_request(self, req_session):
  383. """
  384. This is the place where the actual DDNS processing is done. Other
  385. methods are either subroutines of this method or methods doing the
  386. uninteresting "accounting" stuff, like accepting socket,
  387. initialization, etc.
  388. It is called with the request being session as received from
  389. SocketSessionReceiver, i.e. tuple
  390. (socket, local_address, remote_address, data).
  391. In general, this method doesn't propagate exceptions outside the
  392. method. Most of protocol or system errors will result in an error
  393. response to the update client or dropping the update request.
  394. The update session class should also ensure this. Critical exceptions
  395. such as memory allocation failure will be propagated, however, and
  396. will subsequently terminate the server process.
  397. Return: True if a response to the request is successfully sent;
  398. False otherwise. The return value wouldn't be useful for the server
  399. itself; it's provided mainly for testing purposes.
  400. """
  401. # give tuple elements intuitive names
  402. (sock, local_addr, remote_addr, req_data) = req_session
  403. # The session sender (b10-auth) should have made sure that this is
  404. # a validly formed DNS message of OPCODE being UPDATE, and if it's
  405. # TSIG signed, its key is known to the system and the signature is
  406. # valid. Messages that don't meet these should have been resopnded
  407. # or dropped by the sender, so if such error is detected we treat it
  408. # as an internal error and don't bother to respond.
  409. try:
  410. self.__request_msg.clear(Message.PARSE)
  411. # specify PRESERVE_ORDER as we need to handle each RR separately.
  412. self.__request_msg.from_wire(req_data, Message.PRESERVE_ORDER)
  413. if self.__request_msg.get_opcode() != Opcode.UPDATE:
  414. raise self.InternalError('Update request has unexpected '
  415. 'opcode: ' +
  416. str(self.__request_msg.get_opcode()))
  417. tsig_ctx = self.__check_request_tsig(self.__request_msg, req_data)
  418. except Exception as ex:
  419. logger.error(DDNS_REQUEST_PARSE_FAIL, ex)
  420. return False
  421. # Let an update session object handle the request. Note: things around
  422. # ZoneConfig will soon be substantially revised. For now we don't
  423. # bother to generalize it.
  424. zone_cfg = ZoneConfig(self._secondary_zones, self._datasrc_info[0],
  425. self._datasrc_info[1], self._zone_config)
  426. update_session = self._UpdateSessionClass(self.__request_msg,
  427. remote_addr, zone_cfg)
  428. result, zname, zclass = update_session.handle()
  429. # If the request should be dropped, we're done; otherwise, send the
  430. # response generated by the session object.
  431. if result == isc.ddns.session.UPDATE_DROP:
  432. return False
  433. msg = update_session.get_message()
  434. self.__response_renderer.clear()
  435. if tsig_ctx is not None:
  436. msg.to_wire(self.__response_renderer, tsig_ctx)
  437. else:
  438. msg.to_wire(self.__response_renderer)
  439. ret = self.__send_response(sock, self.__response_renderer.get_data(),
  440. remote_addr)
  441. if result == isc.ddns.session.UPDATE_SUCCESS:
  442. self.__notify_auth(zname, zclass)
  443. self.__notify_xfrout(zname, zclass)
  444. return ret
  445. def __send_response(self, sock, data, dest):
  446. '''Send DDNS response to the client.
  447. Right now, this is a straightforward subroutine of handle_request(),
  448. but is intended to be extended evetually so that it can handle more
  449. comlicated operations for TCP (which requires asynchronous write).
  450. Further, when we support multiple requests over a single TCP
  451. connection, this method may even be shared by multiple methods.
  452. Parameters:
  453. sock: (python socket) the socket to which the response should be sent.
  454. data: (binary) the response data
  455. dest: (python socket address) the destion address to which the response
  456. should be sent.
  457. Return: True if the send operation succeds; otherwise False.
  458. '''
  459. try:
  460. if sock.proto == socket.IPPROTO_UDP:
  461. sock.sendto(data, dest)
  462. else:
  463. tcp_ctx = DNSTCPContext(sock)
  464. send_result = tcp_ctx.send(data)
  465. if send_result == DNSTCPContext.SENDING:
  466. self._tcp_ctxs[sock.fileno()] = (tcp_ctx, dest)
  467. elif send_result == DNSTCPContext.CLOSED:
  468. raise socket.error("socket error in TCP send")
  469. else:
  470. tcp_ctx.close()
  471. except socket.error as ex:
  472. logger.warn(DDNS_RESPONSE_SOCKET_SEND_FAILED, ClientFormatter(dest), ex)
  473. return False
  474. return True
  475. def __notify_start_forwarder(self):
  476. '''Notify auth that DDNS Update messages can now be forwarded'''
  477. try:
  478. self._cc.rpc_call("start_ddns_forwarder", AUTH_MODULE_NAME)
  479. except (SessionTimeout, SessionError, ProtocolError,
  480. RPCRecipientMissing) as ex:
  481. logger.error(DDNS_START_FORWARDER_FAIL, ex)
  482. except RPCError as e:
  483. logger.error(DDNS_START_FORWARDER_ERROR, e)
  484. def __notify_stop_forwarder(self):
  485. '''Notify auth that DDNS Update messages should no longer be forwarded.
  486. '''
  487. try:
  488. self._cc.rpc_call("stop_ddns_forwarder", AUTH_MODULE_NAME)
  489. except (SessionTimeout, SessionError, ProtocolError,
  490. RPCRecipientMissing) as ex:
  491. logger.error(DDNS_STOP_FORWARDER_FAIL, ex)
  492. except RPCError as e:
  493. logger.error(DDNS_STOP_FORWARDER_ERROR, e)
  494. def __notify_auth(self, zname, zclass):
  495. '''Notify auth of the update, if necessary.'''
  496. self.__notify_update(AUTH_MODULE_NAME, AUTH_LOADZONE_COMMAND,
  497. auth_loadzone_params(zname, zclass), zname,
  498. zclass)
  499. def __notify_xfrout(self, zname, zclass):
  500. '''Notify xfrout of the update.'''
  501. param = {'zone_name': zname.to_text(), 'zone_class': zclass.to_text()}
  502. self.__notify_update(XFROUT_MODULE_NAME, 'notify', param, zname,
  503. zclass)
  504. def __notify_update(self, modname, command, params, zname, zclass):
  505. '''Notify other module of the update.
  506. Note that we use blocking communication here. While the internal
  507. communication bus is generally expected to be pretty responsive and
  508. error free, notable delay can still occur, and in worse cases timeouts
  509. or connection reset can happen. In these cases, even if the trouble
  510. is temporary, the update service will be suspended for a while.
  511. For a longer term we'll need to switch to asynchronous communication,
  512. but for now we rely on the blocking operation.
  513. '''
  514. try:
  515. # FIXME? Is really rpc_call the correct one? What if there are more
  516. # than one recipient of the given kind? What if none? We need to
  517. # think of some kind of notification/broadcast mechanism.
  518. self._cc.rpc_call(command, modname, params=params)
  519. logger.debug(TRACE_BASIC, DDNS_UPDATE_NOTIFY, modname,
  520. ZoneFormatter(zname, zclass))
  521. except (SessionTimeout, SessionError, ProtocolError, RPCError) as ex:
  522. logger.error(DDNS_UPDATE_NOTIFY_FAIL, modname,
  523. ZoneFormatter(zname, zclass), ex)
  524. def handle_session(self, fileno):
  525. """Handle incoming session on the socket with given fileno.
  526. Return True if a response (whether positive or negative) has been
  527. sent; otherwise False. The return value isn't expected to be used
  528. for other purposes than testing.
  529. """
  530. logger.debug(TRACE_BASIC, DDNS_SESSION, fileno)
  531. (session_socket, receiver) = self._socksession_receivers[fileno]
  532. try:
  533. req_session = receiver.pop()
  534. (sock, remote_addr) = (req_session[0], req_session[2])
  535. # If this is a TCP client, check the quota, and immediately reject
  536. # it if we cannot accept more.
  537. if sock.proto == socket.IPPROTO_TCP and \
  538. len(self._tcp_ctxs) >= self.TCP_CLIENTS:
  539. logger.warn(DDNS_REQUEST_TCP_QUOTA,
  540. ClientFormatter(remote_addr), len(self._tcp_ctxs))
  541. sock.close()
  542. return False
  543. return self.handle_request(req_session)
  544. except isc.util.cio.socketsession.SocketSessionError as se:
  545. # No matter why this failed, the connection is in unknown, possibly
  546. # broken state. So, we close the socket and remove the receiver.
  547. del self._socksession_receivers[fileno]
  548. session_socket.close()
  549. logger.warn(DDNS_DROP_CONN, fileno, se)
  550. return False
  551. def run(self):
  552. '''
  553. Get and process all commands sent from cfgmgr or other modules.
  554. This loops waiting for events until self.shutdown() has been called.
  555. '''
  556. logger.info(DDNS_STARTED)
  557. cc_fileno = self._cc.get_socket().fileno()
  558. listen_fileno = self._listen_socket.fileno()
  559. while not self._shutdown:
  560. # In this event loop, we propagate most of exceptions, which will
  561. # subsequently kill the process. We expect the handling functions
  562. # to catch their own exceptions which they can recover from
  563. # (malformed packets, lost connections, etc). The rationale behind
  564. # this is they know best which exceptions are recoverable there
  565. # and an exception may be recoverable somewhere, but not elsewhere.
  566. try:
  567. (reads, writes, exceptions) = \
  568. select.select([cc_fileno, listen_fileno] +
  569. list(self._socksession_receivers.keys()),
  570. list(self._tcp_ctxs.keys()), [])
  571. except select.error as se:
  572. # In case it is just interrupted, we continue like nothing
  573. # happened
  574. if se.args[0] == errno.EINTR:
  575. (reads, writes, exceptions) = ([], [], [])
  576. else:
  577. raise
  578. for fileno in reads:
  579. if fileno == cc_fileno:
  580. self._cc.check_command(True)
  581. elif fileno == listen_fileno:
  582. self.accept()
  583. else:
  584. self.handle_session(fileno)
  585. for fileno in writes:
  586. ctx = self._tcp_ctxs[fileno]
  587. result = ctx[0].send_ready()
  588. if result != DNSTCPContext.SENDING:
  589. if result == DNSTCPContext.CLOSED:
  590. logger.warn(DDNS_RESPONSE_TCP_SOCKET_SEND_FAILED,
  591. ClientFormatter(ctx[1]))
  592. ctx[0].close()
  593. del self._tcp_ctxs[fileno]
  594. self.shutdown_cleanup()
  595. logger.info(DDNS_STOPPED)
  596. def create_signal_handler(ddns_server):
  597. '''
  598. This creates a signal_handler for use in set_signal_handler, which
  599. shuts down the given DDNSServer (or any object that has a shutdown()
  600. method)
  601. '''
  602. def signal_handler(signal, frame):
  603. '''
  604. Handler for process signals. Since only signals to shut down are sent
  605. here, the actual signal is not checked and the server is simply shut
  606. down.
  607. '''
  608. ddns_server.trigger_shutdown()
  609. return signal_handler
  610. def set_signal_handler(signal_handler):
  611. '''
  612. Sets the signal handler(s).
  613. '''
  614. signal.signal(signal.SIGTERM, signal_handler)
  615. signal.signal(signal.SIGINT, signal_handler)
  616. def set_cmd_options(parser):
  617. '''
  618. Helper function to set command-line options
  619. '''
  620. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  621. help="display more about what is going on")
  622. def main(ddns_server=None):
  623. '''
  624. The main function.
  625. Parameters:
  626. ddns_server: If None (default), a DDNSServer object is initialized.
  627. If specified, the given DDNSServer will be used. This is
  628. mainly used for testing.
  629. cc_session: If None (default), a new ModuleCCSession will be set up.
  630. If specified, the given session will be used. This is
  631. mainly used for testing.
  632. '''
  633. try:
  634. parser = OptionParser()
  635. set_cmd_options(parser)
  636. (options, args) = parser.parse_args()
  637. if options.verbose:
  638. print("[b10-ddns] Warning: -v verbose option is ignored at this point.")
  639. if ddns_server is None:
  640. ddns_server = DDNSServer()
  641. set_signal_handler(create_signal_handler(ddns_server))
  642. ddns_server.run()
  643. except KeyboardInterrupt:
  644. logger.info(DDNS_STOPPED_BY_KEYBOARD)
  645. except SessionError as e:
  646. logger.error(DDNS_CC_SESSION_ERROR, str(e))
  647. except (ModuleSpecError, ModuleCCSessionError) as e:
  648. logger.error(DDNS_MODULECC_SESSION_ERROR, str(e))
  649. except DDNSConfigError as e:
  650. logger.error(DDNS_CONFIG_ERROR, str(e))
  651. except SessionTimeout as e:
  652. logger.error(DDNS_CC_SESSION_TIMEOUT_ERROR)
  653. except Exception as e:
  654. logger.error(DDNS_UNCAUGHT_EXCEPTION, type(e).__name__, str(e))
  655. clear_socket()
  656. if '__main__' == __name__:
  657. main()