Coverage for src/bin/xfrout/xfrout : 77%
        
        
Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
| 
 #!/usr/bin/python3 
 # Copyright (C) 2010 Internet Systems Consortium. # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 
 
 
 
 
 # Pending system-wide debug level definitions, the ones we # use here are hardcoded for now 
 
 except ImportError as e: # C++ loadable module may not be installed; even so the xfrout process # must keep running, so we warn about it and move forward. logger.error(XFROUT_IMPORT, str(e)) 
 
 
 """An exception indicating an error in updating xfrout configuration. 
 This exception is raised when the xfrout process encouters an error in handling configuration updates. Not all syntax error can be caught at the module-CC layer, so xfrout needs to (explicitly or implicitly) validate the given configuration data itself. When it finds an error it raises this exception (either directly or by converting an exception from other modules) as a unified error in configuration. """ 
 '''An exception raised for some unexpected events during an xfrout session. ''' 
 global SPECFILE_PATH global AUTH_SPECFILE_PATH global UNIX_SOCKET_FILE UNIX_SOCKET_FILE = os.environ["B10_FROM_SOURCE_LOCALSTATEDIR"] + \ "/auth_xfrout_conn" else: else: else: 
 
 
 # borrowed from xfrin.py @ #1298. We should eventually unify it. """Helper function to format a zone name and class as a string of the form '<name>/<class>'. Parameters: zone_name (isc.dns.Name) name to format zone_class (isc.dns.RRClass) class to format """ 
 # borrowed from xfrin.py @ #1298. """Helper function to format the addrinfo as a string of the form <addr>:<port> (for IPv4) or [<addr>]:port (for IPv6). For unix domain sockets, and unknown address families, it returns a basic string conversion of the third element of the passed tuple. Parameters: addrinfo: a 3-tuple consisting of address family, socket type, and, depending on the family, either a 2-tuple with the address and port, or a filename """ elif addrinfo[0] == socket.AF_INET6: return "[" + str(addrinfo[2][0]) + "]:" + str(addrinfo[2][1]) else: return str(addrinfo[2]) except IndexError: raise TypeError("addrinfo argument to format_addrinfo() does not " "appear to be consisting of (family, socktype, (addr, port))") 
 """Returns the wire length of the given RRset""" 
 '''Extract the serial field of an SOA RDATA and returns it as an Serial object. ''' 
 default_acl, zone_config, client_class=DataSourceClient): 
 tsig_key_ring) 
 ''' Handle a xfrout query, send xfrout response(s). 
 This is separated from the constructor so that we can override it from tests. 
 ''' # Check the xfrout quota. We do both increase/decrease in this # method so it's clear we always release it once acuired. # To avoid resource leak we need catch all possible exceptions # We log it later to exclude the case where even logger raises # an exception. 
 # Release any critical resources 
 
 '''Simply close the socket via the given FD. 
 This is a dedicated subroutine of handle() and is sepsarated from it for the convenience of tests. 
 ''' os.close(self._sock_fd) 
 ''' If request has a tsig record, perform tsig related checks ''' self._tsig_key_ring) 
 
 ''' parse query message to [socket,message]''' #TODO, need to add parseHeader() in case the message header is invalid 
 # TSIG related checks 
 # Make sure the question is valid. This should be ensured by # the auth server, but since it's far from xfrout itself, we check # it by ourselves. A viloation would be an internal bug, so we # raise and stop here rather than returning a FORMERR or SERVFAIL. str(msg.get_rr_count(Message.SECTION_QUESTION))) 
 # Identify the request type else: # Likewise, this should be impossible. str(self._request_type)) 
 # ACL checks isc.acl.dns.RequestContext(self._remote[2], msg.get_tsig_record())) self._request_type, format_addrinfo(self._remote), format_zone_str(zone_name, zone_class)) self._request_type, format_addrinfo(self._remote), format_zone_str(zone_name, zone_class)) 
 
 '''Return the ACL that should be applied for a given zone. 
 The zone is identified by a tuple of name and RR class. If a per zone configuration for the zone exists and contains transfer_acl, that ACL will be used; otherwise, the default ACL will be used. 
 ''' # Internally zone names are managed in lower cased label characters, # so we first need to convert the name. 'transfer_acl' in self._zone_config[config_key]: 
 size = len(data) total_count = 0 while total_count < size: count = os.write(sock_fd, data[total_count:]) total_count += count 
 
 # As defined in RFC5936 section3.4, perform case-preserving name # compression for AXFR message. 
 # XXX Currently, python wrapper doesn't accept 'None' parameter in this case, # we should remove the if statement and use a universal interface later. else: 
 
 
 
 
 '''Retrieve the SOA RR of the given zone. 
 It returns a pair of RCODE and the SOA (in the form of RRset). On success RCODE is NOERROR and returned SOA is not None; on failure RCODE indicates the appropriate code in the context of xfr processing, and the returned SOA is None. 
 ''' # Especially for database-based zones, a working zone may be in # a broken state where it has more than one SOA RR. We proactively # check the condition and abort the xfr attempt if we identify it. 
 '''Setup a zone iterator for AXFR or AXFR-style IXFR. 
 ''' # Note that we enable 'separate_rrs'. In xfr-out we need to # preserve as many things as possible (even if it's half broken) # stored in the zone. True) # If the current name server does not have authority for the # zone, xfrout can't serve for it, return rcode NOTAUTH. # Note: this exception can happen for other reasons. We should # update get_iterator() API so that we can distinguish "no such # zone" and other cases (#1373). For now we consider all these # cases as NOTAUTH. 
 # If we are an authoritative name server for the zone, but fail # to find the zone's SOA record in datasource, xfrout can't # provide zone transfer for it. 
 
 '''Setup a zone journal reader for IXFR. 
 If the underlying data source does not know the requested range of zone differences it automatically falls back to AXFR-style IXFR by setting up a zone iterator instead of a journal reader. 
 ''' # Check the authority section. Look for a SOA record with # the same name and class as the question. # Ignore data whose owner name is not the zone apex, and # ignore non-SOA or different class of records. auth_rrset.get_type() != RRType.SOA() or \ auth_rrset.get_class() != zone_class: format_addrinfo(self._remote)) 
 # Retrieve the local SOA 
 # RFC1995 says "If an IXFR query with the same or newer version # number than that of the server is received, it is replied to with # a single SOA record of the server's current version, just as # in AXFR". The claim about AXFR is incorrect, but other than that, # we do as the RFC says. # clear both iterator and jnl_reader to signal we won't do # iteration in response generation format_zone_str(zone_name, zone_class), begin_serial, end_serial) 
 # Set up the journal reader or fall back to AXFR-style IXFR zone_name, begin_serial.get_value(), end_serial.get_value()) # The underlying data source doesn't support journaling. # Fall back to AXFR-style IXFR. format_addrinfo(self._remote), format_zone_str(zone_name, zone_class)) format_zone_str(zone_name, zone_class), begin_serial, end_serial) # this is quite unexpected as we know zone's SOA exists. # It might be a bug or the data source is somehow broken, # but it can still happen if someone has removed the zone # between these two operations. We treat it as NOTAUTH. format_zone_str(zone_name, zone_class)) 
 # Use the reader as the iterator to generate the response. 
 
 '''Setup a context for xfr responses according to the request type. 
 This method identifies the most appropriate data source for the request and set up a zone iterator or journal reader depending on whether the request is AXFR or IXFR. If it identifies any protocol level error it returns an RCODE other than NOERROR. 
 ''' 
 # Identify the data source for the requested zone and see if it has # SOA while initializing objects used for request processing later. # We should eventually generalize this so that we can choose the # appropriate data source from (possible) multiple candidates. # We should eventually take into account the RR class here. # For now, we hardcode a particular type (SQLite3-based), and only # consider that one. self._server.get_db_file() + '"}' 
 else: 
 #TODO. create query message and parse header return return self._reply_query_with_error_rcode(msg, sock_fd, rcode_) Rcode.FORMERR()) format_addrinfo(self._remote), self._server._max_transfers_out) Rcode.REFUSED()) 
 
 format_addrinfo(self._remote), zone_str, ex) format_addrinfo(self._remote), zone_str, rcode_) 
 format_addrinfo(self._remote), zone_str) except Exception as err: logger.error(XFROUT_XFR_TRANSFER_ERROR, self._request_typestr, format_addrinfo(self._remote), zone_str, err) format_addrinfo(self._remote), zone_str) 
 
 
 message_upper_len): '''Add the SOA record to the end of message. 
 If it would exceed the maximum allowable size of a message, a new message will be created to send out the last SOA. 
 We assume a message with a single SOA can always fit the buffer with or without TSIG. In theory this could be wrong if TSIG is stupidly large, but in practice this assumption should be reasonable. ''' XFROUT_MAX_MESSAGE_SIZE: 
 
 # Reserved space for the fixed header size, the size of the question # section, and TSIG size (when included). The size of the question # section is the sum of the qname length and the size of the # fixed-length fields (type and class, 2 bytes each). msg.get_question()[0].get_name().get_length() + 4 + \ self._tsig_len 
 # If the iterator is None, we are responding to IXFR with a single # SOA RR. message_upper_len) 
 # Add the beginning SOA 
 # Add the rest of the zone/diff contets # Check if xfrout is shutdown logger.info(XFROUT_STOPPING) return 
 # For AXFR (or AXFR-style IXFR), in which case _jnl_reader is None, # we should skip SOAs from the iterator. 
 # We calculate the maximum size of the RRset (i.e. the # size without compression) and use that to see if we # may have reached the limit 
 
 # RR would not fit. If there are other RRs in the buffer, send # them now and leave this RR to the next message. 
 # Create a new message and reserve space for the carried-over # RR (and TSIG space in case it's to be TSIG signed) self._tsig_len 
 # If this RR overflows the buffer all by itself, fail. In theory # some RRs might fit in a TCP message when compressed even if they # do not fit when uncompressed, but surely we don't want to send # such monstrosities to an unsuspecting slave. str(rrset_len) + ' bytes)') 
 # Add the RRset to the new message 
 # Add and send the trailing SOA message_upper_len) 
 ThreadingUnixStreamServer): '''The unix domain socket server which accept xfr query sent from auth server.''' 
 cc): self._remove_unused_sock_file(sock_file) self._sock_file = sock_file socketserver_mixin.NoPollMixIn.__init__(self) ThreadingUnixStreamServer.__init__(self, sock_file, handle_class) self._shutdown_event = shutdown_event self._write_sock, self._read_sock = socket.socketpair() self._common_init() self._cc = cc self.update_config_data(config_data) 
 '''Initialization shared with the mock server class used for tests''' 
 ''' receive request message from sock''' # receive data length return None # receive data return None 
 
 ''' Enable server handle a request until shutdown or auth is closed.''' try: request, client_address = self.get_request() except socket.error: logger.error(XFROUT_FETCH_REQUEST_ERROR) return 
 # Check self._shutdown_event to ensure the real shutdown comes. # Linux could trigger a spurious readable event on the _read_sock # due to a bug, so we need perform a double check. while not self._shutdown_event.is_set(): # Check if xfrout is shutdown try: (rlist, wlist, xlist) = select.select([self._read_sock, request], [], []) except select.error as e: if e.args[0] == errno.EINTR: (rlist, wlist, xlist) = ([], [], []) continue else: logger.error(XFROUT_SOCKET_SELECT_ERROR, str(e)) break 
 # self.server._shutdown_event will be set by now, if it is not a false # alarm if self._read_sock in rlist: continue 
 try: self.process_request(request) except Exception as pre: logger.error(XFROUT_PROCESS_REQUEST_ERROR, str(pre)) break 
 """Override the function _handle_request_noblock(), it creates a new thread to handle requests for each auth""" td = threading.Thread(target=self.handle_request) td.setDaemon(True) td.start() 
 """Receive socket fd and query message from auth, then start a new thread to process the request.""" sock_fd = recv_fd(request.fileno()) if sock_fd < 0: # This may happen when one xfrout process try to connect to # xfrout unix socket server, to check whether there is another # xfrout running. if sock_fd == FD_SYSTEM_ERROR: logger.error(XFROUT_RECEIVE_FILE_DESCRIPTOR_ERROR) return 
 # receive request msg request_data = self._receive_query_message(request) if not request_data: return 
 t = threading.Thread(target=self.finish_request, args = (sock_fd, request_data)) if self.daemon_threads: t.daemon = True t.start() 
 """Guess remote address and port of the socket. 
 The sock_fd must be a file descriptor of a socket. This method retuns a 3-tuple consisting of address family, socket type, and a 2-tuple with the address (string) and port (int). 
 """ # This uses a trick. If the socket is IPv4 in reality and we pretend # it to be IPv6, it returns IPv4 address anyway. This doesn't seem # to care about the SOCK_STREAM parameter at all (which it really is, # except for testing) else: # To make it work even on hosts without IPv6 support # (Any idea how to simulate this in test?) 
 # Identify the correct socket family. Due to the above "trick", # we cannot simply use sock.family. 
 '''Finish one request by instantiating RequestHandlerClass. 
 This is an entry point of a separate thread spawned in UnixSockServer.process_request(). 
 This method creates a XfroutSession object. ''' isc.server_common.tsig_keyring.get_keyring(), self._guess_remote(sock_fd), acl, zone_config) 
 '''Try to remove the socket file. If the file is being used by one running xfrout process, exit from python. If it's not a socket file or nobody is listening , it will be removed. If it can't be removed, exit from python. ''' else: return 
 
 '''Check whether the socket file 'sock_file' exists and is being used by one running xfrout process. If it is, return True, or else return False. ''' else: 
 self._write_sock.send(b"shutdown") #terminate the xfrout session thread super().shutdown() # call the shutdown() of class socketserver_mixin.NoPollMixIn try: os.unlink(self._sock_file) except Exception as e: logger.error(XFROUT_REMOVE_UNIX_SOCKET_FILE_ERROR, self._sock_file, str(e)) 
 '''Apply the new config setting of xfrout module. 
 ''' str(e)) 
 
 
 # convert the class, origin (name) pair. First build pydnspp # object to reject invalid input. #zclass_str = 'IN' # temporary 
 # reject duplicate config str(zorigin) + '/' + str(zclass)) 
 # create a new config entry, build any given (and known) config REQUEST_LOADER.load(zconf['transfer_acl']) 'for ' + zorigin.to_text() + '/' + zclass_str + ': ' + str(e)) 
 # this too should be unnecessary, but currently the # 'from build' override isn't stored in the config # (and we don't have indirect python access to datasources yet) file = os.environ["B10_FROM_BUILD"] + os.sep + "bind10_zones.sqlite3" 
 
 '''Return False, if counter + 1 > max_transfers_out, or else return True ''' 
 
 self._unix_socket_server = None self._listen_sock_file = UNIX_SOCKET_FILE self._shutdown_event = threading.Event() self._cc = isc.config.ModuleCCSession(SPECFILE_LOCATION, self.config_handler, self.command_handler) self._config_data = self._cc.get_full_config() self._cc.start() self._cc.add_remote_config(AUTH_SPECFILE_LOCATION) isc.server_common.tsig_keyring.init_keyring(self._cc) self._start_xfr_query_listener() self._start_notifier() 
 '''Start a new thread to accept xfr query. ''' self._unix_socket_server = UnixSockServer(self._listen_sock_file, XfroutSession, self._shutdown_event, self._config_data, self._cc) listener = threading.Thread(target=self._unix_socket_server.serve_forever) listener.start() 
 datasrc = self._unix_socket_server.get_db_file() self._notifier = notify_out.NotifyOut(datasrc) self._notifier.dispatcher() 
 return self._notifier.send_notify(zone_name, zone_class) 
 '''Update config data. TODO. Do error check''' answer = create_answer(0) for key in new_config: if key not in self._config_data: answer = create_answer(1, "Unknown config data: " + str(key)) continue self._config_data[key] = new_config[key] 
 if self._unix_socket_server: try: self._unix_socket_server.update_config_data(self._config_data) except Exception as e: answer = create_answer(1, "Failed to handle new configuration: " + str(e)) 
 return answer 
 
 ''' shutdown the xfrout process. The thread which is doing zone transfer-out should be terminated. ''' 
 global xfrout_server self._unix_socket_server.shutdown() 
 # Wait for all threads to terminate. this is a call that is only used # in shutdown(), but it has its own method, so we can test shutdown # without involving thread operations (the test would override this # method) main_thread = threading.currentThread() for th in threading.enumerate(): if th is main_thread: continue th.join() 
 if cmd == "shutdown": logger.info(XFROUT_RECEIVED_SHUTDOWN_COMMAND) self.shutdown() answer = create_answer(0) 
 elif cmd == notify_out.ZONE_NEW_DATA_READY_CMD: zone_name = args.get('zone_name') zone_class = args.get('zone_class') if not zone_class: zone_class = str(RRClass.IN()) if zone_name: logger.info(XFROUT_NOTIFY_COMMAND, zone_name, zone_class) if self.send_notify(zone_name, zone_class): answer = create_answer(0) else: zonestr = notify_out.format_zone_str(Name(zone_name), zone_class) answer = create_answer(1, "Unknown zone: " + zonestr) else: answer = create_answer(1, "Bad command parameter:" + str(args)) 
 else: answer = create_answer(1, "Unknown command:" + str(cmd)) 
 return answer 
 '''Get and process all commands sent from cfgmgr or other modules. ''' logger.debug(DBG_PROCESS, XFROUT_STARTED) while not self._shutdown_event.is_set(): self._cc.check_command(False) 
 
 
 if xfrout_server: xfrout_server.shutdown() sys.exit(0) 
 signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGINT, signal_handler) 
 parser.add_option("-v", "--verbose", dest="verbose", action="store_true", help="display more about what is going on") 
 try: parser = OptionParser() set_cmd_options(parser) (options, args) = parser.parse_args() VERBOSE_MODE = options.verbose 
 set_signal_handler() xfrout_server = XfroutServer() xfrout_server.run() except KeyboardInterrupt: logger.INFO(XFROUT_STOPPED_BY_KEYBOARD) except SessionError as e: logger.error(XFROUT_CC_SESSION_ERROR, str(e)) except ModuleCCSessionError as e: logger.error(XFROUT_MODULECC_SESSION_ERROR, str(e)) except XfroutConfigError as e: logger.error(XFROUT_CONFIG_ERROR, str(e)) except SessionTimeout as e: logger.error(XFROUT_CC_SESSION_TIMEOUT_ERROR) 
 if xfrout_server: xfrout_server.shutdown() 
  |