"Fossies" - the Fresh Open Source Software Archive

Member "nsd-4.3.7/xfrd.c" (22 Jul 2021, 79912 Bytes) of package /linux/misc/dns/nsd-4.3.7.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "xfrd.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 4.3.6_vs_4.3.7.

    1 /*
    2  * xfrd.c - XFR (transfer) Daemon source file. Coordinates SOA updates.
    3  *
    4  * Copyright (c) 2001-2006, NLnet Labs. All rights reserved.
    5  *
    6  * See LICENSE for the license.
    7  *
    8  */
    9 
   10 #include "config.h"
   11 #include <assert.h>
   12 #include <string.h>
   13 #include <unistd.h>
   14 #include <stdlib.h>
   15 #include <errno.h>
   16 #include <sys/types.h>
   17 #include <sys/wait.h>
   18 #include "xfrd.h"
   19 #include "xfrd-tcp.h"
   20 #include "xfrd-disk.h"
   21 #include "xfrd-notify.h"
   22 #include "options.h"
   23 #include "util.h"
   24 #include "netio.h"
   25 #include "region-allocator.h"
   26 #include "nsd.h"
   27 #include "packet.h"
   28 #include "rdata.h"
   29 #include "difffile.h"
   30 #include "ipc.h"
   31 #include "remote.h"
   32 #include "rrl.h"
   33 #ifdef USE_DNSTAP
   34 #include "dnstap/dnstap_collector.h"
   35 #endif
   36 
   37 #ifdef HAVE_SYSTEMD
   38 #include <systemd/sd-daemon.h>
   39 #endif
   40 
   41 #define XFRD_UDP_TIMEOUT 10 /* seconds, before a udp request times out */
   42 #define XFRD_NO_IXFR_CACHE 172800 /* 48h before retrying ixfr's after notimpl */
   43 #define XFRD_MAX_ROUNDS 1 /* max number of rounds along the masters */
   44 #define XFRD_TSIG_MAX_UNSIGNED 103 /* max number of packets without tsig in a tcp stream. */
   45             /* rfc recommends 100, +3 for offbyone errors/interoperability. */
   46 #define XFRD_CHILD_REAP_TIMEOUT 60 /* seconds to wakeup and reap lost children */
   47         /* these are reload processes that SIGCHILDed but the signal
   48          * was lost, and need waitpid to remove their process entry. */
   49 
   50 /* the daemon state */
   51 xfrd_state_type* xfrd = 0;
   52 
   53 /* main xfrd loop */
   54 static void xfrd_main(void);
   55 /* shut down xfrd, close sockets. */
   56 static void xfrd_shutdown(void);
   57 /* delete pending task xfr files in tmp */
   58 static void xfrd_clean_pending_tasks(struct nsd* nsd, udb_base* u);
   59 /* create zone rbtree at start */
   60 static void xfrd_init_zones(void);
   61 /* initial handshake with SOAINFO from main and send expire to main */
   62 static void xfrd_receive_soa(int socket, int shortsoa);
   63 
   64 /* handle incoming notification message. soa can be NULL. true if transfer needed. */
   65 static int xfrd_handle_incoming_notify(xfrd_zone_type* zone,
   66     xfrd_soa_type* soa);
   67 
   68 /* call with buffer just after the soa dname. returns 0 on error. */
   69 static int xfrd_parse_soa_info(buffer_type* packet, xfrd_soa_type* soa);
   70 /* set the zone state to a new state (takes care of expiry messages) */
   71 static void xfrd_set_zone_state(xfrd_zone_type* zone,
   72     enum xfrd_zone_state new_zone_state);
   73 /* set timer for retry amount (depends on zone_state) */
   74 static void xfrd_set_timer_retry(xfrd_zone_type* zone);
   75 /* set timer for refresh timeout (depends on zone_state) */
   76 static void xfrd_set_timer_refresh(xfrd_zone_type* zone);
   77 
   78 /* set reload timeout */
   79 static void xfrd_set_reload_timeout(void);
   80 /* handle reload timeout */
   81 static void xfrd_handle_reload(int fd, short event, void* arg);
   82 /* handle child timeout */
   83 static void xfrd_handle_child_timer(int fd, short event, void* arg);
   84 
   85 /* send ixfr request, returns fd of connection to read on */
   86 static int xfrd_send_ixfr_request_udp(xfrd_zone_type* zone);
   87 /* obtain udp socket slot */
   88 static void xfrd_udp_obtain(xfrd_zone_type* zone);
   89 
   90 /* read data via udp */
   91 static void xfrd_udp_read(xfrd_zone_type* zone);
   92 
   93 /* find master by notify number */
   94 static int find_same_master_notify(xfrd_zone_type* zone, int acl_num_nfy);
   95 
   96 /* set the write timer to activate */
   97 static void xfrd_write_timer_set(void);
   98 
   99 static void
  100 xfrd_signal_callback(int sig, short event, void* ATTR_UNUSED(arg))
  101 {
  102     if(!(event & EV_SIGNAL))
  103         return;
  104     sig_handler(sig);
  105 }
  106 
  107 static struct event* xfrd_sig_evs[10];
  108 static int xfrd_sig_num = 0;
  109 
  110 static void
  111 xfrd_sigsetup(int sig)
  112 {
  113     struct event *ev = xalloc_zero(sizeof(*ev));
  114     assert(xfrd_sig_num <= (int)(sizeof(xfrd_sig_evs)/sizeof(ev)));
  115     xfrd_sig_evs[xfrd_sig_num++] = ev;
  116     signal_set(ev, sig, xfrd_signal_callback, NULL);
  117     if(event_base_set(xfrd->event_base, ev) != 0) {
  118         log_msg(LOG_ERR, "xfrd sig handler: event_base_set failed");
  119     }
  120     if(signal_add(ev, NULL) != 0) {
  121         log_msg(LOG_ERR, "xfrd sig handler: signal_add failed");
  122     }
  123 }
  124 
  125 void
  126 xfrd_init(int socket, struct nsd* nsd, int shortsoa, int reload_active,
  127     pid_t nsd_pid)
  128 {
  129     region_type* region;
  130 
  131     assert(xfrd == 0);
  132     /* to setup signalhandling */
  133     nsd->server_kind = NSD_SERVER_MAIN;
  134 
  135     region = region_create_custom(xalloc, free, DEFAULT_CHUNK_SIZE,
  136         DEFAULT_LARGE_OBJECT_SIZE, DEFAULT_INITIAL_CLEANUP_SIZE, 1);
  137     xfrd = (xfrd_state_type*)region_alloc(region, sizeof(xfrd_state_type));
  138     memset(xfrd, 0, sizeof(xfrd_state_type));
  139     xfrd->region = region;
  140     xfrd->xfrd_start_time = time(0);
  141     xfrd->event_base = nsd_child_event_base();
  142     if(!xfrd->event_base) {
  143         log_msg(LOG_ERR, "xfrd: cannot create event base");
  144         exit(1);
  145     }
  146     xfrd->nsd = nsd;
  147     xfrd->packet = buffer_create(xfrd->region, QIOBUFSZ);
  148     xfrd->udp_waiting_first = NULL;
  149     xfrd->udp_waiting_last = NULL;
  150     xfrd->udp_use_num = 0;
  151     xfrd->got_time = 0;
  152     xfrd->xfrfilenumber = 0;
  153 #ifdef USE_ZONE_STATS
  154     xfrd->zonestat_safe = nsd->zonestatdesired;
  155 #endif
  156     xfrd->activated_first = NULL;
  157     xfrd->ipc_pass = buffer_create(xfrd->region, QIOBUFSZ);
  158     xfrd->last_task = region_alloc(xfrd->region, sizeof(*xfrd->last_task));
  159     udb_ptr_init(xfrd->last_task, xfrd->nsd->task[xfrd->nsd->mytask]);
  160     assert(shortsoa || udb_base_get_userdata(xfrd->nsd->task[xfrd->nsd->mytask])->data == 0);
  161 
  162     xfrd->reload_handler.ev_fd = -1;
  163     xfrd->reload_added = 0;
  164     xfrd->reload_timeout.tv_sec = 0;
  165     xfrd->reload_cmd_last_sent = xfrd->xfrd_start_time;
  166     xfrd->can_send_reload = !reload_active;
  167     xfrd->reload_pid = nsd_pid;
  168     xfrd->child_timer_added = 0;
  169 
  170     xfrd->ipc_send_blocked = 0;
  171     memset(&xfrd->ipc_handler, 0, sizeof(xfrd->ipc_handler));
  172     event_set(&xfrd->ipc_handler, socket, EV_PERSIST|EV_READ,
  173         xfrd_handle_ipc, xfrd);
  174     if(event_base_set(xfrd->event_base, &xfrd->ipc_handler) != 0)
  175         log_msg(LOG_ERR, "xfrd ipc handler: event_base_set failed");
  176     if(event_add(&xfrd->ipc_handler, NULL) != 0)
  177         log_msg(LOG_ERR, "xfrd ipc handler: event_add failed");
  178     xfrd->ipc_handler_flags = EV_PERSIST|EV_READ;
  179     xfrd->ipc_conn = xfrd_tcp_create(xfrd->region, QIOBUFSZ);
  180     /* not reading using ipc_conn yet */
  181     xfrd->ipc_conn->is_reading = 0;
  182     xfrd->ipc_conn->fd = socket;
  183     xfrd->need_to_send_reload = 0;
  184     xfrd->need_to_send_shutdown = 0;
  185     xfrd->need_to_send_stats = 0;
  186 
  187     xfrd->write_zonefile_needed = 0;
  188     if(nsd->options->zonefiles_write)
  189         xfrd_write_timer_set();
  190 
  191     xfrd->notify_waiting_first = NULL;
  192     xfrd->notify_waiting_last = NULL;
  193     xfrd->notify_udp_num = 0;
  194 
  195 #ifdef HAVE_SSL
  196     daemon_remote_attach(xfrd->nsd->rc, xfrd);
  197 #endif
  198 
  199     xfrd->tcp_set = xfrd_tcp_set_create(xfrd->region, nsd->options->tls_cert_bundle);
  200     xfrd->tcp_set->tcp_timeout = nsd->tcp_timeout;
  201 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_GETRANDOM)
  202     srandom((unsigned long) getpid() * (unsigned long) time(NULL));
  203 #endif
  204 
  205     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd pre-startup"));
  206     xfrd_init_zones();
  207     xfrd_receive_soa(socket, shortsoa);
  208     if(nsd->options->xfrdfile != NULL && nsd->options->xfrdfile[0]!=0)
  209         xfrd_read_state(xfrd);
  210     
  211     /* did we get killed before startup was successful? */
  212     if(nsd->signal_hint_shutdown) {
  213         kill(nsd_pid, SIGTERM);
  214         xfrd_shutdown();
  215         return;
  216     }
  217 
  218     /* init libevent signals now, so that in the previous init scripts
  219      * the normal sighandler is called, and can set nsd->signal_hint..
  220      * these are also looked at in sig_process before we run the main loop*/
  221     xfrd_sigsetup(SIGHUP);
  222     xfrd_sigsetup(SIGTERM);
  223     xfrd_sigsetup(SIGQUIT);
  224     xfrd_sigsetup(SIGCHLD);
  225     xfrd_sigsetup(SIGALRM);
  226     xfrd_sigsetup(SIGILL);
  227     xfrd_sigsetup(SIGUSR1);
  228     xfrd_sigsetup(SIGINT);
  229 
  230     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd startup"));
  231 #ifdef HAVE_SYSTEMD
  232     sd_notify(0, "READY=1");
  233 #endif
  234     xfrd_main();
  235 }
  236 
  237 static void
  238 xfrd_process_activated(void)
  239 {
  240     xfrd_zone_type* zone;
  241     while((zone = xfrd->activated_first)) {
  242         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd zone %s activation",
  243             zone->apex_str));
  244         /* pop zone from activated list */
  245         xfrd->activated_first = zone->activated_next;
  246         if(zone->activated_next)
  247             zone->activated_next->activated_prev = NULL;
  248         zone->is_activated = 0;
  249         /* run it : no events, specifically not the TIMEOUT event,
  250          * so that running zone transfers are not interrupted */
  251         xfrd_handle_zone(zone->zone_handler.ev_fd, 0, zone);
  252     }
  253 }
  254 
  255 static void
  256 xfrd_sig_process(void)
  257 {
  258     int status;
  259     pid_t child_pid;
  260 
  261     if(xfrd->nsd->signal_hint_quit || xfrd->nsd->signal_hint_shutdown) {
  262         xfrd->nsd->signal_hint_quit = 0;
  263         xfrd->nsd->signal_hint_shutdown = 0;
  264         xfrd->need_to_send_shutdown = 1;
  265         if(!(xfrd->ipc_handler_flags&EV_WRITE)) {
  266             ipc_xfrd_set_listening(xfrd, EV_PERSIST|EV_READ|EV_WRITE);
  267         }
  268     } else if(xfrd->nsd->signal_hint_reload_hup) {
  269         log_msg(LOG_WARNING, "SIGHUP received, reloading...");
  270         xfrd->nsd->signal_hint_reload_hup = 0;
  271         if(xfrd->nsd->options->zonefiles_check) {
  272             task_new_check_zonefiles(xfrd->nsd->task[
  273                 xfrd->nsd->mytask], xfrd->last_task, NULL);
  274         }
  275         xfrd_set_reload_now(xfrd);
  276     } else if(xfrd->nsd->signal_hint_statsusr) {
  277         xfrd->nsd->signal_hint_statsusr = 0;
  278         xfrd->need_to_send_stats = 1;
  279         if(!(xfrd->ipc_handler_flags&EV_WRITE)) {
  280             ipc_xfrd_set_listening(xfrd, EV_PERSIST|EV_READ|EV_WRITE);
  281         }
  282     } 
  283 
  284     /* collect children that exited. */
  285     xfrd->nsd->signal_hint_child = 0;
  286     while((child_pid = waitpid(-1, &status, WNOHANG)) != -1 && child_pid != 0) {
  287         if(status != 0) {
  288             log_msg(LOG_ERR, "process %d exited with status %d",
  289                 (int)child_pid, status);
  290         }
  291     }
  292     if(!xfrd->child_timer_added) {
  293         struct timeval tv;
  294         tv.tv_sec = XFRD_CHILD_REAP_TIMEOUT;
  295         tv.tv_usec = 0;
  296         memset(&xfrd->child_timer, 0, sizeof(xfrd->child_timer));
  297         event_set(&xfrd->child_timer, -1, EV_TIMEOUT,
  298             xfrd_handle_child_timer, xfrd);
  299         if(event_base_set(xfrd->event_base, &xfrd->child_timer) != 0)
  300             log_msg(LOG_ERR, "xfrd child timer: event_base_set failed");
  301         if(event_add(&xfrd->child_timer, &tv) != 0)
  302             log_msg(LOG_ERR, "xfrd child timer: event_add failed");
  303         xfrd->child_timer_added = 1;
  304     }
  305 }
  306 
  307 static void
  308 xfrd_main(void)
  309 {
  310     /* we may have signals from the startup period, process them */
  311     xfrd_sig_process();
  312     xfrd->shutdown = 0;
  313     while(!xfrd->shutdown)
  314     {
  315         /* process activated zones before blocking in select again */
  316         xfrd_process_activated();
  317         /* dispatch may block for a longer period, so current is gone */
  318         xfrd->got_time = 0;
  319         if(event_base_loop(xfrd->event_base, EVLOOP_ONCE) == -1) {
  320             if (errno != EINTR) {
  321                 log_msg(LOG_ERR,
  322                     "xfrd dispatch failed: %s",
  323                     strerror(errno));
  324             }
  325         }
  326         xfrd_sig_process();
  327     }
  328     xfrd_shutdown();
  329 }
  330 
  331 static void
  332 xfrd_shutdown()
  333 {
  334     xfrd_zone_type* zone;
  335 
  336     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd shutdown"));
  337 #ifdef HAVE_SYSTEMD
  338     sd_notify(0, "STOPPING=1");
  339 #endif
  340     event_del(&xfrd->ipc_handler);
  341     close(xfrd->ipc_handler.ev_fd); /* notifies parent we stop */
  342     zone_list_close(nsd.options);
  343     if(xfrd->nsd->options->xfrdfile != NULL && xfrd->nsd->options->xfrdfile[0]!=0)
  344         xfrd_write_state(xfrd);
  345     if(xfrd->reload_added) {
  346         event_del(&xfrd->reload_handler);
  347         xfrd->reload_added = 0;
  348     }
  349     if(xfrd->child_timer_added) {
  350         event_del(&xfrd->child_timer);
  351         xfrd->child_timer_added = 0;
  352     }
  353     if(xfrd->nsd->options->zonefiles_write) {
  354         event_del(&xfrd->write_timer);
  355     }
  356 #ifdef HAVE_SSL
  357     daemon_remote_close(xfrd->nsd->rc); /* close sockets of rc */
  358 #endif
  359     /* close sockets */
  360     RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones)
  361     {
  362         if(zone->event_added) {
  363             event_del(&zone->zone_handler);
  364             if(zone->zone_handler.ev_fd != -1) {
  365                 close(zone->zone_handler.ev_fd);
  366                 zone->zone_handler.ev_fd = -1;
  367             }
  368             zone->event_added = 0;
  369         }
  370     }
  371     close_notify_fds(xfrd->notify_zones);
  372 
  373     /* wait for server parent (if necessary) */
  374     if(xfrd->reload_pid != -1) {
  375         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd wait for servermain %d",
  376             (int)xfrd->reload_pid));
  377         while(1) {
  378             if(waitpid(xfrd->reload_pid, NULL, 0) == -1) {
  379                 if(errno == EINTR) continue;
  380                 if(errno == ECHILD) break;
  381                 log_msg(LOG_ERR, "xfrd: waitpid(%d): %s",
  382                     (int)xfrd->reload_pid, strerror(errno));
  383             }
  384             break;
  385         }
  386     }
  387 
  388     /* if we are killed past this point this is not a problem,
  389      * some files left in /tmp are cleaned by the OS, but it is neater
  390      * to clean them out */
  391 
  392     /* unlink xfr files for running transfers */
  393     RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones)
  394     {
  395         if(zone->msg_seq_nr)
  396             xfrd_unlink_xfrfile(xfrd->nsd, zone->xfrfilenumber);
  397     }
  398     /* unlink xfr files in not-yet-done task file */
  399     xfrd_clean_pending_tasks(xfrd->nsd, xfrd->nsd->task[xfrd->nsd->mytask]);
  400     xfrd_del_tempdir(xfrd->nsd);
  401 #ifdef HAVE_SSL
  402     daemon_remote_delete(xfrd->nsd->rc); /* ssl-delete secret keys */
  403     if (xfrd->nsd->tls_ctx)
  404         SSL_CTX_free(xfrd->nsd->tls_ctx);
  405 #endif
  406 #ifdef USE_DNSTAP
  407     dt_collector_close(nsd.dt_collector, &nsd);
  408 #endif
  409 
  410     /* process-exit cleans up memory used by xfrd process */
  411     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd shutdown complete"));
  412 #ifdef MEMCLEAN /* OS collects memory pages */
  413     if(xfrd->zones) {
  414         xfrd_zone_type* z;
  415         RBTREE_FOR(z, xfrd_zone_type*, xfrd->zones) {
  416             tsig_delete_record(&z->tsig, NULL);
  417         }
  418     }
  419     if(xfrd->notify_zones) {
  420         struct notify_zone* n;
  421         RBTREE_FOR(n, struct notify_zone*, xfrd->notify_zones) {
  422             tsig_delete_record(&n->notify_tsig, NULL);
  423         }
  424     }
  425     if(xfrd_sig_num > 0) {
  426         int i;
  427         for(i=0; i<xfrd_sig_num; i++) {
  428             signal_del(xfrd_sig_evs[i]);
  429             free(xfrd_sig_evs[i]);
  430         }
  431     }
  432 #ifdef RATELIMIT
  433     rrl_mmap_deinit();
  434 #endif
  435 #ifdef USE_DNSTAP
  436     dt_collector_destroy(nsd.dt_collector, &nsd);
  437 #endif
  438     udb_base_free(nsd.task[0]);
  439     udb_base_free(nsd.task[1]);
  440     event_base_free(xfrd->event_base);
  441     region_destroy(xfrd->region);
  442     nsd_options_destroy(nsd.options);
  443     region_destroy(nsd.region);
  444     log_finalize();
  445 #endif
  446 
  447     exit(0);
  448 }
  449 
  450 static void
  451 xfrd_clean_pending_tasks(struct nsd* nsd, udb_base* u)
  452 {
  453     udb_ptr t;
  454     udb_ptr_new(&t, u, udb_base_get_userdata(u));
  455     /* no dealloc of entries, we delete the entire file when done */
  456     while(!udb_ptr_is_null(&t)) {
  457         if(TASKLIST(&t)->task_type == task_apply_xfr) {
  458             xfrd_unlink_xfrfile(nsd, TASKLIST(&t)->yesno);
  459         }
  460         udb_ptr_set_rptr(&t, u, &TASKLIST(&t)->next);
  461     }
  462     udb_ptr_unlink(&t, u);
  463 }
  464 
  465 void
  466 xfrd_init_slave_zone(xfrd_state_type* xfrd, struct zone_options* zone_opt)
  467 {
  468     int num, num_xot;
  469     xfrd_zone_type *xzone;
  470     xzone = (xfrd_zone_type*)region_alloc(xfrd->region,
  471         sizeof(xfrd_zone_type));
  472     memset(xzone, 0, sizeof(xfrd_zone_type));
  473     xzone->apex = zone_opt->node.key;
  474     xzone->apex_str = zone_opt->name;
  475     xzone->state = xfrd_zone_refreshing;
  476     xzone->zone_options = zone_opt;
  477     /* first retry will use first master */
  478     xzone->master = xzone->zone_options->pattern->request_xfr;
  479     xzone->master_num = 0;
  480     xzone->next_master = 0;
  481     xzone->fresh_xfr_timeout = XFRD_TRANSFER_TIMEOUT_START;
  482 
  483     xzone->soa_nsd_acquired = 0;
  484     xzone->soa_disk_acquired = 0;
  485     xzone->soa_notified_acquired = 0;
  486     /* [0]=1, [1]=0; "." domain name */
  487     xzone->soa_nsd.prim_ns[0] = 1;
  488     xzone->soa_nsd.email[0] = 1;
  489     xzone->soa_disk.prim_ns[0]=1;
  490     xzone->soa_disk.email[0]=1;
  491     xzone->soa_notified.prim_ns[0]=1;
  492     xzone->soa_notified.email[0]=1;
  493 
  494     xzone->zone_handler.ev_fd = -1;
  495     xzone->zone_handler_flags = 0;
  496     xzone->event_added = 0;
  497 
  498     xzone->tcp_conn = -1;
  499     xzone->tcp_waiting = 0;
  500     xzone->udp_waiting = 0;
  501     xzone->is_activated = 0;
  502 
  503     xzone->multi_master_first_master = -1;
  504     xzone->multi_master_update_check = -1;
  505     tsig_create_record_custom(&xzone->tsig, NULL, 0, 0, 4);
  506 
  507     /* set refreshing anyway, if we have data it may be old */
  508     xfrd_set_refresh_now(xzone);
  509 
  510     /*Check all or none of acls use XoT*/
  511     num = 0;
  512     num_xot = 0;
  513     for (; xzone->master != NULL; xzone->master = xzone->master->next, num++) {
  514         if (xzone->master->tls_auth_options != NULL) num_xot++; 
  515     }
  516     if (num_xot != 0 && num != num_xot)
  517         log_msg(LOG_WARNING, "Some but not all request-xfrs for %s have XFR-over-TLS configured",
  518             xzone->apex_str);
  519 
  520     xzone->node.key = xzone->apex;
  521     rbtree_insert(xfrd->zones, (rbnode_type*)xzone);
  522 }
  523 
  524 static void
  525 xfrd_init_zones()
  526 {
  527     struct zone_options *zone_opt;
  528     assert(xfrd->zones == 0);
  529 
  530     xfrd->zones = rbtree_create(xfrd->region,
  531         (int (*)(const void *, const void *)) dname_compare);
  532     xfrd->notify_zones = rbtree_create(xfrd->region,
  533         (int (*)(const void *, const void *)) dname_compare);
  534 
  535     RBTREE_FOR(zone_opt, struct zone_options*, xfrd->nsd->options->zone_options)
  536     {
  537         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: adding %s zone",
  538             zone_opt->name));
  539 
  540         init_notify_send(xfrd->notify_zones, xfrd->region, zone_opt);
  541         if(!zone_is_slave(zone_opt)) {
  542             DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s, "
  543                 "master zone has no outgoing xfr requests",
  544                 zone_opt->name));
  545             continue;
  546         }
  547         xfrd_init_slave_zone(xfrd, zone_opt);
  548     }
  549     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: started server %d "
  550         "secondary zones", (int)xfrd->zones->count));
  551 }
  552 
  553 static void
  554 xfrd_process_soa_info_task(struct task_list_d* task)
  555 {
  556     xfrd_soa_type soa;
  557     xfrd_soa_type* soa_ptr = &soa;
  558     xfrd_zone_type* zone;
  559     DEBUG(DEBUG_IPC,1, (LOG_INFO, "xfrd: process SOAINFO %s",
  560         dname_to_string(task->zname, 0)));
  561     zone = (xfrd_zone_type*)rbtree_search(xfrd->zones, task->zname);
  562     if(task->size <= sizeof(struct task_list_d)+dname_total_size(
  563         task->zname)+sizeof(uint32_t)*6 + sizeof(uint8_t)*2) {
  564         /* NSD has zone without any info */
  565         DEBUG(DEBUG_IPC,1, (LOG_INFO, "SOAINFO for %s lost zone",
  566             dname_to_string(task->zname,0)));
  567         soa_ptr = NULL;
  568     } else {
  569         uint8_t* p = (uint8_t*)task->zname + dname_total_size(
  570             task->zname);
  571         /* read the soa info */
  572         memset(&soa, 0, sizeof(soa));
  573         /* left out type, klass, count for speed */
  574         soa.type = htons(TYPE_SOA);
  575         soa.klass = htons(CLASS_IN);
  576         memmove(&soa.ttl, p, sizeof(uint32_t));
  577         p += sizeof(uint32_t);
  578         soa.rdata_count = htons(7);
  579         memmove(soa.prim_ns, p, sizeof(uint8_t));
  580         p += sizeof(uint8_t);
  581         memmove(soa.prim_ns+1, p, soa.prim_ns[0]);
  582         p += soa.prim_ns[0];
  583         memmove(soa.email, p, sizeof(uint8_t));
  584         p += sizeof(uint8_t);
  585         memmove(soa.email+1, p, soa.email[0]);
  586         p += soa.email[0];
  587         memmove(&soa.serial, p, sizeof(uint32_t));
  588         p += sizeof(uint32_t);
  589         memmove(&soa.refresh, p, sizeof(uint32_t));
  590         p += sizeof(uint32_t);
  591         memmove(&soa.retry, p, sizeof(uint32_t));
  592         p += sizeof(uint32_t);
  593         memmove(&soa.expire, p, sizeof(uint32_t));
  594         p += sizeof(uint32_t);
  595         memmove(&soa.minimum, p, sizeof(uint32_t));
  596         /* p += sizeof(uint32_t); if we wanted to read further */
  597         DEBUG(DEBUG_IPC,1, (LOG_INFO, "SOAINFO for %s %u",
  598             dname_to_string(task->zname,0),
  599             (unsigned)ntohl(soa.serial)));
  600     }
  601 
  602     if(!zone) {
  603         DEBUG(DEBUG_IPC,1, (LOG_INFO, "xfrd: zone %s master zone updated",
  604             dname_to_string(task->zname,0)));
  605         notify_handle_master_zone_soainfo(xfrd->notify_zones,
  606             task->zname, soa_ptr);
  607         return;
  608     }
  609     xfrd_handle_incoming_soa(zone, soa_ptr, xfrd_time());
  610 }
  611 
  612 static void
  613 xfrd_receive_soa(int socket, int shortsoa)
  614 {
  615     sig_atomic_t cmd;
  616     struct udb_base* xtask = xfrd->nsd->task[xfrd->nsd->mytask];
  617     udb_ptr last_task, t;
  618     xfrd_zone_type* zone;
  619 
  620     if(!shortsoa) {
  621         /* put all expired zones into mytask */
  622         udb_ptr_init(&last_task, xtask);
  623         RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones) {
  624             if(zone->state == xfrd_zone_expired) {
  625                 task_new_expire(xtask, &last_task, zone->apex, 1);
  626             }
  627         }
  628         udb_ptr_unlink(&last_task, xtask);
  629     
  630         /* send RELOAD to main to give it this tasklist */
  631         task_process_sync(xtask);
  632         cmd = NSD_RELOAD;
  633         if(!write_socket(socket, &cmd,  sizeof(cmd))) {
  634             log_msg(LOG_ERR, "problems sending reload xfrdtomain: %s",
  635                 strerror(errno));
  636         }
  637     }
  638 
  639     /* receive RELOAD_DONE to get SOAINFO tasklist */
  640     if(block_read(&nsd, socket, &cmd, sizeof(cmd), -1) != sizeof(cmd) ||
  641         cmd != NSD_RELOAD_DONE) {
  642         if(nsd.signal_hint_shutdown)
  643             return;
  644         log_msg(LOG_ERR, "did not get start signal from main");
  645         exit(1);
  646     }
  647     if(block_read(NULL, socket, &xfrd->reload_pid, sizeof(pid_t), -1)
  648         != sizeof(pid_t)) {
  649         log_msg(LOG_ERR, "xfrd cannot get reload_pid");
  650     }
  651 
  652     /* process tasklist (SOAINFO data) */
  653     udb_ptr_unlink(xfrd->last_task, xtask);
  654     /* if shortsoa: then use my own taskdb that nsdparent filled */
  655     if(!shortsoa)
  656         xfrd->nsd->mytask = 1 - xfrd->nsd->mytask;
  657     xtask = xfrd->nsd->task[xfrd->nsd->mytask];
  658     task_remap(xtask);
  659     udb_ptr_new(&t, xtask, udb_base_get_userdata(xtask));
  660     while(!udb_ptr_is_null(&t)) {
  661         xfrd_process_soa_info_task(TASKLIST(&t));
  662         udb_ptr_set_rptr(&t, xtask, &TASKLIST(&t)->next);
  663     }
  664     udb_ptr_unlink(&t, xtask);
  665     task_clear(xtask);
  666     udb_ptr_init(xfrd->last_task, xfrd->nsd->task[xfrd->nsd->mytask]);
  667 
  668     if(!shortsoa) {
  669         /* receive RELOAD_DONE that signals the other tasklist is
  670          * empty, and thus xfrd can operate (can call reload and swap
  671          * to the other, empty, tasklist) */
  672         if(block_read(NULL, socket, &cmd, sizeof(cmd), -1) !=
  673             sizeof(cmd) ||
  674             cmd != NSD_RELOAD_DONE) {
  675             log_msg(LOG_ERR, "did not get start signal 2 from "
  676                 "main");
  677             exit(1);
  678         }
  679     } else {
  680         /* for shortsoa version, do expire later */
  681         /* if expire notifications, put in my task and
  682          * schedule a reload to make sure they are processed */
  683         RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones) {
  684             if(zone->state == xfrd_zone_expired) {
  685                 xfrd_send_expire_notification(zone);
  686             }
  687         }
  688     }
  689 }
  690 
  691 void
  692 xfrd_reopen_logfile(void)
  693 {
  694     if (xfrd->nsd->file_rotation_ok)
  695         log_reopen(xfrd->nsd->log_filename, 0);
  696 }
  697 
  698 void
  699 xfrd_deactivate_zone(xfrd_zone_type* z)
  700 {
  701     if(z->is_activated) {
  702         /* delete from activated list */
  703         if(z->activated_prev)
  704             z->activated_prev->activated_next = z->activated_next;
  705         else    xfrd->activated_first = z->activated_next;
  706         if(z->activated_next)
  707             z->activated_next->activated_prev = z->activated_prev;
  708         z->is_activated = 0;
  709     }
  710 }
  711 
  712 void
  713 xfrd_del_slave_zone(xfrd_state_type* xfrd, const dname_type* dname)
  714 {
  715     xfrd_zone_type* z = (xfrd_zone_type*)rbtree_delete(xfrd->zones, dname);
  716     if(!z) return;
  717     
  718     /* io */
  719     if(z->tcp_waiting) {
  720         /* delete from tcp waiting list */
  721         if(z->tcp_waiting_prev)
  722             z->tcp_waiting_prev->tcp_waiting_next =
  723                 z->tcp_waiting_next;
  724         else xfrd->tcp_set->tcp_waiting_first = z->tcp_waiting_next;
  725         if(z->tcp_waiting_next)
  726             z->tcp_waiting_next->tcp_waiting_prev =
  727                 z->tcp_waiting_prev;
  728         else xfrd->tcp_set->tcp_waiting_last = z->tcp_waiting_prev;
  729         z->tcp_waiting = 0;
  730     }
  731     if(z->udp_waiting) {
  732         /* delete from udp waiting list */
  733         if(z->udp_waiting_prev)
  734             z->udp_waiting_prev->udp_waiting_next =
  735                 z->udp_waiting_next;
  736         else    xfrd->udp_waiting_first = z->udp_waiting_next;
  737         if(z->udp_waiting_next)
  738             z->udp_waiting_next->udp_waiting_prev =
  739                 z->udp_waiting_prev;
  740         else    xfrd->udp_waiting_last = z->udp_waiting_prev;
  741         z->udp_waiting = 0;
  742     }
  743     xfrd_deactivate_zone(z);
  744     if(z->tcp_conn != -1) {
  745         xfrd_tcp_release(xfrd->tcp_set, z);
  746     } else if(z->zone_handler.ev_fd != -1 && z->event_added) {
  747         xfrd_udp_release(z);
  748     } else if(z->event_added)
  749         event_del(&z->zone_handler);
  750     if(z->msg_seq_nr)
  751         xfrd_unlink_xfrfile(xfrd->nsd, z->xfrfilenumber);
  752 
  753     /* tsig */
  754     tsig_delete_record(&z->tsig, NULL);
  755 
  756     /* z->dname is recycled when the zone_options is removed */
  757     region_recycle(xfrd->region, z, sizeof(*z));
  758 }
  759 
  760 void
  761 xfrd_free_namedb(struct nsd* nsd)
  762 {
  763     namedb_close_udb(nsd->db);
  764     namedb_close(nsd->db);
  765     nsd->db = 0;
  766 }
  767 
  768 static void
  769 xfrd_set_timer_refresh(xfrd_zone_type* zone)
  770 {
  771     time_t set_refresh;
  772     time_t set_expire;
  773     time_t set;
  774     if(zone->soa_disk_acquired == 0 || zone->state != xfrd_zone_ok) {
  775         xfrd_set_timer_retry(zone);
  776         return;
  777     }
  778     /* refresh or expire timeout, whichever is earlier */
  779     set_refresh = bound_soa_disk_refresh(zone);
  780     set_expire  = bound_soa_disk_expire(zone);
  781     set = zone->soa_disk_acquired + ( set_refresh < set_expire
  782                                     ? set_refresh : set_expire );
  783 
  784     /* set point in time to period for xfrd_set_timer() */
  785     xfrd_set_timer(zone, within_refresh_bounds(zone,
  786           set > xfrd_time()
  787         ? set - xfrd_time() : XFRD_LOWERBOUND_REFRESH));
  788 }
  789 
  790 static void
  791 xfrd_set_timer_retry(xfrd_zone_type* zone)
  792 {
  793     time_t set_retry;
  794     time_t set_expire;
  795     int mult;
  796     /* perform exponential backoff in all the cases */
  797     if(zone->fresh_xfr_timeout == 0)
  798         zone->fresh_xfr_timeout = XFRD_TRANSFER_TIMEOUT_START;
  799     else {
  800         /* exponential backoff - some master data in zones is paid-for
  801            but non-working, and will not get fixed. */
  802         zone->fresh_xfr_timeout *= 2;
  803         if(zone->fresh_xfr_timeout > XFRD_TRANSFER_TIMEOUT_MAX)
  804             zone->fresh_xfr_timeout = XFRD_TRANSFER_TIMEOUT_MAX;
  805     }
  806     /* exponential backoff multiplier, starts at 1, backs off */
  807     mult = zone->fresh_xfr_timeout / XFRD_TRANSFER_TIMEOUT_START;
  808     if(mult == 0) mult = 1;
  809 
  810     /* set timer for next retry or expire timeout if earlier. */
  811     if(zone->soa_disk_acquired == 0) {
  812         /* if no information, use reasonable timeout
  813          * within configured and defined bounds
  814          */
  815         xfrd_set_timer(zone,
  816             within_retry_bounds(zone, zone->fresh_xfr_timeout
  817                 + random_generate(zone->fresh_xfr_timeout)));
  818         return;
  819     }
  820     /* exponential backoff within configured and defined bounds */
  821     set_retry = within_retry_bounds(zone,
  822             ntohl(zone->soa_disk.retry) * mult);
  823     if(zone->state == xfrd_zone_expired) {
  824         xfrd_set_timer(zone, set_retry);
  825         return;
  826     }
  827     /* retry or expire timeout, whichever is earlier */
  828     set_expire = zone->soa_disk_acquired + bound_soa_disk_expire(zone);
  829     if(xfrd_time() + set_retry < set_expire) {
  830         xfrd_set_timer(zone, set_retry);
  831         return;
  832     }
  833     /* Not expired, but next retry will be > than expire timeout.
  834      * Retry when the expire timeout runs out.
  835      * set_expire is below retry upper bounds (if statement above),
  836      * but not necessarily above lower bounds,
  837      * so use within_retry_bounds() again.
  838      */
  839     xfrd_set_timer(zone, within_retry_bounds(zone,
  840           set_expire > xfrd_time()
  841         ? set_expire - xfrd_time() : XFRD_LOWERBOUND_RETRY));
  842 }
  843 
  844 void
  845 xfrd_handle_zone(int ATTR_UNUSED(fd), short event, void* arg)
  846 {
  847     xfrd_zone_type* zone = (xfrd_zone_type*)arg;
  848 
  849     if(zone->tcp_conn != -1) {
  850         if(event == 0) /* activated, but already in TCP, nothing to do*/
  851             return;
  852         /* busy in tcp transaction: an internal error */
  853         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s event tcp", zone->apex_str));
  854         xfrd_tcp_release(xfrd->tcp_set, zone);
  855         /* continue to retry; as if a timeout happened */
  856         event = EV_TIMEOUT;
  857     }
  858 
  859     if((event & EV_READ)) {
  860         /* busy in udp transaction */
  861         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s event udp read", zone->apex_str));
  862         xfrd_udp_read(zone);
  863         return;
  864     }
  865 
  866     /* timeout */
  867     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s timeout", zone->apex_str));
  868     if(zone->zone_handler.ev_fd != -1 && zone->event_added &&
  869         (event & EV_TIMEOUT)) {
  870         assert(zone->tcp_conn == -1);
  871         xfrd_udp_release(zone);
  872     }
  873 
  874     if(zone->tcp_waiting) {
  875         DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s skips retry, TCP connections full",
  876             zone->apex_str));
  877         xfrd_unset_timer(zone);
  878         return;
  879     }
  880     if(zone->udp_waiting) {
  881         DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s skips retry, UDP connections full",
  882             zone->apex_str));
  883         xfrd_unset_timer(zone);
  884         return;
  885     }
  886 
  887     if(zone->soa_disk_acquired)
  888     {
  889         if (zone->state != xfrd_zone_expired &&
  890             xfrd_time() >= zone->soa_disk_acquired
  891                     + bound_soa_disk_expire(zone)) {
  892             /* zone expired */
  893             log_msg(LOG_ERR, "xfrd: zone %s has expired", zone->apex_str);
  894             xfrd_set_zone_state(zone, xfrd_zone_expired);
  895         }
  896         else if(zone->state == xfrd_zone_ok &&
  897             xfrd_time() >= zone->soa_disk_acquired
  898                            + bound_soa_disk_refresh(zone)) {
  899             /* zone goes to refreshing state. */
  900             DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s is refreshing", zone->apex_str));
  901             xfrd_set_zone_state(zone, xfrd_zone_refreshing);
  902         }
  903     }
  904 
  905     /* only make a new request if no request is running (UDPorTCP) */
  906     if(zone->zone_handler.ev_fd == -1 && zone->tcp_conn == -1) {
  907         /* make a new request */
  908         xfrd_make_request(zone);
  909     }
  910 }
  911 
  912 void
  913 xfrd_make_request(xfrd_zone_type* zone)
  914 {
  915     if(zone->next_master != -1) {
  916         /* we are told to use this next master */
  917         DEBUG(DEBUG_XFRD,1, (LOG_INFO,
  918             "xfrd zone %s use master %i",
  919             zone->apex_str, zone->next_master));
  920         zone->master_num = zone->next_master;
  921         zone->master = acl_find_num(zone->zone_options->pattern->
  922             request_xfr, zone->master_num);
  923         /* if there is no next master, fallback to use the first one */
  924         if(!zone->master) {
  925             zone->master = zone->zone_options->pattern->request_xfr;
  926             zone->master_num = 0;
  927         }
  928         /* fallback to cycle master */
  929         zone->next_master = -1;
  930         zone->round_num = 0; /* fresh set of retries after notify */
  931     } else {
  932         /* cycle master */
  933 
  934         if(zone->round_num != -1 && zone->master && zone->master->next)
  935         {
  936             /* try the next master */
  937             zone->master = zone->master->next;
  938             zone->master_num++;
  939         } else {
  940             /* start a new round */
  941             zone->master = zone->zone_options->pattern->request_xfr;
  942             zone->master_num = 0;
  943             zone->round_num++;
  944         }
  945         if(zone->round_num >= XFRD_MAX_ROUNDS) {
  946             /* tried all servers that many times, wait */
  947             zone->round_num = -1;
  948             xfrd_set_timer_retry(zone);
  949             DEBUG(DEBUG_XFRD,1, (LOG_INFO,
  950                 "xfrd zone %s makereq wait_retry, rd %d mr %d nx %d",
  951                 zone->apex_str, zone->round_num, zone->master_num, zone->next_master));
  952                        zone->multi_master_first_master = -1;
  953                        return;
  954                }
  955     }
  956 
  957     /* multi-master-check */
  958     if(zone->zone_options->pattern->multi_master_check) {
  959         if(zone->multi_master_first_master == zone->master_num &&
  960             zone->round_num > 0 &&
  961             zone->state != xfrd_zone_expired) {
  962             /* tried all servers and update zone */
  963             if(zone->multi_master_update_check >= 0) {
  964                 VERBOSITY(2, (LOG_INFO, "xfrd: multi master "
  965                     "check: zone %s completed transfers",
  966                     zone->apex_str));
  967             }
  968             zone->round_num = -1; /* next try start anew */
  969             zone->multi_master_first_master = -1;
  970             xfrd_set_timer_refresh(zone);
  971             return;
  972         }
  973         if(zone->multi_master_first_master < 0) {
  974             zone->multi_master_first_master = zone->master_num;
  975             zone->multi_master_update_check = -1;
  976         }
  977     }
  978 
  979     /* cache ixfr_disabled only for XFRD_NO_IXFR_CACHE time */
  980     if (zone->master->ixfr_disabled &&
  981        (zone->master->ixfr_disabled + XFRD_NO_IXFR_CACHE) <= time(NULL)) {
  982         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "clear negative caching ixfr "
  983                         "disabled for master %s num "
  984                         "%d ",
  985             zone->master->ip_address_spec, zone->master_num));
  986         zone->master->ixfr_disabled = 0;
  987     }
  988 
  989     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd zone %s make request round %d mr %d nx %d",
  990         zone->apex_str, zone->round_num, zone->master_num, zone->next_master));
  991     /* perform xfr request */
  992     if (!zone->master->use_axfr_only && zone->soa_disk_acquired > 0 &&
  993         !zone->master->ixfr_disabled) {
  994 
  995         if (zone->master->allow_udp) {
  996             xfrd_set_timer(zone, XFRD_UDP_TIMEOUT);
  997             xfrd_udp_obtain(zone);
  998         }
  999         else { /* doing 3 rounds of IXFR/TCP might not be useful */
 1000             xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
 1001             xfrd_tcp_obtain(xfrd->tcp_set, zone);
 1002         }
 1003     }
 1004     else if (zone->master->use_axfr_only || zone->soa_disk_acquired <= 0) {
 1005         xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
 1006         xfrd_tcp_obtain(xfrd->tcp_set, zone);
 1007     }
 1008     else if (zone->master->ixfr_disabled) {
 1009         if (zone->zone_options->pattern->allow_axfr_fallback) {
 1010             xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
 1011             xfrd_tcp_obtain(xfrd->tcp_set, zone);
 1012         } else {
 1013             DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd zone %s axfr "
 1014                 "fallback not allowed, skipping master %s.",
 1015                 zone->apex_str, zone->master->ip_address_spec));
 1016         }
 1017     }
 1018 }
 1019 
 1020 static void
 1021 xfrd_udp_obtain(xfrd_zone_type* zone)
 1022 {
 1023     assert(zone->udp_waiting == 0);
 1024     if(zone->tcp_conn != -1) {
 1025         /* no tcp and udp at the same time */
 1026         xfrd_tcp_release(xfrd->tcp_set, zone);
 1027     }
 1028     if(xfrd->udp_use_num < XFRD_MAX_UDP) {
 1029         int fd;
 1030         xfrd->udp_use_num++;
 1031         fd = xfrd_send_ixfr_request_udp(zone);
 1032         if(fd == -1)
 1033             xfrd->udp_use_num--;
 1034         else {
 1035             if(zone->event_added)
 1036                 event_del(&zone->zone_handler);
 1037             memset(&zone->zone_handler, 0,
 1038                 sizeof(zone->zone_handler));
 1039             event_set(&zone->zone_handler, fd,
 1040                 EV_PERSIST|EV_READ|EV_TIMEOUT,
 1041                 xfrd_handle_zone, zone);
 1042             if(event_base_set(xfrd->event_base, &zone->zone_handler) != 0)
 1043                 log_msg(LOG_ERR, "xfrd udp: event_base_set failed");
 1044             if(event_add(&zone->zone_handler, &zone->timeout) != 0)
 1045                 log_msg(LOG_ERR, "xfrd udp: event_add failed");
 1046             zone->zone_handler_flags=EV_PERSIST|EV_READ|EV_TIMEOUT;
 1047             zone->event_added = 1;
 1048         }
 1049         return;
 1050     }
 1051     /* queue the zone as last */
 1052     zone->udp_waiting = 1;
 1053     zone->udp_waiting_next = NULL;
 1054     zone->udp_waiting_prev = xfrd->udp_waiting_last;
 1055     if(!xfrd->udp_waiting_first)
 1056         xfrd->udp_waiting_first = zone;
 1057     if(xfrd->udp_waiting_last)
 1058         xfrd->udp_waiting_last->udp_waiting_next = zone;
 1059     xfrd->udp_waiting_last = zone;
 1060     xfrd_unset_timer(zone);
 1061 }
 1062 
 1063 time_t
 1064 xfrd_time()
 1065 {
 1066     if(!xfrd->got_time) {
 1067         xfrd->current_time = time(0);
 1068         xfrd->got_time = 1;
 1069     }
 1070     return xfrd->current_time;
 1071 }
 1072 
 1073 void
 1074 xfrd_copy_soa(xfrd_soa_type* soa, rr_type* rr)
 1075 {
 1076     const uint8_t* rr_ns_wire = dname_name(domain_dname(rdata_atom_domain(rr->rdatas[0])));
 1077     uint8_t rr_ns_len = domain_dname(rdata_atom_domain(rr->rdatas[0]))->name_size;
 1078     const uint8_t* rr_em_wire = dname_name(domain_dname(rdata_atom_domain(rr->rdatas[1])));
 1079     uint8_t rr_em_len = domain_dname(rdata_atom_domain(rr->rdatas[1]))->name_size;
 1080 
 1081     if(rr->type != TYPE_SOA || rr->rdata_count != 7) {
 1082         log_msg(LOG_ERR, "xfrd: copy_soa called with bad rr, type %d rrs %u.",
 1083             rr->type, rr->rdata_count);
 1084         return;
 1085     }
 1086     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: copy_soa rr, type %d rrs %u, ttl %u.",
 1087             (int)rr->type, (unsigned)rr->rdata_count, (unsigned)rr->ttl));
 1088     soa->type = htons(rr->type);
 1089     soa->klass = htons(rr->klass);
 1090     soa->ttl = htonl(rr->ttl);
 1091     soa->rdata_count = htons(rr->rdata_count);
 1092 
 1093     /* copy dnames */
 1094     soa->prim_ns[0] = rr_ns_len;
 1095     memcpy(soa->prim_ns+1, rr_ns_wire, rr_ns_len);
 1096     soa->email[0] = rr_em_len;
 1097     memcpy(soa->email+1, rr_em_wire, rr_em_len);
 1098 
 1099     /* already in network format */
 1100     memcpy(&soa->serial, rdata_atom_data(rr->rdatas[2]), sizeof(uint32_t));
 1101     memcpy(&soa->refresh, rdata_atom_data(rr->rdatas[3]), sizeof(uint32_t));
 1102     memcpy(&soa->retry, rdata_atom_data(rr->rdatas[4]), sizeof(uint32_t));
 1103     memcpy(&soa->expire, rdata_atom_data(rr->rdatas[5]), sizeof(uint32_t));
 1104     memcpy(&soa->minimum, rdata_atom_data(rr->rdatas[6]), sizeof(uint32_t));
 1105     DEBUG(DEBUG_XFRD,1, (LOG_INFO,
 1106         "xfrd: copy_soa rr, serial %u refresh %u retry %u expire %u",
 1107         (unsigned)ntohl(soa->serial), (unsigned)ntohl(soa->refresh),
 1108         (unsigned)ntohl(soa->retry), (unsigned)ntohl(soa->expire)));
 1109 }
 1110 
 1111 static void
 1112 xfrd_set_zone_state(xfrd_zone_type* zone, enum xfrd_zone_state s)
 1113 {
 1114     if(s != zone->state) {
 1115         enum xfrd_zone_state old = zone->state;
 1116         zone->state = s;
 1117         if((s == xfrd_zone_expired || old == xfrd_zone_expired)
 1118             && s!=old) {
 1119             xfrd_send_expire_notification(zone);
 1120         }
 1121     }
 1122 }
 1123 
 1124 void
 1125 xfrd_set_refresh_now(xfrd_zone_type* zone)
 1126 {
 1127     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd zone %s is activated, state %d",
 1128         zone->apex_str, zone->state));
 1129     if(!zone->is_activated) {
 1130         /* push onto list */
 1131         zone->activated_prev = 0;
 1132         zone->activated_next = xfrd->activated_first;
 1133         if(xfrd->activated_first)
 1134             xfrd->activated_first->activated_prev = zone;
 1135         xfrd->activated_first = zone;
 1136         zone->is_activated = 1;
 1137     }
 1138 }
 1139 
 1140 void
 1141 xfrd_unset_timer(xfrd_zone_type* zone)
 1142 {
 1143     assert(zone->zone_handler.ev_fd == -1);
 1144     if(zone->event_added)
 1145         event_del(&zone->zone_handler);
 1146     zone->zone_handler_flags = 0;
 1147     zone->event_added = 0;
 1148 }
 1149 
 1150 void
 1151 xfrd_set_timer(xfrd_zone_type* zone, time_t t)
 1152 {
 1153     int fd = zone->zone_handler.ev_fd;
 1154     int fl = ((fd == -1)?EV_TIMEOUT:zone->zone_handler_flags);
 1155     if(t > XFRD_TRANSFER_TIMEOUT_MAX)
 1156         t = XFRD_TRANSFER_TIMEOUT_MAX;
 1157     /* randomize the time, within 90%-100% of original */
 1158     /* not later so zones cannot expire too late */
 1159     /* only for times far in the future */
 1160     if(t > 10) {
 1161         time_t base = t*9/10;
 1162         t = base + random_generate(t-base);
 1163     }
 1164 
 1165     /* keep existing flags and fd, but re-add with timeout */
 1166     if(zone->event_added)
 1167         event_del(&zone->zone_handler);
 1168     else    fd = -1;
 1169     zone->timeout.tv_sec = t;
 1170     zone->timeout.tv_usec = 0;
 1171     memset(&zone->zone_handler, 0, sizeof(zone->zone_handler));
 1172     event_set(&zone->zone_handler, fd, fl, xfrd_handle_zone, zone);
 1173     if(event_base_set(xfrd->event_base, &zone->zone_handler) != 0)
 1174         log_msg(LOG_ERR, "xfrd timer: event_base_set failed");
 1175     if(event_add(&zone->zone_handler, &zone->timeout) != 0)
 1176         log_msg(LOG_ERR, "xfrd timer: event_add failed");
 1177     zone->zone_handler_flags = fl;
 1178     zone->event_added = 1;
 1179 }
 1180 
 1181 void
 1182 xfrd_handle_incoming_soa(xfrd_zone_type* zone,
 1183     xfrd_soa_type* soa, time_t acquired)
 1184 {
 1185     time_t seconds_since_acquired;
 1186     if(soa == NULL) {
 1187         /* nsd no longer has a zone in memory */
 1188         zone->soa_nsd_acquired = 0;
 1189         xfrd_set_zone_state(zone, xfrd_zone_refreshing);
 1190         xfrd_set_refresh_now(zone);
 1191         return;
 1192     }
 1193     if(zone->soa_nsd_acquired && soa->serial == zone->soa_nsd.serial)
 1194         return;
 1195 
 1196     if(zone->soa_disk_acquired && soa->serial == zone->soa_disk.serial)
 1197     {
 1198         /* soa in disk has been loaded in memory */
 1199         log_msg(LOG_INFO, "zone %s serial %u is updated to %u",
 1200             zone->apex_str, (unsigned)ntohl(zone->soa_nsd.serial),
 1201             (unsigned)ntohl(soa->serial));
 1202         zone->soa_nsd = zone->soa_disk;
 1203         zone->soa_nsd_acquired = zone->soa_disk_acquired;
 1204         xfrd->write_zonefile_needed = 1;
 1205         /* reset exponential backoff, we got a normal timer now */
 1206         zone->fresh_xfr_timeout = 0;
 1207         seconds_since_acquired =
 1208               xfrd_time() > zone->soa_disk_acquired
 1209             ? xfrd_time() - zone->soa_disk_acquired : 0;
 1210         if(seconds_since_acquired < bound_soa_disk_refresh(zone))
 1211         {
 1212             /* zone ok, wait for refresh time */
 1213             xfrd_set_zone_state(zone, xfrd_zone_ok);
 1214             zone->round_num = -1;
 1215             xfrd_set_timer_refresh(zone);
 1216         } else if(seconds_since_acquired < bound_soa_disk_expire(zone))
 1217         {
 1218             /* zone refreshing */
 1219             xfrd_set_zone_state(zone, xfrd_zone_refreshing);
 1220             xfrd_set_refresh_now(zone);
 1221         }
 1222         if(seconds_since_acquired >= bound_soa_disk_expire(zone)) {
 1223             /* zone expired */
 1224             xfrd_set_zone_state(zone, xfrd_zone_expired);
 1225             xfrd_set_refresh_now(zone);
 1226         }
 1227 
 1228         if(zone->soa_notified_acquired != 0 &&
 1229             (zone->soa_notified.serial == 0 ||
 1230             compare_serial(ntohl(zone->soa_disk.serial),
 1231                 ntohl(zone->soa_notified.serial)) >= 0))
 1232         {   /* read was in response to this notification */
 1233             zone->soa_notified_acquired = 0;
 1234         }
 1235         if(zone->soa_notified_acquired && zone->state == xfrd_zone_ok)
 1236         {
 1237             /* refresh because of notification */
 1238             xfrd_set_zone_state(zone, xfrd_zone_refreshing);
 1239             xfrd_set_refresh_now(zone);
 1240         }
 1241         xfrd_send_notify(xfrd->notify_zones, zone->apex, &zone->soa_nsd);
 1242         return;
 1243     }
 1244 
 1245     /* user must have manually provided zone data */
 1246     DEBUG(DEBUG_XFRD,1, (LOG_INFO,
 1247         "xfrd: zone %s serial %u from zonefile. refreshing",
 1248         zone->apex_str, (unsigned)ntohl(soa->serial)));
 1249     zone->soa_nsd = *soa;
 1250     zone->soa_disk = *soa;
 1251     zone->soa_nsd_acquired = acquired;
 1252     zone->soa_disk_acquired = acquired;
 1253     if(zone->soa_notified_acquired != 0 &&
 1254         (zone->soa_notified.serial == 0 ||
 1255         compare_serial(ntohl(zone->soa_disk.serial),
 1256             ntohl(zone->soa_notified.serial)) >= 0))
 1257     {   /* user provided in response to this notification */
 1258         zone->soa_notified_acquired = 0;
 1259     }
 1260     xfrd_set_zone_state(zone, xfrd_zone_refreshing);
 1261     xfrd_set_refresh_now(zone);
 1262     xfrd_send_notify(xfrd->notify_zones, zone->apex, &zone->soa_nsd);
 1263 }
 1264 
 1265 void
 1266 xfrd_send_expire_notification(xfrd_zone_type* zone)
 1267 {
 1268     task_new_expire(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
 1269         zone->apex, zone->state == xfrd_zone_expired);
 1270     xfrd_set_reload_timeout();
 1271 }
 1272 
 1273 int
 1274 xfrd_udp_read_packet(buffer_type* packet, int fd, struct sockaddr* src,
 1275     socklen_t* srclen)
 1276 {
 1277     ssize_t received;
 1278 
 1279     /* read the data */
 1280     buffer_clear(packet);
 1281     received = recvfrom(fd, buffer_begin(packet), buffer_remaining(packet),
 1282         0, src, srclen);
 1283     if(received == -1) {
 1284         log_msg(LOG_ERR, "xfrd: recvfrom failed: %s",
 1285             strerror(errno));
 1286         return 0;
 1287     }
 1288     buffer_set_limit(packet, received);
 1289     return 1;
 1290 }
 1291 
 1292 void
 1293 xfrd_udp_release(xfrd_zone_type* zone)
 1294 {
 1295     assert(zone->udp_waiting == 0);
 1296     if(zone->event_added)
 1297         event_del(&zone->zone_handler);
 1298     if(zone->zone_handler.ev_fd != -1) {
 1299         close(zone->zone_handler.ev_fd);
 1300     }
 1301     zone->zone_handler.ev_fd = -1;
 1302     zone->zone_handler_flags = 0;
 1303     zone->event_added = 0;
 1304     /* see if there are waiting zones */
 1305     if(xfrd->udp_use_num == XFRD_MAX_UDP)
 1306     {
 1307         while(xfrd->udp_waiting_first) {
 1308             /* snip off waiting list */
 1309             xfrd_zone_type* wz = xfrd->udp_waiting_first;
 1310             assert(wz->udp_waiting);
 1311             wz->udp_waiting = 0;
 1312             xfrd->udp_waiting_first = wz->udp_waiting_next;
 1313             if(wz->udp_waiting_next)
 1314                 wz->udp_waiting_next->udp_waiting_prev = NULL;
 1315             if(xfrd->udp_waiting_last == wz)
 1316                 xfrd->udp_waiting_last = NULL;
 1317             /* see if this zone needs udp connection */
 1318             if(wz->tcp_conn == -1) {
 1319                 int fd = xfrd_send_ixfr_request_udp(wz);
 1320                 if(fd != -1) {
 1321                     if(wz->event_added)
 1322                         event_del(&wz->zone_handler);
 1323                     memset(&wz->zone_handler, 0,
 1324                         sizeof(wz->zone_handler));
 1325                     event_set(&wz->zone_handler, fd,
 1326                         EV_READ|EV_TIMEOUT|EV_PERSIST,
 1327                         xfrd_handle_zone, wz);
 1328                     if(event_base_set(xfrd->event_base,
 1329                         &wz->zone_handler) != 0)
 1330                         log_msg(LOG_ERR, "cannot set event_base for ixfr");
 1331                     if(event_add(&wz->zone_handler, &wz->timeout) != 0)
 1332                         log_msg(LOG_ERR, "cannot add event for ixfr");
 1333                     wz->zone_handler_flags = EV_READ|EV_TIMEOUT|EV_PERSIST;
 1334                     wz->event_added = 1;
 1335                     return;
 1336                 } else {
 1337                     /* make this zone do something with
 1338                      * this failure to act */
 1339                     xfrd_set_refresh_now(wz);
 1340                 }
 1341             }
 1342         }
 1343     }
 1344     /* no waiting zones */
 1345     if(xfrd->udp_use_num > 0)
 1346         xfrd->udp_use_num--;
 1347 }
 1348 
 1349 /** disable ixfr for master */
 1350 void
 1351 xfrd_disable_ixfr(xfrd_zone_type* zone)
 1352 {
 1353     if(!(zone->master->ixfr_disabled &&
 1354         (zone->master->ixfr_disabled + XFRD_NO_IXFR_CACHE) <= time(NULL))) {
 1355         /* start new round, with IXFR disabled */
 1356         zone->round_num = 0;
 1357         zone->next_master = zone->master_num;
 1358     }
 1359     zone->master->ixfr_disabled = time(NULL);
 1360 }
 1361 
 1362 static void
 1363 xfrd_udp_read(xfrd_zone_type* zone)
 1364 {
 1365     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s read udp data", zone->apex_str));
 1366     if(!xfrd_udp_read_packet(xfrd->packet, zone->zone_handler.ev_fd,
 1367         NULL, NULL)) {
 1368         zone->master->bad_xfr_count++;
 1369         if (zone->master->bad_xfr_count > 2) {
 1370             xfrd_disable_ixfr(zone);
 1371             zone->master->bad_xfr_count = 0;
 1372         }
 1373         /* drop packet */
 1374         xfrd_udp_release(zone);
 1375         /* query next server */
 1376         xfrd_make_request(zone);
 1377         return;
 1378     }
 1379     switch(xfrd_handle_received_xfr_packet(zone, xfrd->packet)) {
 1380         case xfrd_packet_tcp:
 1381             xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
 1382             xfrd_udp_release(zone);
 1383             xfrd_tcp_obtain(xfrd->tcp_set, zone);
 1384             break;
 1385         case xfrd_packet_transfer:
 1386             if(zone->zone_options->pattern->multi_master_check) {
 1387                 xfrd_udp_release(zone);
 1388                 xfrd_make_request(zone);
 1389                 break;
 1390             }
 1391             /* fallthrough */
 1392         case xfrd_packet_newlease:
 1393             /* nothing more to do */
 1394             assert(zone->round_num == -1);
 1395             xfrd_udp_release(zone);
 1396             break;
 1397         case xfrd_packet_notimpl:
 1398             xfrd_disable_ixfr(zone);
 1399             /* drop packet */
 1400             xfrd_udp_release(zone);
 1401             /* query next server */
 1402             xfrd_make_request(zone);
 1403             break;
 1404         case xfrd_packet_more:
 1405         case xfrd_packet_drop:
 1406             /* drop packet */
 1407             xfrd_udp_release(zone);
 1408             /* query next server */
 1409             xfrd_make_request(zone);
 1410             break;
 1411         case xfrd_packet_bad:
 1412         default:
 1413             zone->master->bad_xfr_count++;
 1414             if (zone->master->bad_xfr_count > 2) {
 1415                 xfrd_disable_ixfr(zone);
 1416                 zone->master->bad_xfr_count = 0;
 1417             }
 1418             /* drop packet */
 1419             xfrd_udp_release(zone);
 1420             /* query next server */
 1421             xfrd_make_request(zone);
 1422             break;
 1423     }
 1424 }
 1425 
 1426 int
 1427 xfrd_send_udp(struct acl_options* acl, buffer_type* packet,
 1428     struct acl_options* ifc)
 1429 {
 1430 #ifdef INET6
 1431     struct sockaddr_storage to;
 1432 #else
 1433     struct sockaddr_in to;
 1434 #endif /* INET6 */
 1435     int fd, family;
 1436 
 1437     /* this will set the remote port to acl->port or TCP_PORT */
 1438     socklen_t to_len = xfrd_acl_sockaddr_to(acl, &to);
 1439 
 1440     /* get the address family of the remote host */
 1441     if(acl->is_ipv6) {
 1442 #ifdef INET6
 1443         family = PF_INET6;
 1444 #else
 1445         return -1;
 1446 #endif /* INET6 */
 1447     } else {
 1448         family = PF_INET;
 1449     }
 1450 
 1451     fd = socket(family, SOCK_DGRAM, IPPROTO_UDP);
 1452     if(fd == -1) {
 1453         log_msg(LOG_ERR, "xfrd: cannot create udp socket to %s: %s",
 1454             acl->ip_address_spec, strerror(errno));
 1455         return -1;
 1456     }
 1457 
 1458     /* bind it */
 1459     if (!xfrd_bind_local_interface(fd, ifc, acl, 0)) {
 1460         log_msg(LOG_ERR, "xfrd: cannot bind outgoing interface '%s' to "
 1461                  "udp socket: No matching ip addresses found",
 1462             ifc->ip_address_spec);
 1463         close(fd);
 1464         return -1;
 1465     }
 1466 
 1467     /* send it (udp) */
 1468     if(sendto(fd,
 1469         buffer_current(packet),
 1470         buffer_remaining(packet), 0,
 1471         (struct sockaddr*)&to, to_len) == -1)
 1472     {
 1473         log_msg(LOG_ERR, "xfrd: sendto %s failed %s",
 1474             acl->ip_address_spec, strerror(errno));
 1475         close(fd);
 1476         return -1;
 1477     }
 1478     return fd;
 1479 }
 1480 
 1481 int
 1482 xfrd_bind_local_interface(int sockd, struct acl_options* ifc,
 1483     struct acl_options* acl, int tcp)
 1484 {
 1485 #ifdef SO_LINGER
 1486     struct linger linger = {1, 0};
 1487 #endif
 1488     socklen_t frm_len;
 1489 #ifdef INET6
 1490     struct sockaddr_storage frm;
 1491 #else
 1492     struct sockaddr_in frm;
 1493 #endif /* INET6 */
 1494     int ret = 1;
 1495 
 1496     if (!ifc) /* no outgoing interface set */
 1497         return 1;
 1498 
 1499     while (ifc) {
 1500         if (ifc->is_ipv6 != acl->is_ipv6) {
 1501             /* check if we have a matching address family */
 1502             ifc = ifc->next;
 1503             continue;
 1504         }
 1505 
 1506         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: bind() %s to %s socket",
 1507             ifc->ip_address_spec, tcp? "tcp":"udp"));
 1508         ret = 0;
 1509         frm_len = xfrd_acl_sockaddr_frm(ifc, &frm);
 1510 
 1511         if (tcp) {
 1512 #ifdef SO_REUSEADDR
 1513             if (setsockopt(sockd, SOL_SOCKET, SO_REUSEADDR, &frm,
 1514                 frm_len) < 0) {
 1515                 VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt "
 1516                  "SO_REUSEADDR failed: %s", strerror(errno)));
 1517             }
 1518 #else
 1519             VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt SO_REUSEADDR "
 1520                  "failed: SO_REUSEADDR not defined"));
 1521 #endif /* SO_REUSEADDR */
 1522 
 1523             if (ifc->port != 0) {
 1524 #ifdef SO_LINGER
 1525                 if (setsockopt(sockd, SOL_SOCKET, SO_LINGER,
 1526                     &linger, sizeof(linger)) < 0) {
 1527                     VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt "
 1528                      "SO_LINGER failed: %s", strerror(errno)));
 1529                 }
 1530 #else
 1531                 VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt SO_LINGER "
 1532                     "failed: SO_LINGER not defined"));
 1533 #endif /* SO_LINGER */
 1534             }
 1535         }
 1536 
 1537         /* found one */
 1538         if(bind(sockd, (struct sockaddr*)&frm, frm_len) >= 0) {
 1539             DEBUG(DEBUG_XFRD,2, (LOG_INFO, "xfrd: bind() %s to %s "
 1540                                "socket was successful",
 1541             ifc->ip_address_spec, tcp? "tcp":"udp"));
 1542             return 1;
 1543         }
 1544 
 1545         DEBUG(DEBUG_XFRD,2, (LOG_INFO, "xfrd: bind() %s to %s socket"
 1546                            "failed: %s",
 1547             ifc->ip_address_spec, tcp? "tcp":"udp",
 1548             strerror(errno)));
 1549 
 1550         log_msg(LOG_WARNING, "xfrd: could not bind source address:port to "
 1551              "socket: %s", strerror(errno));
 1552         /* try another */
 1553         ifc = ifc->next;
 1554     }
 1555     return ret;
 1556 }
 1557 
 1558 void
 1559 xfrd_tsig_sign_request(buffer_type* packet, tsig_record_type* tsig,
 1560     struct acl_options* acl)
 1561 {
 1562     tsig_algorithm_type* algo;
 1563     assert(acl->key_options && acl->key_options->tsig_key);
 1564     algo = tsig_get_algorithm_by_name(acl->key_options->algorithm);
 1565     if(!algo) {
 1566         log_msg(LOG_ERR, "tsig unknown algorithm %s",
 1567             acl->key_options->algorithm);
 1568         return;
 1569     }
 1570     assert(algo);
 1571     tsig_init_record(tsig, algo, acl->key_options->tsig_key);
 1572     tsig_init_query(tsig, ID(packet));
 1573     tsig_prepare(tsig);
 1574     tsig_update(tsig, packet, buffer_position(packet));
 1575     tsig_sign(tsig);
 1576     tsig_append_rr(tsig, packet);
 1577     ARCOUNT_SET(packet, ARCOUNT(packet) + 1);
 1578     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "appending tsig to packet"));
 1579     /* prepare for validating tsigs */
 1580     tsig_prepare(tsig);
 1581 }
 1582 
 1583 static int
 1584 xfrd_send_ixfr_request_udp(xfrd_zone_type* zone)
 1585 {
 1586     int fd;
 1587 
 1588     /* make sure we have a master to query the ixfr request to */
 1589     assert(zone->master);
 1590 
 1591     if(zone->tcp_conn != -1) {
 1592         /* tcp is using the zone_handler.fd */
 1593         log_msg(LOG_ERR, "xfrd: %s tried to send udp whilst tcp engaged",
 1594             zone->apex_str);
 1595         return -1;
 1596     }
 1597     xfrd_setup_packet(xfrd->packet, TYPE_IXFR, CLASS_IN, zone->apex,
 1598         qid_generate());
 1599     zone->query_id = ID(xfrd->packet);
 1600     zone->query_type = TYPE_IXFR;
 1601     /* delete old xfr file? */
 1602     if(zone->msg_seq_nr)
 1603         xfrd_unlink_xfrfile(xfrd->nsd, zone->xfrfilenumber);
 1604     zone->msg_seq_nr = 0;
 1605     zone->msg_rr_count = 0;
 1606     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "sent query with ID %d", zone->query_id));
 1607         NSCOUNT_SET(xfrd->packet, 1);
 1608     xfrd_write_soa_buffer(xfrd->packet, zone->apex, &zone->soa_disk);
 1609     /* if we have tsig keys, sign the ixfr query */
 1610     if(zone->master->key_options && zone->master->key_options->tsig_key) {
 1611         xfrd_tsig_sign_request(xfrd->packet, &zone->tsig, zone->master);
 1612     }
 1613     buffer_flip(xfrd->packet);
 1614     xfrd_set_timer(zone, XFRD_UDP_TIMEOUT);
 1615 
 1616     if((fd = xfrd_send_udp(zone->master, xfrd->packet,
 1617         zone->zone_options->pattern->outgoing_interface)) == -1)
 1618         return -1;
 1619 
 1620     DEBUG(DEBUG_XFRD,1, (LOG_INFO,
 1621         "xfrd sent udp request for ixfr=%u for zone %s to %s",
 1622         (unsigned)ntohl(zone->soa_disk.serial),
 1623         zone->apex_str, zone->master->ip_address_spec));
 1624     return fd;
 1625 }
 1626 
 1627 static int xfrd_parse_soa_info(buffer_type* packet, xfrd_soa_type* soa)
 1628 {
 1629     if(!buffer_available(packet, 10))
 1630         return 0;
 1631     soa->type = htons(buffer_read_u16(packet));
 1632     soa->klass = htons(buffer_read_u16(packet));
 1633     soa->ttl = htonl(buffer_read_u32(packet));
 1634     if(ntohs(soa->type) != TYPE_SOA || ntohs(soa->klass) != CLASS_IN)
 1635     {
 1636         return 0;
 1637     }
 1638 
 1639     if(!buffer_available(packet, buffer_read_u16(packet)) /* rdata length */ ||
 1640         !(soa->prim_ns[0] = dname_make_wire_from_packet(soa->prim_ns+1, packet, 1)) ||
 1641         !(soa->email[0] = dname_make_wire_from_packet(soa->email+1, packet, 1)))
 1642     {
 1643         return 0;
 1644     }
 1645     soa->rdata_count = 7; /* rdata in SOA */
 1646     soa->serial = htonl(buffer_read_u32(packet));
 1647     soa->refresh = htonl(buffer_read_u32(packet));
 1648     soa->retry = htonl(buffer_read_u32(packet));
 1649     soa->expire = htonl(buffer_read_u32(packet));
 1650     soa->minimum = htonl(buffer_read_u32(packet));
 1651 
 1652     return 1;
 1653 }
 1654 
 1655 
 1656 /*
 1657  * Check the RRs in an IXFR/AXFR reply.
 1658  * returns 0 on error, 1 on correct parseable packet.
 1659  * done = 1 if the last SOA in an IXFR/AXFR has been seen.
 1660  * soa then contains that soa info.
 1661  * (soa contents is modified by the routine)
 1662  */
 1663 static int
 1664 xfrd_xfr_check_rrs(xfrd_zone_type* zone, buffer_type* packet, size_t count,
 1665     int *done, xfrd_soa_type* soa, region_type* temp)
 1666 {
 1667     /* first RR has already been checked */
 1668     uint32_t tmp_serial = 0;
 1669     uint16_t type, rrlen;
 1670     size_t i, soapos, mempos;
 1671     const dname_type* dname;
 1672     domain_table_type* owners;
 1673     rdata_atom_type* rdatas;
 1674 
 1675     for(i=0; i<count; ++i,++zone->msg_rr_count)
 1676     {
 1677         if (*done) {
 1678             DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr has "
 1679                 "trailing garbage", zone->apex_str));
 1680             return 0;
 1681         }
 1682         region_free_all(temp);
 1683         owners = domain_table_create(temp);
 1684         /* check the dname for errors */
 1685         dname = dname_make_from_packet(temp, packet, 1, 1);
 1686         if(!dname) {
 1687             DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr unable "
 1688                 "to parse owner name", zone->apex_str));
 1689             return 0;
 1690         }
 1691         if(!buffer_available(packet, 10)) {
 1692             DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr hdr "
 1693                 "too small", zone->apex_str));
 1694             return 0;
 1695         }
 1696         soapos = buffer_position(packet);
 1697         type = buffer_read_u16(packet);
 1698         (void)buffer_read_u16(packet); /* class */
 1699         (void)buffer_read_u32(packet); /* ttl */
 1700         rrlen = buffer_read_u16(packet);
 1701         if(!buffer_available(packet, rrlen)) {
 1702             DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr pkt "
 1703                 "too small", zone->apex_str));
 1704             return 0;
 1705         }
 1706         mempos = buffer_position(packet);
 1707         if(rdata_wireformat_to_rdata_atoms(temp, owners, type, rrlen,
 1708             packet, &rdatas) == -1) {
 1709             DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr unable "
 1710                 "to parse rdata", zone->apex_str));
 1711             return 0;
 1712         }
 1713         if(type == TYPE_SOA) {
 1714             /* check the SOAs */
 1715             buffer_set_position(packet, soapos);
 1716             if(!xfrd_parse_soa_info(packet, soa)) {
 1717                 DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
 1718                     "unable to parse soainfo", zone->apex_str));
 1719                 return 0;
 1720             }
 1721             if(zone->msg_rr_count == 1 &&
 1722                 ntohl(soa->serial) != zone->msg_new_serial) {
 1723                 /* 2nd RR is SOA with lower serial, this is an IXFR */
 1724                 zone->msg_is_ixfr = 1;
 1725                 if(!zone->soa_disk_acquired) {
 1726                     DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
 1727                         "got ixfr but need axfr", zone->apex_str));
 1728                     return 0; /* got IXFR but need AXFR */
 1729                 }
 1730                 if(ntohl(soa->serial) != ntohl(zone->soa_disk.serial)) {
 1731                     DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
 1732                         "bad start serial", zone->apex_str));
 1733                     return 0; /* bad start serial in IXFR */
 1734                 }
 1735                 zone->msg_old_serial = ntohl(soa->serial);
 1736                 tmp_serial = ntohl(soa->serial);
 1737             }
 1738             else if(ntohl(soa->serial) == zone->msg_new_serial) {
 1739                 /* saw another SOA of new serial. */
 1740                 if(zone->msg_is_ixfr == 1) {
 1741                     zone->msg_is_ixfr = 2; /* seen middle SOA in ixfr */
 1742                 } else {
 1743                     /* 2nd SOA for AXFR or 3rd newSOA for IXFR */
 1744                     *done = 1;
 1745                 }
 1746             }
 1747             else if (zone->msg_is_ixfr) {
 1748                 /* some additional checks */
 1749                 if(ntohl(soa->serial) > zone->msg_new_serial) {
 1750                     DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
 1751                         "bad middle serial", zone->apex_str));
 1752                     return 0; /* bad middle serial in IXFR */
 1753                 }
 1754                 if(ntohl(soa->serial) < tmp_serial) {
 1755                     DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
 1756                         "serial decreasing not allowed", zone->apex_str));
 1757                     return 0; /* middle serial decreases in IXFR */
 1758                 }
 1759                 /* serial ok, update tmp serial */
 1760                 tmp_serial = ntohl(soa->serial);
 1761             }
 1762         }
 1763         buffer_set_position(packet, mempos);
 1764         buffer_skip(packet, rrlen);
 1765     }
 1766     /* packet seems to have a valid DNS RR structure */
 1767     return 1;
 1768 }
 1769 
 1770 static int
 1771 xfrd_xfr_process_tsig(xfrd_zone_type* zone, buffer_type* packet)
 1772 {
 1773     int have_tsig = 0;
 1774     assert(zone && zone->master && zone->master->key_options
 1775         && zone->master->key_options->tsig_key && packet);
 1776     if(!tsig_find_rr(&zone->tsig, packet)) {
 1777         log_msg(LOG_ERR, "xfrd: zone %s, from %s: malformed tsig RR",
 1778             zone->apex_str, zone->master->ip_address_spec);
 1779         return 0;
 1780     }
 1781     if(zone->tsig.status == TSIG_OK) {
 1782         have_tsig = 1;
 1783         if (zone->tsig.error_code != TSIG_ERROR_NOERROR) {
 1784             log_msg(LOG_ERR, "xfrd: zone %s, from %s: tsig error "
 1785                 "(%s)", zone->apex_str,
 1786                 zone->master->ip_address_spec,
 1787                 tsig_error(zone->tsig.error_code));
 1788         }
 1789     }
 1790     if(have_tsig) {
 1791         /* strip the TSIG resource record off... */
 1792         buffer_set_limit(packet, zone->tsig.position);
 1793         ARCOUNT_SET(packet, ARCOUNT(packet) - 1);
 1794     }
 1795 
 1796     /* keep running the TSIG hash */
 1797     tsig_update(&zone->tsig, packet, buffer_limit(packet));
 1798     if(have_tsig) {
 1799         if (!tsig_verify(&zone->tsig)) {
 1800             log_msg(LOG_ERR, "xfrd: zone %s, from %s: bad tsig signature",
 1801                 zone->apex_str, zone->master->ip_address_spec);
 1802             return 0;
 1803         }
 1804         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s, from %s: good tsig signature",
 1805             zone->apex_str, zone->master->ip_address_spec));
 1806         /* prepare for next tsigs */
 1807         tsig_prepare(&zone->tsig);
 1808     }
 1809     else if(zone->tsig.updates_since_last_prepare > XFRD_TSIG_MAX_UNSIGNED) {
 1810         /* we allow a number of non-tsig signed packets */
 1811         log_msg(LOG_INFO, "xfrd: zone %s, from %s: too many consecutive "
 1812             "packets without TSIG", zone->apex_str,
 1813             zone->master->ip_address_spec);
 1814         return 0;
 1815     }
 1816 
 1817     if(!have_tsig && zone->msg_seq_nr == 0) {
 1818         log_msg(LOG_ERR, "xfrd: zone %s, from %s: no tsig in first packet of reply",
 1819             zone->apex_str, zone->master->ip_address_spec);
 1820         return 0;
 1821     }
 1822     return 1;
 1823 }
 1824 
 1825 /* parse the received packet. returns xfrd packet result code. */
 1826 static enum xfrd_packet_result
 1827 xfrd_parse_received_xfr_packet(xfrd_zone_type* zone, buffer_type* packet,
 1828     xfrd_soa_type* soa)
 1829 {
 1830     size_t rr_count;
 1831     size_t qdcount = QDCOUNT(packet);
 1832     size_t ancount = ANCOUNT(packet), ancount_todo;
 1833     size_t nscount = NSCOUNT(packet);
 1834     int done = 0;
 1835     region_type* tempregion = NULL;
 1836     assert(zone->master);
 1837 
 1838     /* has to be axfr / ixfr reply */
 1839     if(!buffer_available(packet, QHEADERSZ)) {
 1840         log_msg(LOG_INFO, "packet too small");
 1841         return xfrd_packet_bad;
 1842     }
 1843 
 1844     /* only check ID in first response message. Could also check that
 1845      * AA bit and QR bit are set, but not needed.
 1846      */
 1847     DEBUG(DEBUG_XFRD,2, (LOG_INFO,
 1848         "got query with ID %d and %d needed", ID(packet), zone->query_id));
 1849     if(ID(packet) != zone->query_id) {
 1850         log_msg(LOG_ERR, "xfrd: zone %s received bad query id from %s, "
 1851                  "dropped",
 1852             zone->apex_str, zone->master->ip_address_spec);
 1853         return xfrd_packet_bad;
 1854     }
 1855     /* check RCODE in all response messages */
 1856     if(RCODE(packet) != RCODE_OK) {
 1857         /* for IXFR failures, do not log unless higher verbosity */
 1858         if(!(verbosity < 3 && (RCODE(packet) == RCODE_IMPL ||
 1859             RCODE(packet) == RCODE_FORMAT) &&
 1860             !zone->master->ixfr_disabled &&
 1861             !zone->master->use_axfr_only)) {
 1862             log_msg(LOG_ERR, "xfrd: zone %s received error code %s from "
 1863                     "%s",
 1864                 zone->apex_str, rcode2str(RCODE(packet)),
 1865                 zone->master->ip_address_spec);
 1866         }
 1867         if (RCODE(packet) == RCODE_IMPL ||
 1868             RCODE(packet) == RCODE_FORMAT) {
 1869             return xfrd_packet_notimpl;
 1870         }
 1871         if (RCODE(packet) != RCODE_NOTAUTH) {
 1872             /* RFC 2845: If NOTAUTH, client should do TSIG checking */
 1873             return xfrd_packet_drop;
 1874         }
 1875     }
 1876     /* check TSIG */
 1877     if(zone->master->key_options) {
 1878         if(!xfrd_xfr_process_tsig(zone, packet)) {
 1879             DEBUG(DEBUG_XFRD,1, (LOG_ERR, "dropping xfr reply due "
 1880                 "to bad TSIG"));
 1881             return xfrd_packet_bad;
 1882         }
 1883     }
 1884     if (RCODE(packet) == RCODE_NOTAUTH) {
 1885         return xfrd_packet_drop;
 1886     }
 1887 
 1888     buffer_skip(packet, QHEADERSZ);
 1889     if(qdcount > 64 || ancount > 65530 || nscount > 65530) {
 1890         /* 0 or 1 question section rr, and 64k limits other counts */
 1891         DEBUG(DEBUG_XFRD,1, (LOG_ERR, "dropping xfr reply, impossibly "
 1892             "high record count"));
 1893         return xfrd_packet_bad;
 1894     }
 1895 
 1896     /* skip question section */
 1897     for(rr_count = 0; rr_count < qdcount; ++rr_count) {
 1898         if (!packet_skip_rr(packet, 1)) {
 1899             log_msg(LOG_ERR, "xfrd: zone %s, from %s: bad RR in "
 1900                              "question section",
 1901                 zone->apex_str, zone->master->ip_address_spec);
 1902             return xfrd_packet_bad;
 1903         }
 1904     }
 1905     if(zone->msg_rr_count == 0 && ancount == 0) {
 1906         if(zone->tcp_conn == -1 && TC(packet)) {
 1907             DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: TC flagged"));
 1908             return xfrd_packet_tcp;
 1909         }
 1910         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: too short xfr packet: no "
 1911                                        "answer"));
 1912         /* if IXFR is unknown, fallback to AXFR (if allowed) */
 1913         if (nscount == 1) {
 1914             if(!packet_skip_dname(packet) || !xfrd_parse_soa_info(packet, soa)) {
 1915                 DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
 1916                     "no SOA begins authority section",
 1917                     zone->apex_str, zone->master->ip_address_spec));
 1918                 return xfrd_packet_bad;
 1919             }
 1920             return xfrd_packet_notimpl;
 1921         }
 1922         return xfrd_packet_bad;
 1923     }
 1924     ancount_todo = ancount;
 1925 
 1926     tempregion = region_create(xalloc, free);
 1927     if(zone->msg_rr_count == 0) {
 1928         const dname_type* soaname = dname_make_from_packet(tempregion,
 1929             packet, 1, 1);
 1930         if(!soaname) { /* parse failure */
 1931             DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
 1932                 "parse error in SOA record",
 1933                 zone->apex_str, zone->master->ip_address_spec));
 1934             region_destroy(tempregion);
 1935             return xfrd_packet_bad;
 1936         }
 1937         if(dname_compare(soaname, zone->apex) != 0) { /* wrong name */
 1938             DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
 1939                 "wrong SOA record",
 1940                 zone->apex_str, zone->master->ip_address_spec));
 1941             region_destroy(tempregion);
 1942             return xfrd_packet_bad;
 1943         }
 1944 
 1945         /* parse the first RR, see if it is a SOA */
 1946         if(!xfrd_parse_soa_info(packet, soa))
 1947         {
 1948             DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
 1949                               "bad SOA rdata",
 1950                 zone->apex_str, zone->master->ip_address_spec));
 1951             region_destroy(tempregion);
 1952             return xfrd_packet_bad;
 1953         }
 1954         if(zone->soa_disk_acquired != 0 &&
 1955             zone->state != xfrd_zone_expired /* if expired - accept anything */ &&
 1956             compare_serial(ntohl(soa->serial), ntohl(zone->soa_disk.serial)) < 0) {
 1957                         DEBUG(DEBUG_XFRD,1, (LOG_INFO,
 1958                                 "xfrd: zone %s ignoring old serial (%u/%u) from %s",
 1959                                 zone->apex_str, ntohl(zone->soa_disk.serial), ntohl(soa->serial), zone->master->ip_address_spec));
 1960                         VERBOSITY(1, (LOG_INFO,
 1961                                 "xfrd: zone %s ignoring old serial (%u/%u) from %s",
 1962                                 zone->apex_str, ntohl(zone->soa_disk.serial), ntohl(soa->serial), zone->master->ip_address_spec));
 1963             region_destroy(tempregion);
 1964             return xfrd_packet_bad;
 1965         }
 1966         if(zone->soa_disk_acquired != 0 && zone->soa_disk.serial == soa->serial) {
 1967             DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s got "
 1968                                "update indicating "
 1969                                "current serial",
 1970                 zone->apex_str));
 1971             /* (even if notified) the lease on the current soa is renewed */
 1972             zone->soa_disk_acquired = xfrd_time();
 1973             if(zone->soa_nsd.serial == soa->serial)
 1974                 zone->soa_nsd_acquired = xfrd_time();
 1975             xfrd_set_zone_state(zone, xfrd_zone_ok);
 1976             DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s is ok",
 1977                 zone->apex_str));
 1978             if(zone->zone_options->pattern->multi_master_check) {
 1979                 region_destroy(tempregion);
 1980                 return xfrd_packet_drop;
 1981             }
 1982             if(zone->soa_notified_acquired == 0) {
 1983                 /* not notified or anything, so stop asking around */
 1984                 zone->round_num = -1; /* next try start a new round */
 1985                 xfrd_set_timer_refresh(zone);
 1986                 region_destroy(tempregion);
 1987                 return xfrd_packet_newlease;
 1988             }
 1989             /* try next master */
 1990             region_destroy(tempregion);
 1991             return xfrd_packet_drop;
 1992         }
 1993         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "IXFR reply has ok serial (have \
 1994 %u, reply %u).", (unsigned)ntohl(zone->soa_disk.serial), (unsigned)ntohl(soa->serial)));
 1995         /* serial is newer than soa_disk */
 1996         if(ancount == 1) {
 1997             /* single record means it is like a notify */
 1998             (void)xfrd_handle_incoming_notify(zone, soa);
 1999         }
 2000         else if(zone->soa_notified_acquired && zone->soa_notified.serial &&
 2001             compare_serial(ntohl(zone->soa_notified.serial), ntohl(soa->serial)) < 0) {
 2002             /* this AXFR/IXFR notifies me that an even newer serial exists */
 2003             zone->soa_notified.serial = soa->serial;
 2004         }
 2005         zone->msg_new_serial = ntohl(soa->serial);
 2006         zone->msg_rr_count = 1;
 2007         zone->msg_is_ixfr = 0;
 2008         if(zone->soa_disk_acquired)
 2009             zone->msg_old_serial = ntohl(zone->soa_disk.serial);
 2010         else zone->msg_old_serial = 0;
 2011         ancount_todo = ancount - 1;
 2012     }
 2013 
 2014     if(zone->tcp_conn == -1 && TC(packet)) {
 2015         DEBUG(DEBUG_XFRD,1, (LOG_INFO,
 2016             "xfrd: zone %s received TC from %s. retry tcp.",
 2017             zone->apex_str, zone->master->ip_address_spec));
 2018         region_destroy(tempregion);
 2019         return xfrd_packet_tcp;
 2020     }
 2021 
 2022     if(zone->tcp_conn == -1 && ancount < 2) {
 2023         /* too short to be a real ixfr/axfr data transfer: need at */
 2024         /* least two RRs in the answer section. */
 2025         /* The serial is newer, so try tcp to this master. */
 2026         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: udp reply is short. Try "
 2027                                        "tcp anyway."));
 2028         region_destroy(tempregion);
 2029         return xfrd_packet_tcp;
 2030     }
 2031 
 2032     if(!xfrd_xfr_check_rrs(zone, packet, ancount_todo, &done, soa,
 2033         tempregion))
 2034     {
 2035         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s sent bad xfr "
 2036                                        "reply.", zone->apex_str));
 2037         region_destroy(tempregion);
 2038         return xfrd_packet_bad;
 2039     }
 2040     region_destroy(tempregion);
 2041     if(zone->tcp_conn == -1 && done == 0) {
 2042         DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: udp reply incomplete"));
 2043         return xfrd_packet_bad;
 2044     }
 2045     if(done == 0)
 2046         return xfrd_packet_more;
 2047     if(zone->master->key_options) {
 2048         if(zone->tsig.updates_since_last_prepare != 0) {
 2049             log_msg(LOG_INFO, "xfrd: last packet of reply has no "
 2050                               "TSIG");
 2051             return xfrd_packet_bad;
 2052         }
 2053     }
 2054     return xfrd_packet_transfer;
 2055 }
 2056 
 2057 const char*
 2058 xfrd_pretty_time(time_t v)
 2059 {
 2060     struct tm* tm = localtime(&v);
 2061     static char buf[64];
 2062     if(!strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", tm))
 2063         snprintf(buf, sizeof(buf), "strftime-err-%u", (unsigned)v);
 2064     return buf;
 2065 }
 2066 
 2067 enum xfrd_packet_result
 2068 xfrd_handle_received_xfr_packet(xfrd_zone_type* zone, buffer_type* packet)
 2069 {
 2070     xfrd_soa_type soa;
 2071     enum xfrd_packet_result res;
 2072         uint64_t xfrfile_size;
 2073 
 2074     /* parse and check the packet - see if it ends the xfr */
 2075     switch((res=xfrd_parse_received_xfr_packet(zone, packet, &soa)))
 2076     {
 2077         case xfrd_packet_more:
 2078         case xfrd_packet_transfer:
 2079             /* continue with commit */
 2080             break;
 2081         case xfrd_packet_newlease:
 2082             return xfrd_packet_newlease;
 2083         case xfrd_packet_tcp:
 2084             return xfrd_packet_tcp;
 2085         case xfrd_packet_notimpl:
 2086         case xfrd_packet_bad:
 2087         case xfrd_packet_drop:
 2088         default:
 2089         {
 2090             /* rollback */
 2091             if(zone->msg_seq_nr > 0) {
 2092                 /* do not process xfr - if only one part simply ignore it. */
 2093                 /* delete file with previous parts of commit */
 2094                 xfrd_unlink_xfrfile(xfrd->nsd, zone->xfrfilenumber);
 2095                 VERBOSITY(1, (LOG_INFO, "xfrd: zone %s "
 2096                     "reverted transfer %u from %s",
 2097                     zone->apex_str, zone->msg_rr_count?
 2098                     (int)zone->msg_new_serial:0,
 2099                     zone->master->ip_address_spec));
 2100                 zone->msg_seq_nr = 0;
 2101             } else if (res == xfrd_packet_bad) {
 2102                 VERBOSITY(1, (LOG_INFO, "xfrd: zone %s "
 2103                     "bad transfer %u from %s",
 2104                     zone->apex_str, zone->msg_rr_count?
 2105                     (int)zone->msg_new_serial:0,
 2106                     zone->master->ip_address_spec));
 2107             }
 2108             if (res == xfrd_packet_notimpl
 2109                 && zone->query_type == TYPE_IXFR)
 2110                 return res;
 2111             else
 2112                 return xfrd_packet_bad;
 2113         }
 2114     }
 2115 
 2116     /* dump reply on disk to diff file */
 2117     /* if first part, get new filenumber.  Numbers can wrap around, 64bit
 2118      * is enough so we do not collide with older-transfers-in-progress */
 2119     if(zone->msg_seq_nr == 0)
 2120         zone->xfrfilenumber = xfrd->xfrfilenumber++;
 2121     diff_write_packet(dname_to_string(zone->apex,0),
 2122         zone->zone_options->pattern->pname,
 2123         zone->msg_old_serial, zone->msg_new_serial, zone->msg_seq_nr,
 2124         buffer_begin(packet), buffer_limit(packet), xfrd->nsd,
 2125         zone->xfrfilenumber);
 2126     VERBOSITY(3, (LOG_INFO,
 2127         "xfrd: zone %s written received XFR packet from %s with serial %u to "
 2128         "disk", zone->apex_str, zone->master->ip_address_spec,
 2129         (int)zone->msg_new_serial));
 2130     zone->msg_seq_nr++;
 2131 
 2132         xfrfile_size = xfrd_get_xfrfile_size(xfrd->nsd, zone->xfrfilenumber);
 2133     if( zone->zone_options->pattern->size_limit_xfr != 0 &&
 2134         xfrfile_size > zone->zone_options->pattern->size_limit_xfr ) {
 2135             /*      xfrd_unlink_xfrfile(xfrd->nsd, zone->xfrfilenumber);
 2136                     xfrd_set_reload_timeout(); */
 2137             log_msg(LOG_INFO, "xfrd : transferred zone data was too large %llu", (long long unsigned)xfrfile_size);
 2138         return xfrd_packet_bad;
 2139     }
 2140     if(res == xfrd_packet_more) {
 2141         /* wait for more */
 2142         return xfrd_packet_more;
 2143     }
 2144 
 2145     /* done. we are completely sure of this */
 2146     buffer_clear(packet);
 2147     buffer_printf(packet, "received update to serial %u at %s from %s",
 2148         (unsigned)zone->msg_new_serial, xfrd_pretty_time(xfrd_time()),
 2149         zone->master->ip_address_spec);
 2150     if(zone->master->key_options) {
 2151         buffer_printf(packet, " TSIG verified with key %s",
 2152             zone->master->key_options->name);
 2153     }
 2154     buffer_flip(packet);
 2155     diff_write_commit(zone->apex_str, zone->msg_old_serial,
 2156         zone->msg_new_serial, zone->msg_seq_nr, 1,
 2157         (char*)buffer_begin(packet), xfrd->nsd, zone->xfrfilenumber);
 2158     VERBOSITY(1, (LOG_INFO, "xfrd: zone %s committed \"%s\"",
 2159         zone->apex_str, (char*)buffer_begin(packet)));
 2160     /* reset msg seq nr, so if that is nonnull we know xfr file exists */
 2161     zone->msg_seq_nr = 0;
 2162     /* now put apply_xfr task on the tasklist */
 2163     if(!task_new_apply_xfr(xfrd->nsd->task[xfrd->nsd->mytask],
 2164         xfrd->last_task, zone->apex, zone->msg_old_serial,
 2165         zone->msg_new_serial, zone->xfrfilenumber)) {
 2166         /* delete the file and pretend transfer was bad to continue */
 2167         xfrd_unlink_xfrfile(xfrd->nsd, zone->xfrfilenumber);
 2168         xfrd_set_reload_timeout();
 2169         return xfrd_packet_bad;
 2170     }
 2171     /* update the disk serial no. */
 2172     zone->soa_disk_acquired = xfrd_time();
 2173     zone->soa_disk = soa;
 2174     if(zone->soa_notified_acquired && (
 2175         zone->soa_notified.serial == 0 ||
 2176         compare_serial(htonl(zone->soa_disk.serial),
 2177         htonl(zone->soa_notified.serial)) >= 0))
 2178     {
 2179         zone->soa_notified_acquired = 0;
 2180     }
 2181     if(!zone->soa_notified_acquired) {
 2182         /* do not set expired zone to ok:
 2183          * it would cause nsd to start answering
 2184          * bad data, since the zone is not loaded yet.
 2185          * if nsd does not reload < retry time, more
 2186          * queries (for even newer versions) are made.
 2187          * For expired zone after reload it is set ok (SOAINFO ipc). */
 2188         if(zone->state != xfrd_zone_expired)
 2189             xfrd_set_zone_state(zone, xfrd_zone_ok);
 2190         DEBUG(DEBUG_XFRD,1, (LOG_INFO,
 2191             "xfrd: zone %s is waiting for reload",
 2192             zone->apex_str));
 2193         if(zone->zone_options->pattern->multi_master_check) {
 2194             zone->multi_master_update_check = zone->master_num;
 2195             xfrd_set_reload_timeout();
 2196             return xfrd_packet_transfer;
 2197         }
 2198         zone->round_num = -1; /* next try start anew */
 2199         xfrd_set_timer_refresh(zone);
 2200         xfrd_set_reload_timeout();
 2201         return xfrd_packet_transfer;
 2202     } else {
 2203         /* try to get an even newer serial */
 2204         /* pretend it was bad to continue queries */
 2205         xfrd_set_reload_timeout();
 2206         return xfrd_packet_bad;
 2207     }
 2208 }
 2209 
 2210 static void
 2211 xfrd_set_reload_timeout()
 2212 {
 2213     if(xfrd->nsd->options->xfrd_reload_timeout == -1)
 2214         return; /* automatic reload disabled. */
 2215     if(xfrd->reload_timeout.tv_sec == 0 ||
 2216         xfrd_time() >= (time_t)xfrd->reload_timeout.tv_sec ) {
 2217         /* no reload wait period (or it passed), do it right away */
 2218         xfrd_set_reload_now(xfrd);
 2219         /* start reload wait period */
 2220         xfrd->reload_timeout.tv_sec = xfrd_time() +
 2221             xfrd->nsd->options->xfrd_reload_timeout;
 2222         xfrd->reload_timeout.tv_usec = 0;
 2223         return;
 2224     }
 2225     /* cannot reload now, set that after the timeout a reload has to happen */
 2226     if(xfrd->reload_added == 0) {
 2227         struct timeval tv;
 2228         tv.tv_sec = xfrd->reload_timeout.tv_sec - xfrd_time();
 2229         tv.tv_usec = 0;
 2230         if(tv.tv_sec > xfrd->nsd->options->xfrd_reload_timeout)
 2231             tv.tv_sec = xfrd->nsd->options->xfrd_reload_timeout;
 2232         memset(&xfrd->reload_handler, 0, sizeof(xfrd->reload_handler));
 2233         event_set(&xfrd->reload_handler, -1, EV_TIMEOUT,
 2234             xfrd_handle_reload, xfrd);
 2235         if(event_base_set(xfrd->event_base, &xfrd->reload_handler) != 0)
 2236             log_msg(LOG_ERR, "cannot set reload event base");
 2237         if(event_add(&xfrd->reload_handler, &tv) != 0)
 2238             log_msg(LOG_ERR, "cannot add reload event");
 2239         xfrd->reload_added = 1;
 2240     }
 2241 }
 2242 
 2243 static void
 2244 xfrd_handle_reload(int ATTR_UNUSED(fd), short event, void* ATTR_UNUSED(arg))
 2245 {
 2246     /* reload timeout */
 2247     assert(event & EV_TIMEOUT);
 2248     (void)event;
 2249     /* timeout wait period after this request is sent */
 2250     xfrd->reload_added = 0;
 2251     xfrd->reload_timeout.tv_sec = xfrd_time() +
 2252         xfrd->nsd->options->xfrd_reload_timeout;
 2253     xfrd_set_reload_now(xfrd);
 2254 }
 2255 
 2256 void
 2257 xfrd_handle_notify_and_start_xfr(xfrd_zone_type* zone, xfrd_soa_type* soa)
 2258 {
 2259     if(xfrd_handle_incoming_notify(zone, soa)) {
 2260         if(zone->zone_handler.ev_fd == -1 && zone->tcp_conn == -1 &&
 2261             !zone->tcp_waiting && !zone->udp_waiting) {
 2262             xfrd_set_refresh_now(zone);
 2263         }
 2264         /* zones with no content start expbackoff again; this is also
 2265          * for nsd-control started transfer commands, and also when
 2266          * the master apparently sends notifies (is back up) */
 2267         if(zone->soa_disk_acquired == 0)
 2268             zone->fresh_xfr_timeout = XFRD_TRANSFER_TIMEOUT_START;
 2269     }
 2270 }
 2271 
 2272 void
 2273 xfrd_handle_passed_packet(buffer_type* packet,
 2274     int acl_num, int acl_num_xfr)
 2275 {
 2276     uint8_t qnamebuf[MAXDOMAINLEN];
 2277     uint16_t qtype, qclass;
 2278     const dname_type* dname;
 2279     region_type* tempregion = region_create(xalloc, free);
 2280     xfrd_zone_type* zone;
 2281 
 2282     buffer_skip(packet, QHEADERSZ);
 2283     if(!packet_read_query_section(packet, qnamebuf, &qtype, &qclass)) {
 2284         region_destroy(tempregion);
 2285         return; /* drop bad packet */
 2286     }
 2287 
 2288     dname = dname_make(tempregion, qnamebuf, 1);
 2289     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: got passed packet for %s, acl "
 2290            "%d", dname_to_string(dname,0), acl_num));
 2291 
 2292     /* find the zone */
 2293     zone = (xfrd_zone_type*)rbtree_search(xfrd->zones, dname);
 2294     if(!zone) {
 2295         /* this could be because the zone has been deleted meanwhile */
 2296         DEBUG(DEBUG_XFRD, 1, (LOG_INFO, "xfrd: incoming packet for "
 2297             "unknown zone %s", dname_to_string(dname,0)));
 2298         region_destroy(tempregion);
 2299         return; /* drop packet for unknown zone */
 2300     }
 2301     region_destroy(tempregion);
 2302 
 2303     /* handle */
 2304     if(OPCODE(packet) == OPCODE_NOTIFY) {
 2305         xfrd_soa_type soa;
 2306         int have_soa = 0;
 2307         int next;
 2308         /* get serial from a SOA */
 2309         if(ANCOUNT(packet) == 1 && packet_skip_dname(packet) &&
 2310             xfrd_parse_soa_info(packet, &soa)) {
 2311                 have_soa = 1;
 2312         }
 2313         xfrd_handle_notify_and_start_xfr(zone, have_soa?&soa:NULL);
 2314         /* First, see if our notifier has a match in provide-xfr */
 2315         if (acl_find_num(zone->zone_options->pattern->request_xfr,
 2316                 acl_num_xfr))
 2317             next = acl_num_xfr;
 2318         else /* If not, find master that matches notifiers ACL entry */
 2319             next = find_same_master_notify(zone, acl_num);
 2320         if(next != -1) {
 2321             zone->next_master = next;
 2322             DEBUG(DEBUG_XFRD,1, (LOG_INFO,
 2323                 "xfrd: notify set next master to query %d",
 2324                 next));
 2325         }
 2326     }
 2327     else {
 2328         /* ignore other types of messages */
 2329     }
 2330 }
 2331 
 2332 static int
 2333 xfrd_handle_incoming_notify(xfrd_zone_type* zone, xfrd_soa_type* soa)
 2334 {
 2335     if(soa && zone->soa_disk_acquired && zone->state != xfrd_zone_expired &&
 2336        compare_serial(ntohl(soa->serial),ntohl(zone->soa_disk.serial)) <= 0)
 2337     {
 2338         DEBUG(DEBUG_XFRD,1, (LOG_INFO,
 2339             "xfrd: ignored notify %s %u old serial, zone valid "
 2340             "(soa disk serial %u)", zone->apex_str,
 2341             (unsigned)ntohl(soa->serial),
 2342             (unsigned)ntohl(zone->soa_disk.serial)));
 2343         return 0; /* ignore notify with old serial, we have a valid zone */
 2344     }
 2345     if(soa == 0) {
 2346         zone->soa_notified.serial = 0;
 2347     }
 2348     else if (zone->soa_notified_acquired == 0 ||
 2349          zone->soa_notified.serial == 0 ||
 2350          compare_serial(ntohl(soa->serial),
 2351             ntohl(zone->soa_notified.serial)) > 0)
 2352     {
 2353         zone->soa_notified = *soa;
 2354     }
 2355     zone->soa_notified_acquired = xfrd_time();
 2356     if(zone->state == xfrd_zone_ok) {
 2357         xfrd_set_zone_state(zone, xfrd_zone_refreshing);
 2358     }
 2359     /* transfer right away */
 2360     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "Handle incoming notify for zone %s",
 2361         zone->apex_str));
 2362     return 1;
 2363 }
 2364 
 2365 static int
 2366 find_same_master_notify(xfrd_zone_type* zone, int acl_num_nfy)
 2367 {
 2368     struct acl_options* nfy_acl = acl_find_num(zone->zone_options->pattern->
 2369         allow_notify, acl_num_nfy);
 2370     int num = 0;
 2371     struct acl_options* master = zone->zone_options->pattern->request_xfr;
 2372     if(!nfy_acl)
 2373         return -1;
 2374     while(master)
 2375     {
 2376         if(acl_addr_matches_host(nfy_acl, master))
 2377             return num;
 2378         master = master->next;
 2379         num++;
 2380     }
 2381     return -1;
 2382 }
 2383 
 2384 void
 2385 xfrd_check_failed_updates()
 2386 {
 2387     /* see if updates have not come through */
 2388     xfrd_zone_type* zone;
 2389     RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones)
 2390     {
 2391         /* zone has a disk soa, and no nsd soa or a different nsd soa */
 2392         if(zone->soa_disk_acquired != 0 &&
 2393             (zone->soa_nsd_acquired == 0 ||
 2394             zone->soa_disk.serial != zone->soa_nsd.serial))
 2395         {
 2396             if(zone->soa_disk_acquired <
 2397                 xfrd->reload_cmd_last_sent)
 2398             {
 2399                 /* this zone should have been loaded, since its disk
 2400                    soa time is before the time of the reload cmd. */
 2401                 xfrd_soa_type dumped_soa = zone->soa_disk;
 2402                 log_msg(LOG_ERR, "xfrd: zone %s: soa serial %u "
 2403                                  "update failed, restarting "
 2404                                  "transfer (notified zone)",
 2405                     zone->apex_str, (unsigned)ntohl(zone->soa_disk.serial));
 2406                 /* revert the soa; it has not been acquired properly */
 2407                 if(zone->soa_disk_acquired == zone->soa_nsd_acquired) {
 2408                     /* this was the same as served,
 2409                      * perform force_axfr , re-download
 2410                      * same serial from master */
 2411                     zone->soa_disk_acquired = 0;
 2412                     zone->soa_nsd_acquired = 0;
 2413                 } else {
 2414                     /* revert soa to the one in server */
 2415                     zone->soa_disk_acquired = zone->soa_nsd_acquired;
 2416                     zone->soa_disk = zone->soa_nsd;
 2417                 }
 2418                 /* pretend we are notified with disk soa.
 2419                    This will cause a refetch of the data, and reload. */
 2420                 xfrd_handle_incoming_notify(zone, &dumped_soa);
 2421                 xfrd_set_timer_refresh(zone);
 2422             } else if(zone->soa_disk_acquired >= xfrd->reload_cmd_last_sent) {
 2423                 /* this zone still has to be loaded,
 2424                    make sure reload is set to be sent. */
 2425                 if(xfrd->need_to_send_reload == 0 &&
 2426                     xfrd->reload_added == 0) {
 2427                     log_msg(LOG_ERR, "xfrd: zone %s: needs "
 2428                                      "to be loaded. reload lost? "
 2429                                      "try again", zone->apex_str);
 2430                     xfrd_set_reload_timeout();
 2431                 }
 2432             }
 2433         }
 2434     }
 2435 }
 2436 
 2437 void
 2438 xfrd_prepare_zones_for_reload()
 2439 {
 2440     xfrd_zone_type* zone;
 2441     RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones)
 2442     {
 2443         /* zone has a disk soa, and no nsd soa or a different nsd soa */
 2444         if(zone->soa_disk_acquired != 0 &&
 2445             (zone->soa_nsd_acquired == 0 ||
 2446             zone->soa_disk.serial != zone->soa_nsd.serial))
 2447         {
 2448             if(zone->soa_disk_acquired == xfrd_time()) {
 2449                 /* antedate by one second.
 2450                  * this makes sure that the zone time is before
 2451                  * reload, so that check_failed_zones() is
 2452                  * certain of the result.
 2453                  */
 2454                 zone->soa_disk_acquired--;
 2455             }
 2456         }
 2457     }
 2458 }
 2459 
 2460 struct buffer*
 2461 xfrd_get_temp_buffer()
 2462 {
 2463     return xfrd->packet;
 2464 }
 2465 
 2466 #ifdef BIND8_STATS
 2467 /** process stat info task */
 2468 static void
 2469 xfrd_process_stat_info_task(xfrd_state_type* xfrd, struct task_list_d* task)
 2470 {
 2471     size_t i;
 2472     stc_type* p = (void*)((char*)task->zname + sizeof(struct nsdst));
 2473     stats_add(&xfrd->nsd->st, (struct nsdst*)task->zname);
 2474     for(i=0; i<xfrd->nsd->child_count; i++) {
 2475         xfrd->nsd->children[i].query_count += *p++;
 2476     }
 2477     /* got total, now see if users are interested in these statistics */
 2478 #ifdef HAVE_SSL
 2479     daemon_remote_process_stats(xfrd->nsd->rc);
 2480 #endif
 2481 }
 2482 #endif /* BIND8_STATS */
 2483 
 2484 #ifdef USE_ZONE_STATS
 2485 /** process zonestat inc task */
 2486 static void
 2487 xfrd_process_zonestat_inc_task(xfrd_state_type* xfrd, struct task_list_d* task)
 2488 {
 2489     xfrd->zonestat_safe = (unsigned)task->oldserial;
 2490     zonestat_remap(xfrd->nsd, 0, xfrd->zonestat_safe*sizeof(struct nsdst));
 2491     xfrd->nsd->zonestatsize[0] = xfrd->zonestat_safe;
 2492     zonestat_remap(xfrd->nsd, 1, xfrd->zonestat_safe*sizeof(struct nsdst));
 2493     xfrd->nsd->zonestatsize[1] = xfrd->zonestat_safe;
 2494 }
 2495 #endif /* USE_ZONE_STATS */
 2496 
 2497 static void
 2498 xfrd_handle_taskresult(xfrd_state_type* xfrd, struct task_list_d* task)
 2499 {
 2500 #ifndef BIND8_STATS
 2501     (void)xfrd;
 2502 #endif
 2503     switch(task->task_type) {
 2504     case task_soa_info:
 2505         xfrd_process_soa_info_task(task);
 2506         break;
 2507 #ifdef BIND8_STATS
 2508     case task_stat_info:
 2509         xfrd_process_stat_info_task(xfrd, task);
 2510         break;
 2511 #endif /* BIND8_STATS */
 2512 #ifdef USE_ZONE_STATS
 2513     case task_zonestat_inc:
 2514         xfrd_process_zonestat_inc_task(xfrd, task);
 2515         break;
 2516 #endif
 2517     default:
 2518         log_msg(LOG_WARNING, "unhandled task result in xfrd from "
 2519             "reload type %d", (int)task->task_type);
 2520     }
 2521 }
 2522 
 2523 void xfrd_process_task_result(xfrd_state_type* xfrd, struct udb_base* taskudb)
 2524 {
 2525     udb_ptr t;
 2526     /* remap it for usage */
 2527     task_remap(taskudb);
 2528     /* process the task-results in the taskudb */
 2529     udb_ptr_new(&t, taskudb, udb_base_get_userdata(taskudb));
 2530     while(!udb_ptr_is_null(&t)) {
 2531         xfrd_handle_taskresult(xfrd, TASKLIST(&t));
 2532         udb_ptr_set_rptr(&t, taskudb, &TASKLIST(&t)->next);
 2533     }
 2534     udb_ptr_unlink(&t, taskudb);
 2535     /* clear the udb so it can be used by xfrd to make new tasks for
 2536      * reload, this happens when the reload signal is sent, and thus
 2537      * the taskudbs are swapped */
 2538     task_clear(taskudb);
 2539 #ifdef HAVE_SYSTEMD
 2540     sd_notify(0, "READY=1");
 2541 #endif
 2542 }
 2543 
 2544 void xfrd_set_reload_now(xfrd_state_type* xfrd)
 2545 {
 2546 #ifdef HAVE_SYSTEMD
 2547     sd_notify(0, "RELOADING=1");
 2548 #endif
 2549     xfrd->need_to_send_reload = 1;
 2550     if(!(xfrd->ipc_handler_flags&EV_WRITE)) {
 2551         ipc_xfrd_set_listening(xfrd, EV_PERSIST|EV_READ|EV_WRITE);
 2552     }
 2553 }
 2554 
 2555 static void
 2556 xfrd_handle_write_timer(int ATTR_UNUSED(fd), short event, void* ATTR_UNUSED(arg))
 2557 {
 2558     /* timeout for write events */
 2559     assert(event & EV_TIMEOUT);
 2560     (void)event;
 2561     if(xfrd->nsd->options->zonefiles_write == 0)
 2562         return;
 2563     /* call reload to write changed zonefiles */
 2564     if(!xfrd->write_zonefile_needed) {
 2565         DEBUG(DEBUG_XFRD,2, (LOG_INFO, "zonefiles write timer (nothing)"));
 2566         xfrd_write_timer_set();
 2567         return;
 2568     }
 2569     DEBUG(DEBUG_XFRD,1, (LOG_INFO, "zonefiles write timer"));
 2570     task_new_write_zonefiles(xfrd->nsd->task[xfrd->nsd->mytask],
 2571         xfrd->last_task, NULL);
 2572     xfrd_set_reload_now(xfrd);
 2573     xfrd->write_zonefile_needed = 0;
 2574     xfrd_write_timer_set();
 2575 }
 2576 
 2577 static void xfrd_write_timer_set()
 2578 {
 2579     struct timeval tv;
 2580     if(xfrd->nsd->options->zonefiles_write == 0)
 2581         return;
 2582     tv.tv_sec = xfrd->nsd->options->zonefiles_write;
 2583     tv.tv_usec = 0;
 2584     memset(&xfrd->write_timer, 0, sizeof(xfrd->write_timer));
 2585     event_set(&xfrd->write_timer, -1, EV_TIMEOUT,
 2586         xfrd_handle_write_timer, xfrd);
 2587     if(event_base_set(xfrd->event_base, &xfrd->write_timer) != 0)
 2588         log_msg(LOG_ERR, "xfrd write timer: event_base_set failed");
 2589     if(event_add(&xfrd->write_timer, &tv) != 0)
 2590         log_msg(LOG_ERR, "xfrd write timer: event_add failed");
 2591 }
 2592 
 2593 static void xfrd_handle_child_timer(int ATTR_UNUSED(fd), short event,
 2594     void* ATTR_UNUSED(arg))
 2595 {
 2596     assert(event & EV_TIMEOUT);
 2597     (void)event;
 2598     /* only used to wakeup the process to reap children, note the
 2599      * event is no longer registered */
 2600     xfrd->child_timer_added = 0;
 2601 }